blob: 8372dbb856da33d78ae185574a4476082695e4fd [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060050}
John Kessenich140f3df2015-06-26 16:58:36 -060051
52// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020053#include "../glslang/MachineIndependent/localintermediate.h"
54#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060055#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050056#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060057
John Kessenich140f3df2015-06-26 16:58:36 -060058#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040060#include <list>
61#include <map>
62#include <stack>
63#include <string>
64#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060065
66namespace {
67
John Kessenich55e7d112015-11-15 21:33:39 -070068// For low-order part of the generator's magic number. Bump up
69// when there is a change in the style (e.g., if SSA form changes,
70// or a different instruction sequence to do something gets used).
71const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060072
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
92}
93
John Kessenich140f3df2015-06-26 16:58:36 -060094//
95// The main holder of information for translating glslang to SPIR-V.
96//
97// Derives from the AST walking base class.
98//
99class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
100public:
Lei Zhang17535f72016-05-04 15:55:59 -0400101 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600102 virtual ~TGlslangToSpvTraverser();
103
104 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
105 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
106 void visitConstantUnion(glslang::TIntermConstantUnion*);
107 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
108 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
109 void visitSymbol(glslang::TIntermSymbol* symbol);
110 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
111 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
112 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
113
John Kessenich7ba63412015-12-20 17:37:07 -0700114 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600115
116protected:
Rex Xubbceed72016-05-21 09:40:44 +0800117 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100118 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700119 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
121 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600122 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
123 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
124 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700126 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600127 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
128 glslang::TLayoutPacking, const glslang::TQualifier&);
129 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
130 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700131 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700132 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800133 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600134 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700135 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700136 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
137 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
138 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100139 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
John Kessenich6fccb3c2016-09-19 16:01:41 -0600141 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 void makeFunctions(const glslang::TIntermSequence&);
143 void makeGlobalInitializers(const glslang::TIntermSequence&);
144 void visitFunctions(const glslang::TIntermSequence&);
145 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800146 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600147 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
148 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600149 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
150
qining25262b32016-05-06 17:25:16 -0400151 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
152 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
153 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800154 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800155 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600156 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800157 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800158 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800159#ifdef AMD_EXTENSIONS
160 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand);
161#endif
John Kessenich5e4b1242015-08-06 22:53:06 -0600162 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800163 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
165 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700166 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700168 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400169 spv::Id createSpvConstant(const glslang::TIntermTyped&);
170 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600171 bool isTrivialLeaf(const glslang::TIntermTyped* node);
172 bool isTrivial(const glslang::TIntermTyped* node);
173 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800174 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600175
176 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700177 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600178 int sequenceDepth;
179
Lei Zhang17535f72016-05-04 15:55:59 -0400180 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400181
John Kessenich140f3df2015-06-26 16:58:36 -0600182 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
183 spv::Builder builder;
184 bool inMain;
185 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700186 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700187 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600188 const glslang::TIntermediate* glslangIntermediate;
189 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800190 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600191
John Kessenich2f273362015-07-18 22:34:27 -0600192 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600193 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600194 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700195 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600196 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600197 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600198};
199
200//
201// Helper functions for translating glslang representations to SPIR-V enumerants.
202//
203
204// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700205spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600206{
John Kessenich66e2faf2016-03-12 18:34:36 -0700207 switch (source) {
208 case glslang::EShSourceGlsl:
209 switch (profile) {
210 case ENoProfile:
211 case ECoreProfile:
212 case ECompatibilityProfile:
213 return spv::SourceLanguageGLSL;
214 case EEsProfile:
215 return spv::SourceLanguageESSL;
216 default:
217 return spv::SourceLanguageUnknown;
218 }
219 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400220 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
221 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600222 default:
223 return spv::SourceLanguageUnknown;
224 }
225}
226
227// Translate glslang language (stage) to SPIR-V execution model.
228spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
229{
230 switch (stage) {
231 case EShLangVertex: return spv::ExecutionModelVertex;
232 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
233 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
234 case EShLangGeometry: return spv::ExecutionModelGeometry;
235 case EShLangFragment: return spv::ExecutionModelFragment;
236 case EShLangCompute: return spv::ExecutionModelGLCompute;
237 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700238 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600239 return spv::ExecutionModelFragment;
240 }
241}
242
243// Translate glslang type to SPIR-V storage class.
244spv::StorageClass TranslateStorageClass(const glslang::TType& type)
245{
246 if (type.getQualifier().isPipeInput())
247 return spv::StorageClassInput;
248 else if (type.getQualifier().isPipeOutput())
249 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700250 else if (type.getBasicType() == glslang::EbtSampler)
251 return spv::StorageClassUniformConstant;
252 else if (type.getBasicType() == glslang::EbtAtomicUint)
253 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600254 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700255 if (type.getQualifier().layoutPushConstant)
256 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600257 if (type.getBasicType() == glslang::EbtBlock)
258 return spv::StorageClassUniform;
259 else
260 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600261 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600262 } else {
263 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700264 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
265 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
267 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400268 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700269 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600270 return spv::StorageClassFunction;
271 }
272 }
273}
274
275// Translate glslang sampler type to SPIR-V dimensionality.
276spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
277{
278 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700279 case glslang::Esd1D: return spv::Dim1D;
280 case glslang::Esd2D: return spv::Dim2D;
281 case glslang::Esd3D: return spv::Dim3D;
282 case glslang::EsdCube: return spv::DimCube;
283 case glslang::EsdRect: return spv::DimRect;
284 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700285 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700287 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600288 return spv::Dim2D;
289 }
290}
291
John Kessenichf6640762016-08-01 19:44:00 -0600292// Translate glslang precision to SPIR-V precision decorations.
293spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600294{
John Kessenichf6640762016-08-01 19:44:00 -0600295 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700296 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600297 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600298 default:
299 return spv::NoPrecision;
300 }
301}
302
John Kessenichf6640762016-08-01 19:44:00 -0600303// Translate glslang type to SPIR-V precision decorations.
304spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
305{
306 return TranslatePrecisionDecoration(type.getQualifier().precision);
307}
308
John Kessenich140f3df2015-06-26 16:58:36 -0600309// Translate glslang type to SPIR-V block decorations.
310spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
311{
312 if (type.getBasicType() == glslang::EbtBlock) {
313 switch (type.getQualifier().storage) {
314 case glslang::EvqUniform: return spv::DecorationBlock;
315 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
316 case glslang::EvqVaryingIn: return spv::DecorationBlock;
317 case glslang::EvqVaryingOut: return spv::DecorationBlock;
318 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700319 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600320 break;
321 }
322 }
323
John Kessenich4016e382016-07-15 11:53:56 -0600324 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600325}
326
Rex Xu1da878f2016-02-21 20:59:01 +0800327// Translate glslang type to SPIR-V memory decorations.
328void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
329{
330 if (qualifier.coherent)
331 memory.push_back(spv::DecorationCoherent);
332 if (qualifier.volatil)
333 memory.push_back(spv::DecorationVolatile);
334 if (qualifier.restrict)
335 memory.push_back(spv::DecorationRestrict);
336 if (qualifier.readonly)
337 memory.push_back(spv::DecorationNonWritable);
338 if (qualifier.writeonly)
339 memory.push_back(spv::DecorationNonReadable);
340}
341
John Kessenich140f3df2015-06-26 16:58:36 -0600342// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700343spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600344{
345 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700346 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600347 case glslang::ElmRowMajor:
348 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600350 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700351 default:
352 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600353 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 }
355 } else {
356 switch (type.getBasicType()) {
357 default:
John Kessenich4016e382016-07-15 11:53:56 -0600358 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600359 break;
360 case glslang::EbtBlock:
361 switch (type.getQualifier().storage) {
362 case glslang::EvqUniform:
363 case glslang::EvqBuffer:
364 switch (type.getQualifier().layoutPacking) {
365 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600366 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
367 default:
John Kessenich4016e382016-07-15 11:53:56 -0600368 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 }
370 case glslang::EvqVaryingIn:
371 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700372 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600373 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600374 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 }
378 }
379 }
380}
381
382// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600383// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700384// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800385spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600386{
Rex Xubbceed72016-05-21 09:40:44 +0800387 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700388 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800390 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700392 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600393 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800394#ifdef AMD_EXTENSIONS
395 else if (qualifier.explicitInterp)
396 return spv::DecorationExplicitInterpAMD;
397#endif
Rex Xubbceed72016-05-21 09:40:44 +0800398 else
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800400}
401
402// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600403// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800404// should be applied.
405spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
406{
407 if (qualifier.patch)
408 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600410 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700411 else if (qualifier.sample) {
412 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600413 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700414 } else
John Kessenich4016e382016-07-15 11:53:56 -0600415 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600416}
417
John Kessenich92187592016-02-01 13:45:25 -0700418// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700419spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700421 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationInvariant;
423 else
John Kessenich4016e382016-07-15 11:53:56 -0600424 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600425}
426
qining9220dbb2016-05-04 17:34:38 -0400427// If glslang type is noContraction, return SPIR-V NoContraction decoration.
428spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
429{
430 if (qualifier.noContraction)
431 return spv::DecorationNoContraction;
432 else
John Kessenich4016e382016-07-15 11:53:56 -0600433 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400434}
435
David Netoa901ffe2016-06-08 14:11:40 +0100436// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
437// associated capabilities when required. For some built-in variables, a capability
438// is generated only when using the variable in an executable instruction, but not when
439// just declaring a struct member variable with it. This is true for PointSize,
440// ClipDistance, and CullDistance.
441spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600442{
443 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700444 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600445 // Defer adding the capability until the built-in is actually used.
446 if (! memberDeclaration) {
447 switch (glslangIntermediate->getStage()) {
448 case EShLangGeometry:
449 builder.addCapability(spv::CapabilityGeometryPointSize);
450 break;
451 case EShLangTessControl:
452 case EShLangTessEvaluation:
453 builder.addCapability(spv::CapabilityTessellationPointSize);
454 break;
455 default:
456 break;
457 }
John Kessenich92187592016-02-01 13:45:25 -0700458 }
459 return spv::BuiltInPointSize;
460
John Kessenichebb50532016-05-16 19:22:05 -0600461 // These *Distance capabilities logically belong here, but if the member is declared and
462 // then never used, consumers of SPIR-V prefer the capability not be declared.
463 // They are now generated when used, rather than here when declared.
464 // Potentially, the specification should be more clear what the minimum
465 // use needed is to trigger the capability.
466 //
John Kessenich92187592016-02-01 13:45:25 -0700467 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100468 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600469 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700470 return spv::BuiltInClipDistance;
471
472 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600474 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInCullDistance;
476
477 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500478 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700479 return spv::BuiltInViewportIndex;
480
John Kessenich5e801132016-02-15 11:09:46 -0700481 case glslang::EbvSampleId:
482 builder.addCapability(spv::CapabilitySampleRateShading);
483 return spv::BuiltInSampleId;
484
485 case glslang::EbvSamplePosition:
486 builder.addCapability(spv::CapabilitySampleRateShading);
487 return spv::BuiltInSamplePosition;
488
489 case glslang::EbvSampleMask:
490 builder.addCapability(spv::CapabilitySampleRateShading);
491 return spv::BuiltInSampleMask;
492
John Kessenich78a45572016-07-08 14:05:15 -0600493 case glslang::EbvLayer:
494 builder.addCapability(spv::CapabilityGeometry);
495 return spv::BuiltInLayer;
496
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvVertexId: return spv::BuiltInVertexId;
499 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700500 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
501 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
503 case glslang::EbvBaseInstance:
504 case glslang::EbvDrawId:
505 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600506 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600507 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600508 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
509 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600510 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
511 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
512 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
513 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
514 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
515 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
516 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600517 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
518 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
519 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
520 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
521 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
522 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
523 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
524 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800525
Rex Xu574ab042016-04-14 16:53:07 +0800526 case glslang::EbvSubGroupSize:
Rex Xu51596642016-09-21 18:56:12 +0800527 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
528 return spv::BuiltInSubgroupSize;
529
Rex Xu574ab042016-04-14 16:53:07 +0800530 case glslang::EbvSubGroupInvocation:
Rex Xu51596642016-09-21 18:56:12 +0800531 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
532 return spv::BuiltInSubgroupLocalInvocationId;
533
Rex Xu574ab042016-04-14 16:53:07 +0800534 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800535 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
536 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
537 return spv::BuiltInSubgroupEqMaskKHR;
538
Rex Xu574ab042016-04-14 16:53:07 +0800539 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
541 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
542 return spv::BuiltInSubgroupGeMaskKHR;
543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupGtMaskKHR;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupLeMaskKHR;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupLtMaskKHR;
558
Rex Xu9d93a232016-05-05 12:30:44 +0800559#ifdef AMD_EXTENSIONS
560 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
561 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
562 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
563 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
564 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
565 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
566 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
567#endif
John Kessenich4016e382016-07-15 11:53:56 -0600568 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600569 }
570}
571
Rex Xufc618912015-09-09 16:42:49 +0800572// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700573spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800574{
575 assert(type.getBasicType() == glslang::EbtSampler);
576
John Kessenich5d0fa972016-02-15 11:57:00 -0700577 // Check for capabilities
578 switch (type.getQualifier().layoutFormat) {
579 case glslang::ElfRg32f:
580 case glslang::ElfRg16f:
581 case glslang::ElfR11fG11fB10f:
582 case glslang::ElfR16f:
583 case glslang::ElfRgba16:
584 case glslang::ElfRgb10A2:
585 case glslang::ElfRg16:
586 case glslang::ElfRg8:
587 case glslang::ElfR16:
588 case glslang::ElfR8:
589 case glslang::ElfRgba16Snorm:
590 case glslang::ElfRg16Snorm:
591 case glslang::ElfRg8Snorm:
592 case glslang::ElfR16Snorm:
593 case glslang::ElfR8Snorm:
594
595 case glslang::ElfRg32i:
596 case glslang::ElfRg16i:
597 case glslang::ElfRg8i:
598 case glslang::ElfR16i:
599 case glslang::ElfR8i:
600
601 case glslang::ElfRgb10a2ui:
602 case glslang::ElfRg32ui:
603 case glslang::ElfRg16ui:
604 case glslang::ElfRg8ui:
605 case glslang::ElfR16ui:
606 case glslang::ElfR8ui:
607 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
608 break;
609
610 default:
611 break;
612 }
613
614 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800615 switch (type.getQualifier().layoutFormat) {
616 case glslang::ElfNone: return spv::ImageFormatUnknown;
617 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
618 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
619 case glslang::ElfR32f: return spv::ImageFormatR32f;
620 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
621 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
622 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
623 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
624 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
625 case glslang::ElfR16f: return spv::ImageFormatR16f;
626 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
627 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
628 case glslang::ElfRg16: return spv::ImageFormatRg16;
629 case glslang::ElfRg8: return spv::ImageFormatRg8;
630 case glslang::ElfR16: return spv::ImageFormatR16;
631 case glslang::ElfR8: return spv::ImageFormatR8;
632 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
633 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
634 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
635 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
636 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
637 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
638 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
639 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
640 case glslang::ElfR32i: return spv::ImageFormatR32i;
641 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
642 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
643 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
644 case glslang::ElfR16i: return spv::ImageFormatR16i;
645 case glslang::ElfR8i: return spv::ImageFormatR8i;
646 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
647 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
648 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
649 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
650 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
651 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
652 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
653 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
654 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
655 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600656 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800657 }
658}
659
qining25262b32016-05-06 17:25:16 -0400660// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700661// descriptor set.
662bool IsDescriptorResource(const glslang::TType& type)
663{
John Kessenichf7497e22016-03-08 21:36:22 -0700664 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700665 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700666 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700667
668 // non block...
669 // basically samplerXXX/subpass/sampler/texture are all included
670 // if they are the global-scope-class, not the function parameter
671 // (or local, if they ever exist) class.
672 if (type.getBasicType() == glslang::EbtSampler)
673 return type.getQualifier().isUniformOrBuffer();
674
675 // None of the above.
676 return false;
677}
678
John Kesseniche0b6cad2015-12-24 10:30:13 -0700679void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
680{
681 if (child.layoutMatrix == glslang::ElmNone)
682 child.layoutMatrix = parent.layoutMatrix;
683
684 if (parent.invariant)
685 child.invariant = true;
686 if (parent.nopersp)
687 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800688#ifdef AMD_EXTENSIONS
689 if (parent.explicitInterp)
690 child.explicitInterp = true;
691#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700692 if (parent.flat)
693 child.flat = true;
694 if (parent.centroid)
695 child.centroid = true;
696 if (parent.patch)
697 child.patch = true;
698 if (parent.sample)
699 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800700 if (parent.coherent)
701 child.coherent = true;
702 if (parent.volatil)
703 child.volatil = true;
704 if (parent.restrict)
705 child.restrict = true;
706 if (parent.readonly)
707 child.readonly = true;
708 if (parent.writeonly)
709 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700710}
711
John Kessenichf2b7f332016-09-01 17:05:23 -0600712bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700713{
John Kessenich7b9fa252016-01-21 18:56:57 -0700714 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600715 // - struct members might inherit from a struct declaration
716 // (note that non-block structs don't explicitly inherit,
717 // only implicitly, meaning no decoration involved)
718 // - affect decorations on the struct members
719 // (note smooth does not, and expecting something like volatile
720 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700721 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600722 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700723}
724
John Kessenich140f3df2015-06-26 16:58:36 -0600725//
726// Implement the TGlslangToSpvTraverser class.
727//
728
Lei Zhang17535f72016-05-04 15:55:59 -0400729TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
730 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
731 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600732 inMain(false), mainTerminated(false), linkageOnly(false),
733 glslangIntermediate(glslangIntermediate)
734{
735 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
736
737 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700738 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600739 stdBuiltins = builder.import("GLSL.std.450");
740 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600741 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
742 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600743
744 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600745 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
746 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600747 builder.addSourceExtension(it->c_str());
748
749 // Add the top-level modes for this shader.
750
John Kessenich92187592016-02-01 13:45:25 -0700751 if (glslangIntermediate->getXfbMode()) {
752 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600753 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700754 }
John Kessenich140f3df2015-06-26 16:58:36 -0600755
756 unsigned int mode;
757 switch (glslangIntermediate->getStage()) {
758 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600759 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600760 break;
761
762 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600763 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600764 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
765 break;
766
767 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600768 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600769 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700770 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
771 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
772 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600773 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600774 }
John Kessenich4016e382016-07-15 11:53:56 -0600775 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600776 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
777
John Kesseniche6903322015-10-13 16:29:02 -0600778 switch (glslangIntermediate->getVertexSpacing()) {
779 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
780 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
781 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600782 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600783 }
John Kessenich4016e382016-07-15 11:53:56 -0600784 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600785 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
786
787 switch (glslangIntermediate->getVertexOrder()) {
788 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
789 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600790 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600791 }
John Kessenich4016e382016-07-15 11:53:56 -0600792 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600793 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
794
795 if (glslangIntermediate->getPointMode())
796 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600797 break;
798
799 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600800 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600801 switch (glslangIntermediate->getInputPrimitive()) {
802 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
803 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
804 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700805 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600806 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600807 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600808 }
John Kessenich4016e382016-07-15 11:53:56 -0600809 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600810 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600811
John Kessenich140f3df2015-06-26 16:58:36 -0600812 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
813
814 switch (glslangIntermediate->getOutputPrimitive()) {
815 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
816 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
817 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600818 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600819 }
John Kessenich4016e382016-07-15 11:53:56 -0600820 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600821 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
822 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
823 break;
824
825 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600826 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600827 if (glslangIntermediate->getPixelCenterInteger())
828 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600829
John Kessenich140f3df2015-06-26 16:58:36 -0600830 if (glslangIntermediate->getOriginUpperLeft())
831 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600832 else
833 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600834
835 if (glslangIntermediate->getEarlyFragmentTests())
836 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
837
838 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600839 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
840 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600841 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600842 }
John Kessenich4016e382016-07-15 11:53:56 -0600843 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600844 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
845
846 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
847 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600848 break;
849
850 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600851 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600852 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
853 glslangIntermediate->getLocalSize(1),
854 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600855 break;
856
857 default:
858 break;
859 }
860
861}
862
John Kessenich7ba63412015-12-20 17:37:07 -0700863// Finish everything and dump
864void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
865{
866 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100867 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
868 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700869
qiningda397332016-03-09 19:54:03 -0500870 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700871 builder.dump(out);
872}
873
John Kessenich140f3df2015-06-26 16:58:36 -0600874TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
875{
876 if (! mainTerminated) {
877 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
878 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600879 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600880 }
881}
882
883//
884// Implement the traversal functions.
885//
886// Return true from interior nodes to have the external traversal
887// continue on to children. Return false if children were
888// already processed.
889//
890
891//
qining25262b32016-05-06 17:25:16 -0400892// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600893// - uniform/input reads
894// - output writes
895// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
896// - something simple that degenerates into the last bullet
897//
898void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
899{
qining75d1d802016-04-06 14:42:01 -0400900 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
901 if (symbol->getType().getQualifier().isSpecConstant())
902 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
903
John Kessenich140f3df2015-06-26 16:58:36 -0600904 // getSymbolId() will set up all the IO decorations on the first call.
905 // Formal function parameters were mapped during makeFunctions().
906 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700907
908 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
909 if (builder.isPointer(id)) {
910 spv::StorageClass sc = builder.getStorageClass(id);
911 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
912 iOSet.insert(id);
913 }
914
915 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700916 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600917 // Prepare to generate code for the access
918
919 // L-value chains will be computed left to right. We're on the symbol now,
920 // which is the left-most part of the access chain, so now is "clear" time,
921 // followed by setting the base.
922 builder.clearAccessChain();
923
924 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700925 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600926 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700927 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600928 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700929 // These are also pure R-values.
930 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600931 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600932 builder.setAccessChainRValue(id);
933 else
934 builder.setAccessChainLValue(id);
935 }
936}
937
938bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
939{
qining40887662016-04-03 22:20:42 -0400940 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
941 if (node->getType().getQualifier().isSpecConstant())
942 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
943
John Kessenich140f3df2015-06-26 16:58:36 -0600944 // First, handle special cases
945 switch (node->getOp()) {
946 case glslang::EOpAssign:
947 case glslang::EOpAddAssign:
948 case glslang::EOpSubAssign:
949 case glslang::EOpMulAssign:
950 case glslang::EOpVectorTimesMatrixAssign:
951 case glslang::EOpVectorTimesScalarAssign:
952 case glslang::EOpMatrixTimesScalarAssign:
953 case glslang::EOpMatrixTimesMatrixAssign:
954 case glslang::EOpDivAssign:
955 case glslang::EOpModAssign:
956 case glslang::EOpAndAssign:
957 case glslang::EOpInclusiveOrAssign:
958 case glslang::EOpExclusiveOrAssign:
959 case glslang::EOpLeftShiftAssign:
960 case glslang::EOpRightShiftAssign:
961 // A bin-op assign "a += b" means the same thing as "a = a + b"
962 // where a is evaluated before b. For a simple assignment, GLSL
963 // says to evaluate the left before the right. So, always, left
964 // node then right node.
965 {
966 // get the left l-value, save it away
967 builder.clearAccessChain();
968 node->getLeft()->traverse(this);
969 spv::Builder::AccessChain lValue = builder.getAccessChain();
970
971 // evaluate the right
972 builder.clearAccessChain();
973 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700974 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600975
976 if (node->getOp() != glslang::EOpAssign) {
977 // the left is also an r-value
978 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700979 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600980
981 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600982 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400983 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600984 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
985 node->getType().getBasicType());
986
987 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700988 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600989 }
990
991 // store the result
992 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -0600993 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600994
995 // assignments are expressions having an rValue after they are evaluated...
996 builder.clearAccessChain();
997 builder.setAccessChainRValue(rValue);
998 }
999 return false;
1000 case glslang::EOpIndexDirect:
1001 case glslang::EOpIndexDirectStruct:
1002 {
1003 // Get the left part of the access chain.
1004 node->getLeft()->traverse(this);
1005
1006 // Add the next element in the chain
1007
David Netoa901ffe2016-06-08 14:11:40 +01001008 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001009 if (! node->getLeft()->getType().isArray() &&
1010 node->getLeft()->getType().isVector() &&
1011 node->getOp() == glslang::EOpIndexDirect) {
1012 // This is essentially a hard-coded vector swizzle of size 1,
1013 // so short circuit the access-chain stuff with a swizzle.
1014 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001015 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001016 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001017 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001018 int spvIndex = glslangIndex;
1019 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1020 node->getOp() == glslang::EOpIndexDirectStruct)
1021 {
1022 // This may be, e.g., an anonymous block-member selection, which generally need
1023 // index remapping due to hidden members in anonymous blocks.
1024 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1025 assert(remapper.size() > 0);
1026 spvIndex = remapper[glslangIndex];
1027 }
John Kessenichebb50532016-05-16 19:22:05 -06001028
David Netoa901ffe2016-06-08 14:11:40 +01001029 // normal case for indexing array or structure or block
1030 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1031
1032 // Add capabilities here for accessing PointSize and clip/cull distance.
1033 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001034 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001035 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001036 }
1037 }
1038 return false;
1039 case glslang::EOpIndexIndirect:
1040 {
1041 // Structure or array or vector indirection.
1042 // Will use native SPIR-V access-chain for struct and array indirection;
1043 // matrices are arrays of vectors, so will also work for a matrix.
1044 // Will use the access chain's 'component' for variable index into a vector.
1045
1046 // This adapter is building access chains left to right.
1047 // Set up the access chain to the left.
1048 node->getLeft()->traverse(this);
1049
1050 // save it so that computing the right side doesn't trash it
1051 spv::Builder::AccessChain partial = builder.getAccessChain();
1052
1053 // compute the next index in the chain
1054 builder.clearAccessChain();
1055 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001056 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001057
1058 // restore the saved access chain
1059 builder.setAccessChain(partial);
1060
1061 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001062 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001063 else
John Kessenichfa668da2015-09-13 14:46:30 -06001064 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001065 }
1066 return false;
1067 case glslang::EOpVectorSwizzle:
1068 {
1069 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001070 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001071 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001072 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001073 }
1074 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001075 case glslang::EOpLogicalOr:
1076 case glslang::EOpLogicalAnd:
1077 {
1078
1079 // These may require short circuiting, but can sometimes be done as straight
1080 // binary operations. The right operand must be short circuited if it has
1081 // side effects, and should probably be if it is complex.
1082 if (isTrivial(node->getRight()->getAsTyped()))
1083 break; // handle below as a normal binary operation
1084 // otherwise, we need to do dynamic short circuiting on the right operand
1085 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1086 builder.clearAccessChain();
1087 builder.setAccessChainRValue(result);
1088 }
1089 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001090 default:
1091 break;
1092 }
1093
1094 // Assume generic binary op...
1095
John Kessenich32cfd492016-02-02 12:37:46 -07001096 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001097 builder.clearAccessChain();
1098 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001099 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001100
John Kessenich32cfd492016-02-02 12:37:46 -07001101 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001102 builder.clearAccessChain();
1103 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001104 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001105
John Kessenich32cfd492016-02-02 12:37:46 -07001106 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001107 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001108 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001109 convertGlslangToSpvType(node->getType()), left, right,
1110 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001111
John Kessenich50e57562015-12-21 21:21:11 -07001112 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001113 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001114 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001115 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001116 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001117 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001118 return false;
1119 }
John Kessenich140f3df2015-06-26 16:58:36 -06001120}
1121
1122bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1123{
qining40887662016-04-03 22:20:42 -04001124 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1125 if (node->getType().getQualifier().isSpecConstant())
1126 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1127
John Kessenichfc51d282015-08-19 13:34:18 -06001128 spv::Id result = spv::NoResult;
1129
1130 // try texturing first
1131 result = createImageTextureFunctionCall(node);
1132 if (result != spv::NoResult) {
1133 builder.clearAccessChain();
1134 builder.setAccessChainRValue(result);
1135
1136 return false; // done with this node
1137 }
1138
1139 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001140
1141 if (node->getOp() == glslang::EOpArrayLength) {
1142 // Quite special; won't want to evaluate the operand.
1143
1144 // Normal .length() would have been constant folded by the front-end.
1145 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001146 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001147 assert(node->getOperand()->getType().isRuntimeSizedArray());
1148 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1149 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001150 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1151 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001152
1153 builder.clearAccessChain();
1154 builder.setAccessChainRValue(length);
1155
1156 return false;
1157 }
1158
John Kessenichfc51d282015-08-19 13:34:18 -06001159 // Start by evaluating the operand
1160
John Kessenich8c8505c2016-07-26 12:50:38 -06001161 // Does it need a swizzle inversion? If so, evaluation is inverted;
1162 // operate first on the swizzle base, then apply the swizzle.
1163 spv::Id invertedType = spv::NoType;
1164 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1165 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1166 invertedType = getInvertedSwizzleType(*node->getOperand());
1167
John Kessenich140f3df2015-06-26 16:58:36 -06001168 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001169 if (invertedType != spv::NoType)
1170 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1171 else
1172 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001173
Rex Xufc618912015-09-09 16:42:49 +08001174 spv::Id operand = spv::NoResult;
1175
1176 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1177 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001178 node->getOp() == glslang::EOpAtomicCounter ||
1179 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001180 operand = builder.accessChainGetLValue(); // Special case l-value operands
1181 else
John Kessenich32cfd492016-02-02 12:37:46 -07001182 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001183
John Kessenichf6640762016-08-01 19:44:00 -06001184 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001185 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001186
1187 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001188 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001189 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001190
1191 // if not, then possibly an operation
1192 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001193 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001194
1195 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001196 if (invertedType)
1197 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1198
John Kessenich140f3df2015-06-26 16:58:36 -06001199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(result);
1201
1202 return false; // done with this node
1203 }
1204
1205 // it must be a special case, check...
1206 switch (node->getOp()) {
1207 case glslang::EOpPostIncrement:
1208 case glslang::EOpPostDecrement:
1209 case glslang::EOpPreIncrement:
1210 case glslang::EOpPreDecrement:
1211 {
1212 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001213 spv::Id one = 0;
1214 if (node->getBasicType() == glslang::EbtFloat)
1215 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001216 else if (node->getBasicType() == glslang::EbtDouble)
1217 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001218 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1219 one = builder.makeInt64Constant(1);
1220 else
1221 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001222 glslang::TOperator op;
1223 if (node->getOp() == glslang::EOpPreIncrement ||
1224 node->getOp() == glslang::EOpPostIncrement)
1225 op = glslang::EOpAdd;
1226 else
1227 op = glslang::EOpSub;
1228
John Kessenichf6640762016-08-01 19:44:00 -06001229 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001230 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001231 convertGlslangToSpvType(node->getType()), operand, one,
1232 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001233 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001234
1235 // The result of operation is always stored, but conditionally the
1236 // consumed result. The consumed result is always an r-value.
1237 builder.accessChainStore(result);
1238 builder.clearAccessChain();
1239 if (node->getOp() == glslang::EOpPreIncrement ||
1240 node->getOp() == glslang::EOpPreDecrement)
1241 builder.setAccessChainRValue(result);
1242 else
1243 builder.setAccessChainRValue(operand);
1244 }
1245
1246 return false;
1247
1248 case glslang::EOpEmitStreamVertex:
1249 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1250 return false;
1251 case glslang::EOpEndStreamPrimitive:
1252 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1253 return false;
1254
1255 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001256 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001257 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001258 }
John Kessenich140f3df2015-06-26 16:58:36 -06001259}
1260
1261bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1262{
qining27e04a02016-04-14 16:40:20 -04001263 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1264 if (node->getType().getQualifier().isSpecConstant())
1265 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1266
John Kessenichfc51d282015-08-19 13:34:18 -06001267 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001268 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1269 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001270
1271 // try texturing
1272 result = createImageTextureFunctionCall(node);
1273 if (result != spv::NoResult) {
1274 builder.clearAccessChain();
1275 builder.setAccessChainRValue(result);
1276
1277 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001278 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001279 // "imageStore" is a special case, which has no result
1280 return false;
1281 }
John Kessenichfc51d282015-08-19 13:34:18 -06001282
John Kessenich140f3df2015-06-26 16:58:36 -06001283 glslang::TOperator binOp = glslang::EOpNull;
1284 bool reduceComparison = true;
1285 bool isMatrix = false;
1286 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001287 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001288
1289 assert(node->getOp());
1290
John Kessenichf6640762016-08-01 19:44:00 -06001291 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001292
1293 switch (node->getOp()) {
1294 case glslang::EOpSequence:
1295 {
1296 if (preVisit)
1297 ++sequenceDepth;
1298 else
1299 --sequenceDepth;
1300
1301 if (sequenceDepth == 1) {
1302 // If this is the parent node of all the functions, we want to see them
1303 // early, so all call points have actual SPIR-V functions to reference.
1304 // In all cases, still let the traverser visit the children for us.
1305 makeFunctions(node->getAsAggregate()->getSequence());
1306
John Kessenich6fccb3c2016-09-19 16:01:41 -06001307 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001308 // anything else gets there, so visit out of order, doing them all now.
1309 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1310
1311 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1312 // so do them manually.
1313 visitFunctions(node->getAsAggregate()->getSequence());
1314
1315 return false;
1316 }
1317
1318 return true;
1319 }
1320 case glslang::EOpLinkerObjects:
1321 {
1322 if (visit == glslang::EvPreVisit)
1323 linkageOnly = true;
1324 else
1325 linkageOnly = false;
1326
1327 return true;
1328 }
1329 case glslang::EOpComma:
1330 {
1331 // processing from left to right naturally leaves the right-most
1332 // lying around in the access chain
1333 glslang::TIntermSequence& glslangOperands = node->getSequence();
1334 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1335 glslangOperands[i]->traverse(this);
1336
1337 return false;
1338 }
1339 case glslang::EOpFunction:
1340 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001341 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001342 inMain = true;
1343 builder.setBuildPoint(shaderEntry->getLastBlock());
1344 } else {
1345 handleFunctionEntry(node);
1346 }
1347 } else {
1348 if (inMain)
1349 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001350 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001351 inMain = false;
1352 }
1353
1354 return true;
1355 case glslang::EOpParameters:
1356 // Parameters will have been consumed by EOpFunction processing, but not
1357 // the body, so we still visited the function node's children, making this
1358 // child redundant.
1359 return false;
1360 case glslang::EOpFunctionCall:
1361 {
1362 if (node->isUserDefined())
1363 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001364 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1365 if (result) {
1366 builder.clearAccessChain();
1367 builder.setAccessChainRValue(result);
1368 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001369 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001370
1371 return false;
1372 }
1373 case glslang::EOpConstructMat2x2:
1374 case glslang::EOpConstructMat2x3:
1375 case glslang::EOpConstructMat2x4:
1376 case glslang::EOpConstructMat3x2:
1377 case glslang::EOpConstructMat3x3:
1378 case glslang::EOpConstructMat3x4:
1379 case glslang::EOpConstructMat4x2:
1380 case glslang::EOpConstructMat4x3:
1381 case glslang::EOpConstructMat4x4:
1382 case glslang::EOpConstructDMat2x2:
1383 case glslang::EOpConstructDMat2x3:
1384 case glslang::EOpConstructDMat2x4:
1385 case glslang::EOpConstructDMat3x2:
1386 case glslang::EOpConstructDMat3x3:
1387 case glslang::EOpConstructDMat3x4:
1388 case glslang::EOpConstructDMat4x2:
1389 case glslang::EOpConstructDMat4x3:
1390 case glslang::EOpConstructDMat4x4:
1391 isMatrix = true;
1392 // fall through
1393 case glslang::EOpConstructFloat:
1394 case glslang::EOpConstructVec2:
1395 case glslang::EOpConstructVec3:
1396 case glslang::EOpConstructVec4:
1397 case glslang::EOpConstructDouble:
1398 case glslang::EOpConstructDVec2:
1399 case glslang::EOpConstructDVec3:
1400 case glslang::EOpConstructDVec4:
1401 case glslang::EOpConstructBool:
1402 case glslang::EOpConstructBVec2:
1403 case glslang::EOpConstructBVec3:
1404 case glslang::EOpConstructBVec4:
1405 case glslang::EOpConstructInt:
1406 case glslang::EOpConstructIVec2:
1407 case glslang::EOpConstructIVec3:
1408 case glslang::EOpConstructIVec4:
1409 case glslang::EOpConstructUint:
1410 case glslang::EOpConstructUVec2:
1411 case glslang::EOpConstructUVec3:
1412 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001413 case glslang::EOpConstructInt64:
1414 case glslang::EOpConstructI64Vec2:
1415 case glslang::EOpConstructI64Vec3:
1416 case glslang::EOpConstructI64Vec4:
1417 case glslang::EOpConstructUint64:
1418 case glslang::EOpConstructU64Vec2:
1419 case glslang::EOpConstructU64Vec3:
1420 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001421 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001422 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001423 {
1424 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001425 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001426 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001427 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001428 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001429 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001430 std::vector<spv::Id> constituents;
1431 for (int c = 0; c < (int)arguments.size(); ++c)
1432 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001433 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001434 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001435 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001436 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001437 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 builder.clearAccessChain();
1440 builder.setAccessChainRValue(constructed);
1441
1442 return false;
1443 }
1444
1445 // These six are component-wise compares with component-wise results.
1446 // Forward on to createBinaryOperation(), requesting a vector result.
1447 case glslang::EOpLessThan:
1448 case glslang::EOpGreaterThan:
1449 case glslang::EOpLessThanEqual:
1450 case glslang::EOpGreaterThanEqual:
1451 case glslang::EOpVectorEqual:
1452 case glslang::EOpVectorNotEqual:
1453 {
1454 // Map the operation to a binary
1455 binOp = node->getOp();
1456 reduceComparison = false;
1457 switch (node->getOp()) {
1458 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1459 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1460 default: binOp = node->getOp(); break;
1461 }
1462
1463 break;
1464 }
1465 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001466 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001467 binOp = glslang::EOpMul;
1468 break;
1469 case glslang::EOpOuterProduct:
1470 // two vectors multiplied to make a matrix
1471 binOp = glslang::EOpOuterProduct;
1472 break;
1473 case glslang::EOpDot:
1474 {
qining25262b32016-05-06 17:25:16 -04001475 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001476 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001477 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001478 binOp = glslang::EOpMul;
1479 break;
1480 }
1481 case glslang::EOpMod:
1482 // when an aggregate, this is the floating-point mod built-in function,
1483 // which can be emitted by the one in createBinaryOperation()
1484 binOp = glslang::EOpMod;
1485 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001486 case glslang::EOpEmitVertex:
1487 case glslang::EOpEndPrimitive:
1488 case glslang::EOpBarrier:
1489 case glslang::EOpMemoryBarrier:
1490 case glslang::EOpMemoryBarrierAtomicCounter:
1491 case glslang::EOpMemoryBarrierBuffer:
1492 case glslang::EOpMemoryBarrierImage:
1493 case glslang::EOpMemoryBarrierShared:
1494 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001495 case glslang::EOpAllMemoryBarrierWithGroupSync:
1496 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1497 case glslang::EOpWorkgroupMemoryBarrier:
1498 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001499 noReturnValue = true;
1500 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1501 break;
1502
John Kessenich426394d2015-07-23 10:22:48 -06001503 case glslang::EOpAtomicAdd:
1504 case glslang::EOpAtomicMin:
1505 case glslang::EOpAtomicMax:
1506 case glslang::EOpAtomicAnd:
1507 case glslang::EOpAtomicOr:
1508 case glslang::EOpAtomicXor:
1509 case glslang::EOpAtomicExchange:
1510 case glslang::EOpAtomicCompSwap:
1511 atomic = true;
1512 break;
1513
John Kessenich140f3df2015-06-26 16:58:36 -06001514 default:
1515 break;
1516 }
1517
1518 //
1519 // See if it maps to a regular operation.
1520 //
John Kessenich140f3df2015-06-26 16:58:36 -06001521 if (binOp != glslang::EOpNull) {
1522 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1523 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1524 assert(left && right);
1525
1526 builder.clearAccessChain();
1527 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001528 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001529
1530 builder.clearAccessChain();
1531 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001532 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001533
qining25262b32016-05-06 17:25:16 -04001534 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001535 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001536 left->getType().getBasicType(), reduceComparison);
1537
1538 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001539 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001540 builder.clearAccessChain();
1541 builder.setAccessChainRValue(result);
1542
1543 return false;
1544 }
1545
John Kessenich426394d2015-07-23 10:22:48 -06001546 //
1547 // Create the list of operands.
1548 //
John Kessenich140f3df2015-06-26 16:58:36 -06001549 glslang::TIntermSequence& glslangOperands = node->getSequence();
1550 std::vector<spv::Id> operands;
1551 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001552 // special case l-value operands; there are just a few
1553 bool lvalue = false;
1554 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001555 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001556 case glslang::EOpModf:
1557 if (arg == 1)
1558 lvalue = true;
1559 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001560 case glslang::EOpInterpolateAtSample:
1561 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001562#ifdef AMD_EXTENSIONS
1563 case glslang::EOpInterpolateAtVertex:
1564#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001565 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001566 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001567
1568 // Does it need a swizzle inversion? If so, evaluation is inverted;
1569 // operate first on the swizzle base, then apply the swizzle.
1570 if (glslangOperands[0]->getAsOperator() &&
1571 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1572 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1573 }
Rex Xu7a26c172015-12-08 17:12:09 +08001574 break;
Rex Xud4782c12015-09-06 16:30:11 +08001575 case glslang::EOpAtomicAdd:
1576 case glslang::EOpAtomicMin:
1577 case glslang::EOpAtomicMax:
1578 case glslang::EOpAtomicAnd:
1579 case glslang::EOpAtomicOr:
1580 case glslang::EOpAtomicXor:
1581 case glslang::EOpAtomicExchange:
1582 case glslang::EOpAtomicCompSwap:
1583 if (arg == 0)
1584 lvalue = true;
1585 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001586 case glslang::EOpAddCarry:
1587 case glslang::EOpSubBorrow:
1588 if (arg == 2)
1589 lvalue = true;
1590 break;
1591 case glslang::EOpUMulExtended:
1592 case glslang::EOpIMulExtended:
1593 if (arg >= 2)
1594 lvalue = true;
1595 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001596 default:
1597 break;
1598 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001599 builder.clearAccessChain();
1600 if (invertedType != spv::NoType && arg == 0)
1601 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1602 else
1603 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001604 if (lvalue)
1605 operands.push_back(builder.accessChainGetLValue());
1606 else
John Kessenich32cfd492016-02-02 12:37:46 -07001607 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001608 }
John Kessenich426394d2015-07-23 10:22:48 -06001609
1610 if (atomic) {
1611 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001612 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001613 } else {
1614 // Pass through to generic operations.
1615 switch (glslangOperands.size()) {
1616 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001617 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001618 break;
1619 case 1:
qining25262b32016-05-06 17:25:16 -04001620 result = createUnaryOperation(
1621 node->getOp(), precision,
1622 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001623 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001624 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001625 break;
1626 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001627 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001628 break;
1629 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001630 if (invertedType)
1631 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001632 }
1633
1634 if (noReturnValue)
1635 return false;
1636
1637 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001638 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001639 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001640 } else {
1641 builder.clearAccessChain();
1642 builder.setAccessChainRValue(result);
1643 return false;
1644 }
1645}
1646
1647bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1648{
1649 // This path handles both if-then-else and ?:
1650 // The if-then-else has a node type of void, while
1651 // ?: has a non-void node type
1652 spv::Id result = 0;
1653 if (node->getBasicType() != glslang::EbtVoid) {
1654 // don't handle this as just on-the-fly temporaries, because there will be two names
1655 // and better to leave SSA to later passes
1656 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1657 }
1658
1659 // emit the condition before doing anything with selection
1660 node->getCondition()->traverse(this);
1661
1662 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001663 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001664
1665 if (node->getTrueBlock()) {
1666 // emit the "then" statement
1667 node->getTrueBlock()->traverse(this);
1668 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001669 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001670 }
1671
1672 if (node->getFalseBlock()) {
1673 ifBuilder.makeBeginElse();
1674 // emit the "else" statement
1675 node->getFalseBlock()->traverse(this);
1676 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001677 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001678 }
1679
1680 ifBuilder.makeEndIf();
1681
1682 if (result) {
1683 // GLSL only has r-values as the result of a :?, but
1684 // if we have an l-value, that can be more efficient if it will
1685 // become the base of a complex r-value expression, because the
1686 // next layer copies r-values into memory to use the access-chain mechanism
1687 builder.clearAccessChain();
1688 builder.setAccessChainLValue(result);
1689 }
1690
1691 return false;
1692}
1693
1694bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1695{
1696 // emit and get the condition before doing anything with switch
1697 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001698 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001699
1700 // browse the children to sort out code segments
1701 int defaultSegment = -1;
1702 std::vector<TIntermNode*> codeSegments;
1703 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1704 std::vector<int> caseValues;
1705 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1706 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1707 TIntermNode* child = *c;
1708 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001709 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001710 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001711 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001712 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1713 } else
1714 codeSegments.push_back(child);
1715 }
1716
qining25262b32016-05-06 17:25:16 -04001717 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001718 // statements between the last case and the end of the switch statement
1719 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1720 (int)codeSegments.size() == defaultSegment)
1721 codeSegments.push_back(nullptr);
1722
1723 // make the switch statement
1724 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001725 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001726
1727 // emit all the code in the segments
1728 breakForLoop.push(false);
1729 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1730 builder.nextSwitchSegment(segmentBlocks, s);
1731 if (codeSegments[s])
1732 codeSegments[s]->traverse(this);
1733 else
1734 builder.addSwitchBreak();
1735 }
1736 breakForLoop.pop();
1737
1738 builder.endSwitch(segmentBlocks);
1739
1740 return false;
1741}
1742
1743void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1744{
1745 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001746 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001747
1748 builder.clearAccessChain();
1749 builder.setAccessChainRValue(constant);
1750}
1751
1752bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1753{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001754 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001755 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001756 // Spec requires back edges to target header blocks, and every header block
1757 // must dominate its merge block. Make a header block first to ensure these
1758 // conditions are met. By definition, it will contain OpLoopMerge, followed
1759 // by a block-ending branch. But we don't want to put any other body/test
1760 // instructions in it, since the body/test may have arbitrary instructions,
1761 // including merges of its own.
1762 builder.setBuildPoint(&blocks.head);
1763 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001764 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001765 spv::Block& test = builder.makeNewBlock();
1766 builder.createBranch(&test);
1767
1768 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001769 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001770 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001771 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001772 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1773
1774 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001775 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001776 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001777 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001778 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001779 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001780
1781 builder.setBuildPoint(&blocks.continue_target);
1782 if (node->getTerminal())
1783 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001784 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001785 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001786 builder.createBranch(&blocks.body);
1787
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001788 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001789 builder.setBuildPoint(&blocks.body);
1790 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001791 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001792 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001793 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001794
1795 builder.setBuildPoint(&blocks.continue_target);
1796 if (node->getTerminal())
1797 node->getTerminal()->traverse(this);
1798 if (node->getTest()) {
1799 node->getTest()->traverse(this);
1800 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001801 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001802 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001803 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001804 // TODO: unless there was a break/return/discard instruction
1805 // somewhere in the body, this is an infinite loop, so we should
1806 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001807 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001808 }
John Kessenich140f3df2015-06-26 16:58:36 -06001809 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001810 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001811 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001812 return false;
1813}
1814
1815bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1816{
1817 if (node->getExpression())
1818 node->getExpression()->traverse(this);
1819
1820 switch (node->getFlowOp()) {
1821 case glslang::EOpKill:
1822 builder.makeDiscard();
1823 break;
1824 case glslang::EOpBreak:
1825 if (breakForLoop.top())
1826 builder.createLoopExit();
1827 else
1828 builder.addSwitchBreak();
1829 break;
1830 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001831 builder.createLoopContinue();
1832 break;
1833 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001834 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001835 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001836 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001837 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001838
1839 builder.clearAccessChain();
1840 break;
1841
1842 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001843 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001844 break;
1845 }
1846
1847 return false;
1848}
1849
1850spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1851{
qining25262b32016-05-06 17:25:16 -04001852 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001853 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001854 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001855 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001856 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001857 }
1858
1859 // Now, handle actual variables
1860 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1861 spv::Id spvType = convertGlslangToSpvType(node->getType());
1862
1863 const char* name = node->getName().c_str();
1864 if (glslang::IsAnonymous(name))
1865 name = "";
1866
1867 return builder.createVariable(storageClass, spvType, name);
1868}
1869
1870// Return type Id of the sampled type.
1871spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1872{
1873 switch (sampler.type) {
1874 case glslang::EbtFloat: return builder.makeFloatType(32);
1875 case glslang::EbtInt: return builder.makeIntType(32);
1876 case glslang::EbtUint: return builder.makeUintType(32);
1877 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001878 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001879 return builder.makeFloatType(32);
1880 }
1881}
1882
John Kessenich8c8505c2016-07-26 12:50:38 -06001883// If node is a swizzle operation, return the type that should be used if
1884// the swizzle base is first consumed by another operation, before the swizzle
1885// is applied.
1886spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1887{
1888 if (node.getAsOperator() &&
1889 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1890 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1891 else
1892 return spv::NoType;
1893}
1894
1895// When inverting a swizzle with a parent op, this function
1896// will apply the swizzle operation to a completed parent operation.
1897spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1898{
1899 std::vector<unsigned> swizzle;
1900 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1901 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1902}
1903
1904
1905// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1906void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1907{
1908 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1909 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1910 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1911}
1912
John Kessenich3ac051e2015-12-20 11:29:16 -07001913// Convert from a glslang type to an SPV type, by calling into a
1914// recursive version of this function. This establishes the inherited
1915// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001916spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1917{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001918 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001919}
1920
1921// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001922// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001923// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001924spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001925{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001926 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001927
1928 switch (type.getBasicType()) {
1929 case glslang::EbtVoid:
1930 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001931 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001932 break;
1933 case glslang::EbtFloat:
1934 spvType = builder.makeFloatType(32);
1935 break;
1936 case glslang::EbtDouble:
1937 spvType = builder.makeFloatType(64);
1938 break;
1939 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001940 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1941 // a 32-bit int where non-0 means true.
1942 if (explicitLayout != glslang::ElpNone)
1943 spvType = builder.makeUintType(32);
1944 else
1945 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001946 break;
1947 case glslang::EbtInt:
1948 spvType = builder.makeIntType(32);
1949 break;
1950 case glslang::EbtUint:
1951 spvType = builder.makeUintType(32);
1952 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001953 case glslang::EbtInt64:
1954 builder.addCapability(spv::CapabilityInt64);
1955 spvType = builder.makeIntType(64);
1956 break;
1957 case glslang::EbtUint64:
1958 builder.addCapability(spv::CapabilityInt64);
1959 spvType = builder.makeUintType(64);
1960 break;
John Kessenich426394d2015-07-23 10:22:48 -06001961 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001962 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001963 spvType = builder.makeUintType(32);
1964 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001965 case glslang::EbtSampler:
1966 {
1967 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001968 if (sampler.sampler) {
1969 // pure sampler
1970 spvType = builder.makeSamplerType();
1971 } else {
1972 // an image is present, make its type
1973 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1974 sampler.image ? 2 : 1, TranslateImageFormat(type));
1975 if (sampler.combined) {
1976 // already has both image and sampler, make the combined type
1977 spvType = builder.makeSampledImageType(spvType);
1978 }
John Kessenich55e7d112015-11-15 21:33:39 -07001979 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001980 }
John Kessenich140f3df2015-06-26 16:58:36 -06001981 break;
1982 case glslang::EbtStruct:
1983 case glslang::EbtBlock:
1984 {
1985 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001986 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001987
1988 // Try to share structs for different layouts, but not yet for other
1989 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06001990 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001991 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001992 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001993 break;
1994
1995 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001996 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001997 memberRemapper[glslangMembers].resize(glslangMembers->size());
1998 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001999 }
2000 break;
2001 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002002 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002003 break;
2004 }
2005
2006 if (type.isMatrix())
2007 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2008 else {
2009 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2010 if (type.getVectorSize() > 1)
2011 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2012 }
2013
2014 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002015 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2016
John Kessenichc9a80832015-09-12 12:17:44 -06002017 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002018 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002019 // We need to decorate array strides for types needing explicit layout, except blocks.
2020 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002021 // Use a dummy glslang type for querying internal strides of
2022 // arrays of arrays, but using just a one-dimensional array.
2023 glslang::TType simpleArrayType(type, 0); // deference type of the array
2024 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2025 simpleArrayType.getArraySizes().dereference();
2026
2027 // Will compute the higher-order strides here, rather than making a whole
2028 // pile of types and doing repetitive recursion on their contents.
2029 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2030 }
John Kessenichf8842e52016-01-04 19:22:56 -07002031
2032 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002033 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002034 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002035 if (stride > 0)
2036 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002037 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002038 }
2039 } else {
2040 // single-dimensional array, and don't yet have stride
2041
John Kessenichf8842e52016-01-04 19:22:56 -07002042 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002043 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2044 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002045 }
John Kessenich31ed4832015-09-09 17:51:38 -06002046
John Kessenichc9a80832015-09-12 12:17:44 -06002047 // Do the outer dimension, which might not be known for a runtime-sized array
2048 if (type.isRuntimeSizedArray()) {
2049 spvType = builder.makeRuntimeArray(spvType);
2050 } else {
2051 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002052 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002053 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002054 if (stride > 0)
2055 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 }
2057
2058 return spvType;
2059}
2060
John Kessenich6090df02016-06-30 21:18:02 -06002061
2062// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2063// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2064// Mutually recursive with convertGlslangToSpvType().
2065spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2066 const glslang::TTypeList* glslangMembers,
2067 glslang::TLayoutPacking explicitLayout,
2068 const glslang::TQualifier& qualifier)
2069{
2070 // Create a vector of struct types for SPIR-V to consume
2071 std::vector<spv::Id> spvMembers;
2072 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2073 int locationOffset = 0; // for use across struct members, when they are called recursively
2074 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2075 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2076 if (glslangMember.hiddenMember()) {
2077 ++memberDelta;
2078 if (type.getBasicType() == glslang::EbtBlock)
2079 memberRemapper[glslangMembers][i] = -1;
2080 } else {
2081 if (type.getBasicType() == glslang::EbtBlock)
2082 memberRemapper[glslangMembers][i] = i - memberDelta;
2083 // modify just this child's view of the qualifier
2084 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2085 InheritQualifiers(memberQualifier, qualifier);
2086
2087 // manually inherit location; it's more complex
2088 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2089 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2090 if (qualifier.hasLocation())
2091 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2092
2093 // recurse
2094 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2095 }
2096 }
2097
2098 // Make the SPIR-V type
2099 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002100 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002101 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2102
2103 // Decorate it
2104 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2105
2106 return spvType;
2107}
2108
2109void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2110 const glslang::TTypeList* glslangMembers,
2111 glslang::TLayoutPacking explicitLayout,
2112 const glslang::TQualifier& qualifier,
2113 spv::Id spvType)
2114{
2115 // Name and decorate the non-hidden members
2116 int offset = -1;
2117 int locationOffset = 0; // for use within the members of this struct
2118 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2119 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2120 int member = i;
2121 if (type.getBasicType() == glslang::EbtBlock)
2122 member = memberRemapper[glslangMembers][i];
2123
2124 // modify just this child's view of the qualifier
2125 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2126 InheritQualifiers(memberQualifier, qualifier);
2127
2128 // using -1 above to indicate a hidden member
2129 if (member >= 0) {
2130 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2131 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2132 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2133 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2134 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2135 if (type.getBasicType() == glslang::EbtBlock) {
2136 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2137 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2138 }
2139 }
2140 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2141
2142 if (qualifier.storage == glslang::EvqBuffer) {
2143 std::vector<spv::Decoration> memory;
2144 TranslateMemoryDecoration(memberQualifier, memory);
2145 for (unsigned int i = 0; i < memory.size(); ++i)
2146 addMemberDecoration(spvType, member, memory[i]);
2147 }
2148
John Kessenich2f47bc92016-06-30 21:47:35 -06002149 // Compute location decoration; tricky based on whether inheritance is at play and
2150 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002151 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2152 // probably move to the linker stage of the front end proper, and just have the
2153 // answer sitting already distributed throughout the individual member locations.
2154 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002155 // Ignore member locations if the container is an array, as that's
2156 // ill-specified and decisions have been made to not allow this anyway.
2157 // The object itself must have a location, and that comes out from decorating the object,
2158 // not the type (this code decorates types).
2159 if (! type.isArray()) {
2160 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2161 // struct members should not have explicit locations
2162 assert(type.getBasicType() != glslang::EbtStruct);
2163 location = memberQualifier.layoutLocation;
2164 } else if (type.getBasicType() != glslang::EbtBlock) {
2165 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2166 // The members, and their nested types, must not themselves have Location decorations.
2167 } else if (qualifier.hasLocation()) // inheritance
2168 location = qualifier.layoutLocation + locationOffset;
2169 }
John Kessenich6090df02016-06-30 21:18:02 -06002170 if (location >= 0)
2171 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2172
John Kessenich2f47bc92016-06-30 21:47:35 -06002173 if (qualifier.hasLocation()) // track for upcoming inheritance
2174 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2175
John Kessenich6090df02016-06-30 21:18:02 -06002176 // component, XFB, others
2177 if (glslangMember.getQualifier().hasComponent())
2178 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2179 if (glslangMember.getQualifier().hasXfbOffset())
2180 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2181 else if (explicitLayout != glslang::ElpNone) {
2182 // figure out what to do with offset, which is accumulating
2183 int nextOffset;
2184 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2185 if (offset >= 0)
2186 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2187 offset = nextOffset;
2188 }
2189
2190 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2191 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2192
2193 // built-in variable decorations
2194 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002195 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002196 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2197 }
2198 }
2199
2200 // Decorate the structure
2201 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2202 addDecoration(spvType, TranslateBlockDecoration(type));
2203 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2204 builder.addCapability(spv::CapabilityGeometryStreams);
2205 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2206 }
2207 if (glslangIntermediate->getXfbMode()) {
2208 builder.addCapability(spv::CapabilityTransformFeedback);
2209 if (type.getQualifier().hasXfbStride())
2210 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2211 if (type.getQualifier().hasXfbBuffer())
2212 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2213 }
2214}
2215
John Kessenich6c292d32016-02-15 20:58:50 -07002216// Turn the expression forming the array size into an id.
2217// This is not quite trivial, because of specialization constants.
2218// Sometimes, a raw constant is turned into an Id, and sometimes
2219// a specialization constant expression is.
2220spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2221{
2222 // First, see if this is sized with a node, meaning a specialization constant:
2223 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2224 if (specNode != nullptr) {
2225 builder.clearAccessChain();
2226 specNode->traverse(this);
2227 return accessChainLoad(specNode->getAsTyped()->getType());
2228 }
qining25262b32016-05-06 17:25:16 -04002229
John Kessenich6c292d32016-02-15 20:58:50 -07002230 // Otherwise, need a compile-time (front end) size, get it:
2231 int size = arraySizes.getDimSize(dim);
2232 assert(size > 0);
2233 return builder.makeUintConstant(size);
2234}
2235
John Kessenich103bef92016-02-08 21:38:15 -07002236// Wrap the builder's accessChainLoad to:
2237// - localize handling of RelaxedPrecision
2238// - use the SPIR-V inferred type instead of another conversion of the glslang type
2239// (avoids unnecessary work and possible type punning for structures)
2240// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002241spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2242{
John Kessenich103bef92016-02-08 21:38:15 -07002243 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2244 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2245
2246 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002247 if (type.getBasicType() == glslang::EbtBool) {
2248 if (builder.isScalarType(nominalTypeId)) {
2249 // Conversion for bool
2250 spv::Id boolType = builder.makeBoolType();
2251 if (nominalTypeId != boolType)
2252 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2253 } else if (builder.isVectorType(nominalTypeId)) {
2254 // Conversion for bvec
2255 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2256 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2257 if (nominalTypeId != bvecType)
2258 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2259 }
2260 }
John Kessenich103bef92016-02-08 21:38:15 -07002261
2262 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002263}
2264
Rex Xu27253232016-02-23 17:51:09 +08002265// Wrap the builder's accessChainStore to:
2266// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002267//
2268// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002269void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2270{
2271 // Need to convert to abstract types when necessary
2272 if (type.getBasicType() == glslang::EbtBool) {
2273 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2274
2275 if (builder.isScalarType(nominalTypeId)) {
2276 // Conversion for bool
2277 spv::Id boolType = builder.makeBoolType();
2278 if (nominalTypeId != boolType) {
2279 spv::Id zero = builder.makeUintConstant(0);
2280 spv::Id one = builder.makeUintConstant(1);
2281 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2282 }
2283 } else if (builder.isVectorType(nominalTypeId)) {
2284 // Conversion for bvec
2285 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2286 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2287 if (nominalTypeId != bvecType) {
2288 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2289 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2290 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2291 }
2292 }
2293 }
2294
2295 builder.accessChainStore(rvalue);
2296}
2297
John Kessenich4bf71552016-09-02 11:20:21 -06002298// For storing when types match at the glslang level, but not might match at the
2299// SPIR-V level.
2300//
2301// This especially happens when a single glslang type expands to multiple
2302// SPIR-V types, like a struct that is used in an member-undecorated way as well
2303// as in a member-decorated way.
2304//
2305// NOTE: This function can handle any store request; if it's not special it
2306// simplifies to a simple OpStore.
2307//
2308// Implicitly uses the existing builder.accessChain as the storage target.
2309void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2310{
John Kessenichb3e24e42016-09-11 12:33:43 -06002311 // we only do the complex path here if it's an aggregate
2312 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002313 accessChainStore(type, rValue);
2314 return;
2315 }
2316
John Kessenichb3e24e42016-09-11 12:33:43 -06002317 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002318 spv::Id rType = builder.getTypeId(rValue);
2319 spv::Id lValue = builder.accessChainGetLValue();
2320 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2321 if (lType == rType) {
2322 accessChainStore(type, rValue);
2323 return;
2324 }
2325
John Kessenichb3e24e42016-09-11 12:33:43 -06002326 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002327 // where the two types were the same type in GLSL. This requires member
2328 // by member copy, recursively.
2329
John Kessenichb3e24e42016-09-11 12:33:43 -06002330 // If an array, copy element by element.
2331 if (type.isArray()) {
2332 glslang::TType glslangElementType(type, 0);
2333 spv::Id elementRType = builder.getContainedTypeId(rType);
2334 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2335 // get the source member
2336 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002337
John Kessenichb3e24e42016-09-11 12:33:43 -06002338 // set up the target storage
2339 builder.clearAccessChain();
2340 builder.setAccessChainLValue(lValue);
2341 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002342
John Kessenichb3e24e42016-09-11 12:33:43 -06002343 // store the member
2344 multiTypeStore(glslangElementType, elementRValue);
2345 }
2346 } else {
2347 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002348
John Kessenichb3e24e42016-09-11 12:33:43 -06002349 // loop over structure members
2350 const glslang::TTypeList& members = *type.getStruct();
2351 for (int m = 0; m < (int)members.size(); ++m) {
2352 const glslang::TType& glslangMemberType = *members[m].type;
2353
2354 // get the source member
2355 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2356 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2357
2358 // set up the target storage
2359 builder.clearAccessChain();
2360 builder.setAccessChainLValue(lValue);
2361 builder.accessChainPush(builder.makeIntConstant(m));
2362
2363 // store the member
2364 multiTypeStore(glslangMemberType, memberRValue);
2365 }
John Kessenich4bf71552016-09-02 11:20:21 -06002366 }
2367}
2368
John Kessenichf85e8062015-12-19 13:57:10 -07002369// Decide whether or not this type should be
2370// decorated with offsets and strides, and if so
2371// whether std140 or std430 rules should be applied.
2372glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002373{
John Kessenichf85e8062015-12-19 13:57:10 -07002374 // has to be a block
2375 if (type.getBasicType() != glslang::EbtBlock)
2376 return glslang::ElpNone;
2377
2378 // has to be a uniform or buffer block
2379 if (type.getQualifier().storage != glslang::EvqUniform &&
2380 type.getQualifier().storage != glslang::EvqBuffer)
2381 return glslang::ElpNone;
2382
2383 // return the layout to use
2384 switch (type.getQualifier().layoutPacking) {
2385 case glslang::ElpStd140:
2386 case glslang::ElpStd430:
2387 return type.getQualifier().layoutPacking;
2388 default:
2389 return glslang::ElpNone;
2390 }
John Kessenich31ed4832015-09-09 17:51:38 -06002391}
2392
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002393// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002394int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002395{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002396 int size;
John Kessenich49987892015-12-29 17:11:44 -07002397 int stride;
2398 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002399
2400 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002401}
2402
John Kessenich49987892015-12-29 17:11:44 -07002403// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002404// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002405int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002406{
John Kessenich49987892015-12-29 17:11:44 -07002407 glslang::TType elementType;
2408 elementType.shallowCopy(matrixType);
2409 elementType.clearArraySizes();
2410
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002411 int size;
John Kessenich49987892015-12-29 17:11:44 -07002412 int stride;
2413 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2414
2415 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002416}
2417
John Kessenich5e4b1242015-08-06 22:53:06 -06002418// Given a member type of a struct, realign the current offset for it, and compute
2419// the next (not yet aligned) offset for the next member, which will get aligned
2420// on the next call.
2421// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2422// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2423// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002424void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002425 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002426{
2427 // this will get a positive value when deemed necessary
2428 nextOffset = -1;
2429
John Kessenich5e4b1242015-08-06 22:53:06 -06002430 // override anything in currentOffset with user-set offset
2431 if (memberType.getQualifier().hasOffset())
2432 currentOffset = memberType.getQualifier().layoutOffset;
2433
2434 // It could be that current linker usage in glslang updated all the layoutOffset,
2435 // in which case the following code does not matter. But, that's not quite right
2436 // once cross-compilation unit GLSL validation is done, as the original user
2437 // settings are needed in layoutOffset, and then the following will come into play.
2438
John Kessenichf85e8062015-12-19 13:57:10 -07002439 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002440 if (! memberType.getQualifier().hasOffset())
2441 currentOffset = -1;
2442
2443 return;
2444 }
2445
John Kessenichf85e8062015-12-19 13:57:10 -07002446 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002447 if (currentOffset < 0)
2448 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002449
John Kessenich5e4b1242015-08-06 22:53:06 -06002450 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2451 // but possibly not yet correctly aligned.
2452
2453 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002454 int dummyStride;
2455 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002456 glslang::RoundToPow2(currentOffset, memberAlignment);
2457 nextOffset = currentOffset + memberSize;
2458}
2459
David Netoa901ffe2016-06-08 14:11:40 +01002460void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002461{
David Netoa901ffe2016-06-08 14:11:40 +01002462 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2463 switch (glslangBuiltIn)
2464 {
2465 case glslang::EbvClipDistance:
2466 case glslang::EbvCullDistance:
2467 case glslang::EbvPointSize:
2468 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2469 // Alternately, we could just call this for any glslang built-in, since the
2470 // capability already guards against duplicates.
2471 TranslateBuiltInDecoration(glslangBuiltIn, false);
2472 break;
2473 default:
2474 // Capabilities were already generated when the struct was declared.
2475 break;
2476 }
John Kessenichebb50532016-05-16 19:22:05 -06002477}
2478
John Kessenich6fccb3c2016-09-19 16:01:41 -06002479bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002480{
John Kessenicheee9d532016-09-19 18:09:30 -06002481 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002482}
2483
2484// Make all the functions, skeletally, without actually visiting their bodies.
2485void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2486{
2487 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2488 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002489 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002490 continue;
2491
2492 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002493 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002494 //
qining25262b32016-05-06 17:25:16 -04002495 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002496 // function. What it is an address of varies:
2497 //
John Kessenich4bf71552016-09-02 11:20:21 -06002498 // - "in" parameters not marked as "const" can be written to without modifying the calling
2499 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002500 //
2501 // - "const in" parameters can just be the r-value, as no writes need occur.
2502 //
John Kessenich4bf71552016-09-02 11:20:21 -06002503 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2504 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06002505
2506 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002507 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002508 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2509
2510 for (int p = 0; p < (int)parameters.size(); ++p) {
2511 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2512 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002513 if (paramType.isOpaque())
2514 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2515 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002516 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2517 else
John Kessenich4bf71552016-09-02 11:20:21 -06002518 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002519 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002520 paramTypes.push_back(typeId);
2521 }
2522
2523 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002524 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2525 convertGlslangToSpvType(glslFunction->getType()),
2526 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002527
2528 // Track function to emit/call later
2529 functionMap[glslFunction->getName().c_str()] = function;
2530
2531 // Set the parameter id's
2532 for (int p = 0; p < (int)parameters.size(); ++p) {
2533 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2534 // give a name too
2535 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2536 }
2537 }
2538}
2539
2540// Process all the initializers, while skipping the functions and link objects
2541void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2542{
2543 builder.setBuildPoint(shaderEntry->getLastBlock());
2544 for (int i = 0; i < (int)initializers.size(); ++i) {
2545 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2546 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2547
2548 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002549 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002550 initializer->traverse(this);
2551 }
2552 }
2553}
2554
2555// Process all the functions, while skipping initializers.
2556void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2557{
2558 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2559 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2560 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2561 node->traverse(this);
2562 }
2563}
2564
2565void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2566{
qining25262b32016-05-06 17:25:16 -04002567 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002568 // that called makeFunctions().
2569 spv::Function* function = functionMap[node->getName().c_str()];
2570 spv::Block* functionBlock = function->getEntryBlock();
2571 builder.setBuildPoint(functionBlock);
2572}
2573
Rex Xu04db3f52015-09-16 11:44:02 +08002574void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002575{
Rex Xufc618912015-09-09 16:42:49 +08002576 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002577
2578 glslang::TSampler sampler = {};
2579 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002580 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002581 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2582 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2583 }
2584
John Kessenich140f3df2015-06-26 16:58:36 -06002585 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2586 builder.clearAccessChain();
2587 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002588
2589 // Special case l-value operands
2590 bool lvalue = false;
2591 switch (node.getOp()) {
2592 case glslang::EOpImageAtomicAdd:
2593 case glslang::EOpImageAtomicMin:
2594 case glslang::EOpImageAtomicMax:
2595 case glslang::EOpImageAtomicAnd:
2596 case glslang::EOpImageAtomicOr:
2597 case glslang::EOpImageAtomicXor:
2598 case glslang::EOpImageAtomicExchange:
2599 case glslang::EOpImageAtomicCompSwap:
2600 if (i == 0)
2601 lvalue = true;
2602 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002603 case glslang::EOpSparseImageLoad:
2604 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2605 lvalue = true;
2606 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002607 case glslang::EOpSparseTexture:
2608 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2609 lvalue = true;
2610 break;
2611 case glslang::EOpSparseTextureClamp:
2612 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2613 lvalue = true;
2614 break;
2615 case glslang::EOpSparseTextureLod:
2616 case glslang::EOpSparseTextureOffset:
2617 if (i == 3)
2618 lvalue = true;
2619 break;
2620 case glslang::EOpSparseTextureFetch:
2621 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2622 lvalue = true;
2623 break;
2624 case glslang::EOpSparseTextureFetchOffset:
2625 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2626 lvalue = true;
2627 break;
2628 case glslang::EOpSparseTextureLodOffset:
2629 case glslang::EOpSparseTextureGrad:
2630 case glslang::EOpSparseTextureOffsetClamp:
2631 if (i == 4)
2632 lvalue = true;
2633 break;
2634 case glslang::EOpSparseTextureGradOffset:
2635 case glslang::EOpSparseTextureGradClamp:
2636 if (i == 5)
2637 lvalue = true;
2638 break;
2639 case glslang::EOpSparseTextureGradOffsetClamp:
2640 if (i == 6)
2641 lvalue = true;
2642 break;
2643 case glslang::EOpSparseTextureGather:
2644 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2645 lvalue = true;
2646 break;
2647 case glslang::EOpSparseTextureGatherOffset:
2648 case glslang::EOpSparseTextureGatherOffsets:
2649 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2650 lvalue = true;
2651 break;
Rex Xufc618912015-09-09 16:42:49 +08002652 default:
2653 break;
2654 }
2655
Rex Xu6b86d492015-09-16 17:48:22 +08002656 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002657 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002658 else
John Kessenich32cfd492016-02-02 12:37:46 -07002659 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002660 }
2661}
2662
John Kessenichfc51d282015-08-19 13:34:18 -06002663void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002664{
John Kessenichfc51d282015-08-19 13:34:18 -06002665 builder.clearAccessChain();
2666 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002667 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002668}
John Kessenich140f3df2015-06-26 16:58:36 -06002669
John Kessenichfc51d282015-08-19 13:34:18 -06002670spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2671{
Rex Xufc618912015-09-09 16:42:49 +08002672 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002673 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002674 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002675 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002676
John Kessenichfc51d282015-08-19 13:34:18 -06002677 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002678 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2679 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2680 std::vector<spv::Id> arguments;
2681 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002682 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002683 else
2684 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002685 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002686
2687 spv::Builder::TextureParameters params = { };
2688 params.sampler = arguments[0];
2689
Rex Xu04db3f52015-09-16 11:44:02 +08002690 glslang::TCrackedTextureOp cracked;
2691 node->crackTexture(sampler, cracked);
2692
John Kessenichfc51d282015-08-19 13:34:18 -06002693 // Check for queries
2694 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002695 // a sampled image needs to have the image extracted first
2696 if (builder.isSampledImage(params.sampler))
2697 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002698 switch (node->getOp()) {
2699 case glslang::EOpImageQuerySize:
2700 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002701 if (arguments.size() > 1) {
2702 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002703 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002704 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002706 case glslang::EOpImageQuerySamples:
2707 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002709 case glslang::EOpTextureQueryLod:
2710 params.coords = arguments[1];
2711 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2712 case glslang::EOpTextureQueryLevels:
2713 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002714 case glslang::EOpSparseTexelsResident:
2715 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002716 default:
2717 assert(0);
2718 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002719 }
John Kessenich140f3df2015-06-26 16:58:36 -06002720 }
2721
Rex Xufc618912015-09-09 16:42:49 +08002722 // Check for image functions other than queries
2723 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002724 std::vector<spv::Id> operands;
2725 auto opIt = arguments.begin();
2726 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002727
2728 // Handle subpass operations
2729 // TODO: GLSL should change to have the "MS" only on the type rather than the
2730 // built-in function.
2731 if (cracked.subpass) {
2732 // add on the (0,0) coordinate
2733 spv::Id zero = builder.makeIntConstant(0);
2734 std::vector<spv::Id> comps;
2735 comps.push_back(zero);
2736 comps.push_back(zero);
2737 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2738 if (sampler.ms) {
2739 operands.push_back(spv::ImageOperandsSampleMask);
2740 operands.push_back(*(opIt++));
2741 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002742 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002743 }
2744
John Kessenich56bab042015-09-16 10:54:31 -06002745 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002746 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002747 if (sampler.ms) {
2748 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002749 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002750 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002751 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2752 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002753 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002754 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002755 if (sampler.ms) {
2756 operands.push_back(*(opIt + 1));
2757 operands.push_back(spv::ImageOperandsSampleMask);
2758 operands.push_back(*opIt);
2759 } else
2760 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002761 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002762 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2763 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002764 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002765 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2766 builder.addCapability(spv::CapabilitySparseResidency);
2767 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2768 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2769
2770 if (sampler.ms) {
2771 operands.push_back(spv::ImageOperandsSampleMask);
2772 operands.push_back(*opIt++);
2773 }
2774
2775 // Create the return type that was a special structure
2776 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002777 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002778 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2779 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2780
2781 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2782
2783 // Decode the return type
2784 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2785 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002786 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002787 // Process image atomic operations
2788
2789 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2790 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002791 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002792
John Kessenich8c8505c2016-07-26 12:50:38 -06002793 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002794 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002795
2796 std::vector<spv::Id> operands;
2797 operands.push_back(pointer);
2798 for (; opIt != arguments.end(); ++opIt)
2799 operands.push_back(*opIt);
2800
John Kessenich8c8505c2016-07-26 12:50:38 -06002801 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002802 }
2803 }
2804
2805 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002806 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002807 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2808
John Kessenichfc51d282015-08-19 13:34:18 -06002809 // check for bias argument
2810 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002811 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002812 int nonBiasArgCount = 2;
2813 if (cracked.offset)
2814 ++nonBiasArgCount;
2815 if (cracked.grad)
2816 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002817 if (cracked.lodClamp)
2818 ++nonBiasArgCount;
2819 if (sparse)
2820 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002821
2822 if ((int)arguments.size() > nonBiasArgCount)
2823 bias = true;
2824 }
2825
John Kessenicha5c33d62016-06-02 23:45:21 -06002826 // See if the sampler param should really be just the SPV image part
2827 if (cracked.fetch) {
2828 // a fetch needs to have the image extracted first
2829 if (builder.isSampledImage(params.sampler))
2830 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2831 }
2832
John Kessenichfc51d282015-08-19 13:34:18 -06002833 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002834
John Kessenichfc51d282015-08-19 13:34:18 -06002835 params.coords = arguments[1];
2836 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002837 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002838
2839 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002840 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002841 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002842 ++extraArgs;
2843 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002844 params.Dref = arguments[2];
2845 ++extraArgs;
2846 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002847 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002848 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002849 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002850 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002851 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002852 dRefComp = builder.getNumComponents(params.coords) - 1;
2853 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002854 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2855 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002856
2857 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002858 if (cracked.lod) {
2859 params.lod = arguments[2];
2860 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002861 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2862 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2863 noImplicitLod = true;
2864 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002865
2866 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002867 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002868 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002869 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002870 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002871
2872 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002873 if (cracked.grad) {
2874 params.gradX = arguments[2 + extraArgs];
2875 params.gradY = arguments[3 + extraArgs];
2876 extraArgs += 2;
2877 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002878
2879 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002880 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002881 params.offset = arguments[2 + extraArgs];
2882 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002883 } else if (cracked.offsets) {
2884 params.offsets = arguments[2 + extraArgs];
2885 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002886 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002887
2888 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002889 if (cracked.lodClamp) {
2890 params.lodClamp = arguments[2 + extraArgs];
2891 ++extraArgs;
2892 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002893
2894 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002895 if (sparse) {
2896 params.texelOut = arguments[2 + extraArgs];
2897 ++extraArgs;
2898 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002899
2900 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002901 if (bias) {
2902 params.bias = arguments[2 + extraArgs];
2903 ++extraArgs;
2904 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002905
2906 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002907 if (cracked.gather && ! sampler.shadow) {
2908 // default component is 0, if missing, otherwise an argument
2909 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002910 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002911 ++extraArgs;
2912 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002913 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002914 }
2915 }
John Kessenichfc51d282015-08-19 13:34:18 -06002916
John Kessenich65336482016-06-16 14:06:26 -06002917 // projective component (might not to move)
2918 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2919 // are divided by the last component of P."
2920 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2921 // unused components will appear after all used components."
2922 if (cracked.proj) {
2923 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2924 int projTargetComp;
2925 switch (sampler.dim) {
2926 case glslang::Esd1D: projTargetComp = 1; break;
2927 case glslang::Esd2D: projTargetComp = 2; break;
2928 case glslang::EsdRect: projTargetComp = 2; break;
2929 default: projTargetComp = projSourceComp; break;
2930 }
2931 // copy the projective coordinate if we have to
2932 if (projTargetComp != projSourceComp) {
2933 spv::Id projComp = builder.createCompositeExtract(params.coords,
2934 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2935 projSourceComp);
2936 params.coords = builder.createCompositeInsert(projComp, params.coords,
2937 builder.getTypeId(params.coords), projTargetComp);
2938 }
2939 }
2940
John Kessenich8c8505c2016-07-26 12:50:38 -06002941 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002942}
2943
2944spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2945{
2946 // Grab the function's pointer from the previously created function
2947 spv::Function* function = functionMap[node->getName().c_str()];
2948 if (! function)
2949 return 0;
2950
2951 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2952 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2953
2954 // See comments in makeFunctions() for details about the semantics for parameter passing.
2955 //
2956 // These imply we need a four step process:
2957 // 1. Evaluate the arguments
2958 // 2. Allocate and make copies of in, out, and inout arguments
2959 // 3. Make the call
2960 // 4. Copy back the results
2961
2962 // 1. Evaluate the arguments
2963 std::vector<spv::Builder::AccessChain> lValues;
2964 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002965 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002967 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002968 // build l-value
2969 builder.clearAccessChain();
2970 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002971 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002972 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002973 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002974 // save l-value
2975 lValues.push_back(builder.getAccessChain());
2976 } else {
2977 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002978 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002979 }
2980 }
2981
2982 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2983 // copy the original into that space.
2984 //
2985 // Also, build up the list of actual arguments to pass in for the call
2986 int lValueCount = 0;
2987 int rValueCount = 0;
2988 std::vector<spv::Id> spvArgs;
2989 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002990 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002991 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002992 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002993 builder.setAccessChain(lValues[lValueCount]);
2994 arg = builder.accessChainGetLValue();
2995 ++lValueCount;
2996 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002997 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002998 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2999 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3000 // need to copy the input into output space
3001 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003002 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003003 builder.clearAccessChain();
3004 builder.setAccessChainLValue(arg);
3005 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003006 }
3007 ++lValueCount;
3008 } else {
3009 arg = rValues[rValueCount];
3010 ++rValueCount;
3011 }
3012 spvArgs.push_back(arg);
3013 }
3014
3015 // 3. Make the call.
3016 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003017 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003018
3019 // 4. Copy back out an "out" arguments.
3020 lValueCount = 0;
3021 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003022 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003023 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3024 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3025 spv::Id copy = builder.createLoad(spvArgs[a]);
3026 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003027 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003028 }
3029 ++lValueCount;
3030 }
3031 }
3032
3033 return result;
3034}
3035
3036// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003037spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3038 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003039 spv::Id typeId, spv::Id left, spv::Id right,
3040 glslang::TBasicType typeProxy, bool reduceComparison)
3041{
Rex Xu8ff43de2016-04-22 16:51:45 +08003042 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003043 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08003044 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003045
3046 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003047 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003048 bool comparison = false;
3049
3050 switch (op) {
3051 case glslang::EOpAdd:
3052 case glslang::EOpAddAssign:
3053 if (isFloat)
3054 binOp = spv::OpFAdd;
3055 else
3056 binOp = spv::OpIAdd;
3057 break;
3058 case glslang::EOpSub:
3059 case glslang::EOpSubAssign:
3060 if (isFloat)
3061 binOp = spv::OpFSub;
3062 else
3063 binOp = spv::OpISub;
3064 break;
3065 case glslang::EOpMul:
3066 case glslang::EOpMulAssign:
3067 if (isFloat)
3068 binOp = spv::OpFMul;
3069 else
3070 binOp = spv::OpIMul;
3071 break;
3072 case glslang::EOpVectorTimesScalar:
3073 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003074 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003075 if (builder.isVector(right))
3076 std::swap(left, right);
3077 assert(builder.isScalar(right));
3078 needMatchingVectors = false;
3079 binOp = spv::OpVectorTimesScalar;
3080 } else
3081 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003082 break;
3083 case glslang::EOpVectorTimesMatrix:
3084 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003085 binOp = spv::OpVectorTimesMatrix;
3086 break;
3087 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003088 binOp = spv::OpMatrixTimesVector;
3089 break;
3090 case glslang::EOpMatrixTimesScalar:
3091 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003092 binOp = spv::OpMatrixTimesScalar;
3093 break;
3094 case glslang::EOpMatrixTimesMatrix:
3095 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003096 binOp = spv::OpMatrixTimesMatrix;
3097 break;
3098 case glslang::EOpOuterProduct:
3099 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003100 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003101 break;
3102
3103 case glslang::EOpDiv:
3104 case glslang::EOpDivAssign:
3105 if (isFloat)
3106 binOp = spv::OpFDiv;
3107 else if (isUnsigned)
3108 binOp = spv::OpUDiv;
3109 else
3110 binOp = spv::OpSDiv;
3111 break;
3112 case glslang::EOpMod:
3113 case glslang::EOpModAssign:
3114 if (isFloat)
3115 binOp = spv::OpFMod;
3116 else if (isUnsigned)
3117 binOp = spv::OpUMod;
3118 else
3119 binOp = spv::OpSMod;
3120 break;
3121 case glslang::EOpRightShift:
3122 case glslang::EOpRightShiftAssign:
3123 if (isUnsigned)
3124 binOp = spv::OpShiftRightLogical;
3125 else
3126 binOp = spv::OpShiftRightArithmetic;
3127 break;
3128 case glslang::EOpLeftShift:
3129 case glslang::EOpLeftShiftAssign:
3130 binOp = spv::OpShiftLeftLogical;
3131 break;
3132 case glslang::EOpAnd:
3133 case glslang::EOpAndAssign:
3134 binOp = spv::OpBitwiseAnd;
3135 break;
3136 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003137 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 binOp = spv::OpLogicalAnd;
3139 break;
3140 case glslang::EOpInclusiveOr:
3141 case glslang::EOpInclusiveOrAssign:
3142 binOp = spv::OpBitwiseOr;
3143 break;
3144 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003145 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003146 binOp = spv::OpLogicalOr;
3147 break;
3148 case glslang::EOpExclusiveOr:
3149 case glslang::EOpExclusiveOrAssign:
3150 binOp = spv::OpBitwiseXor;
3151 break;
3152 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003153 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003154 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003155 break;
3156
3157 case glslang::EOpLessThan:
3158 case glslang::EOpGreaterThan:
3159 case glslang::EOpLessThanEqual:
3160 case glslang::EOpGreaterThanEqual:
3161 case glslang::EOpEqual:
3162 case glslang::EOpNotEqual:
3163 case glslang::EOpVectorEqual:
3164 case glslang::EOpVectorNotEqual:
3165 comparison = true;
3166 break;
3167 default:
3168 break;
3169 }
3170
John Kessenich7c1aa102015-10-15 13:29:11 -06003171 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003172 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003173 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003174 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003175 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003176
3177 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003178 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003179 builder.promoteScalar(precision, left, right);
3180
qining25262b32016-05-06 17:25:16 -04003181 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3182 addDecoration(result, noContraction);
3183 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003184 }
3185
3186 if (! comparison)
3187 return 0;
3188
John Kessenich7c1aa102015-10-15 13:29:11 -06003189 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003190
John Kessenich4583b612016-08-07 19:14:22 -06003191 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3192 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003193 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003194
3195 switch (op) {
3196 case glslang::EOpLessThan:
3197 if (isFloat)
3198 binOp = spv::OpFOrdLessThan;
3199 else if (isUnsigned)
3200 binOp = spv::OpULessThan;
3201 else
3202 binOp = spv::OpSLessThan;
3203 break;
3204 case glslang::EOpGreaterThan:
3205 if (isFloat)
3206 binOp = spv::OpFOrdGreaterThan;
3207 else if (isUnsigned)
3208 binOp = spv::OpUGreaterThan;
3209 else
3210 binOp = spv::OpSGreaterThan;
3211 break;
3212 case glslang::EOpLessThanEqual:
3213 if (isFloat)
3214 binOp = spv::OpFOrdLessThanEqual;
3215 else if (isUnsigned)
3216 binOp = spv::OpULessThanEqual;
3217 else
3218 binOp = spv::OpSLessThanEqual;
3219 break;
3220 case glslang::EOpGreaterThanEqual:
3221 if (isFloat)
3222 binOp = spv::OpFOrdGreaterThanEqual;
3223 else if (isUnsigned)
3224 binOp = spv::OpUGreaterThanEqual;
3225 else
3226 binOp = spv::OpSGreaterThanEqual;
3227 break;
3228 case glslang::EOpEqual:
3229 case glslang::EOpVectorEqual:
3230 if (isFloat)
3231 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003232 else if (isBool)
3233 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003234 else
3235 binOp = spv::OpIEqual;
3236 break;
3237 case glslang::EOpNotEqual:
3238 case glslang::EOpVectorNotEqual:
3239 if (isFloat)
3240 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003241 else if (isBool)
3242 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003243 else
3244 binOp = spv::OpINotEqual;
3245 break;
3246 default:
3247 break;
3248 }
3249
qining25262b32016-05-06 17:25:16 -04003250 if (binOp != spv::OpNop) {
3251 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3252 addDecoration(result, noContraction);
3253 return builder.setPrecision(result, precision);
3254 }
John Kessenich140f3df2015-06-26 16:58:36 -06003255
3256 return 0;
3257}
3258
John Kessenich04bb8a02015-12-12 12:28:14 -07003259//
3260// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3261// These can be any of:
3262//
3263// matrix * scalar
3264// scalar * matrix
3265// matrix * matrix linear algebraic
3266// matrix * vector
3267// vector * matrix
3268// matrix * matrix componentwise
3269// matrix op matrix op in {+, -, /}
3270// matrix op scalar op in {+, -, /}
3271// scalar op matrix op in {+, -, /}
3272//
qining25262b32016-05-06 17:25:16 -04003273spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003274{
3275 bool firstClass = true;
3276
3277 // First, handle first-class matrix operations (* and matrix/scalar)
3278 switch (op) {
3279 case spv::OpFDiv:
3280 if (builder.isMatrix(left) && builder.isScalar(right)) {
3281 // turn matrix / scalar into a multiply...
3282 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3283 op = spv::OpMatrixTimesScalar;
3284 } else
3285 firstClass = false;
3286 break;
3287 case spv::OpMatrixTimesScalar:
3288 if (builder.isMatrix(right))
3289 std::swap(left, right);
3290 assert(builder.isScalar(right));
3291 break;
3292 case spv::OpVectorTimesMatrix:
3293 assert(builder.isVector(left));
3294 assert(builder.isMatrix(right));
3295 break;
3296 case spv::OpMatrixTimesVector:
3297 assert(builder.isMatrix(left));
3298 assert(builder.isVector(right));
3299 break;
3300 case spv::OpMatrixTimesMatrix:
3301 assert(builder.isMatrix(left));
3302 assert(builder.isMatrix(right));
3303 break;
3304 default:
3305 firstClass = false;
3306 break;
3307 }
3308
qining25262b32016-05-06 17:25:16 -04003309 if (firstClass) {
3310 spv::Id result = builder.createBinOp(op, typeId, left, right);
3311 addDecoration(result, noContraction);
3312 return builder.setPrecision(result, precision);
3313 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003314
LoopDawg592860c2016-06-09 08:57:35 -06003315 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003316 // The result type of all of them is the same type as the (a) matrix operand.
3317 // The algorithm is to:
3318 // - break the matrix(es) into vectors
3319 // - smear any scalar to a vector
3320 // - do vector operations
3321 // - make a matrix out the vector results
3322 switch (op) {
3323 case spv::OpFAdd:
3324 case spv::OpFSub:
3325 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003326 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003327 case spv::OpFMul:
3328 {
3329 // one time set up...
3330 bool leftMat = builder.isMatrix(left);
3331 bool rightMat = builder.isMatrix(right);
3332 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3333 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3334 spv::Id scalarType = builder.getScalarTypeId(typeId);
3335 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3336 std::vector<spv::Id> results;
3337 spv::Id smearVec = spv::NoResult;
3338 if (builder.isScalar(left))
3339 smearVec = builder.smearScalar(precision, left, vecType);
3340 else if (builder.isScalar(right))
3341 smearVec = builder.smearScalar(precision, right, vecType);
3342
3343 // do each vector op
3344 for (unsigned int c = 0; c < numCols; ++c) {
3345 std::vector<unsigned int> indexes;
3346 indexes.push_back(c);
3347 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3348 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003349 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3350 addDecoration(result, noContraction);
3351 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003352 }
3353
3354 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003355 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003356 }
3357 default:
3358 assert(0);
3359 return spv::NoResult;
3360 }
3361}
3362
qining25262b32016-05-06 17:25:16 -04003363spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003364{
3365 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003366 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003367 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003368 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003369 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003370
3371 switch (op) {
3372 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003373 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003374 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003375 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003376 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003377 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003378 unaryOp = spv::OpSNegate;
3379 break;
3380
3381 case glslang::EOpLogicalNot:
3382 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003383 unaryOp = spv::OpLogicalNot;
3384 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003385 case glslang::EOpBitwiseNot:
3386 unaryOp = spv::OpNot;
3387 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003388
John Kessenich140f3df2015-06-26 16:58:36 -06003389 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003390 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003391 break;
3392 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003393 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003394 break;
3395 case glslang::EOpTranspose:
3396 unaryOp = spv::OpTranspose;
3397 break;
3398
3399 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003400 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003401 break;
3402 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003403 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003404 break;
3405 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003410 break;
3411 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003412 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003415 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003416 break;
3417 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003418 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003419 break;
3420 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003421 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003422 break;
3423
3424 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003425 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003426 break;
3427 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003428 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003429 break;
3430 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003431 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003432 break;
3433 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003434 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003435 break;
3436 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003437 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003438 break;
3439 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003440 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003441 break;
3442
3443 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003444 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003445 break;
3446 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003447 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003448 break;
3449
3450 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003451 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003452 break;
3453 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003454 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003455 break;
3456 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003457 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003458 break;
3459 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003460 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003461 break;
3462 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003463 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003464 break;
3465 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003466 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468
3469 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003470 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003471 break;
3472 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003473 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003474 break;
3475 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003476 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003477 break;
3478 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003482 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003483 break;
3484 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003485 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487
3488 case glslang::EOpIsNan:
3489 unaryOp = spv::OpIsNan;
3490 break;
3491 case glslang::EOpIsInf:
3492 unaryOp = spv::OpIsInf;
3493 break;
LoopDawg592860c2016-06-09 08:57:35 -06003494 case glslang::EOpIsFinite:
3495 unaryOp = spv::OpIsFinite;
3496 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003497
Rex Xucbc426e2015-12-15 16:03:10 +08003498 case glslang::EOpFloatBitsToInt:
3499 case glslang::EOpFloatBitsToUint:
3500 case glslang::EOpIntBitsToFloat:
3501 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003502 case glslang::EOpDoubleBitsToInt64:
3503 case glslang::EOpDoubleBitsToUint64:
3504 case glslang::EOpInt64BitsToDouble:
3505 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003506 unaryOp = spv::OpBitcast;
3507 break;
3508
John Kessenich140f3df2015-06-26 16:58:36 -06003509 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003510 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003511 break;
3512 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003513 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003514 break;
3515 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 break;
3518 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003519 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003522 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 break;
3524 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003526 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003527 case glslang::EOpPackSnorm4x8:
3528 libCall = spv::GLSLstd450PackSnorm4x8;
3529 break;
3530 case glslang::EOpUnpackSnorm4x8:
3531 libCall = spv::GLSLstd450UnpackSnorm4x8;
3532 break;
3533 case glslang::EOpPackUnorm4x8:
3534 libCall = spv::GLSLstd450PackUnorm4x8;
3535 break;
3536 case glslang::EOpUnpackUnorm4x8:
3537 libCall = spv::GLSLstd450UnpackUnorm4x8;
3538 break;
3539 case glslang::EOpPackDouble2x32:
3540 libCall = spv::GLSLstd450PackDouble2x32;
3541 break;
3542 case glslang::EOpUnpackDouble2x32:
3543 libCall = spv::GLSLstd450UnpackDouble2x32;
3544 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003545
Rex Xu8ff43de2016-04-22 16:51:45 +08003546 case glslang::EOpPackInt2x32:
3547 case glslang::EOpUnpackInt2x32:
3548 case glslang::EOpPackUint2x32:
3549 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003550 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003551 break;
3552
John Kessenich140f3df2015-06-26 16:58:36 -06003553 case glslang::EOpDPdx:
3554 unaryOp = spv::OpDPdx;
3555 break;
3556 case glslang::EOpDPdy:
3557 unaryOp = spv::OpDPdy;
3558 break;
3559 case glslang::EOpFwidth:
3560 unaryOp = spv::OpFwidth;
3561 break;
3562 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003563 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003564 unaryOp = spv::OpDPdxFine;
3565 break;
3566 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003567 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003568 unaryOp = spv::OpDPdyFine;
3569 break;
3570 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003571 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003572 unaryOp = spv::OpFwidthFine;
3573 break;
3574 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003575 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003576 unaryOp = spv::OpDPdxCoarse;
3577 break;
3578 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003579 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003580 unaryOp = spv::OpDPdyCoarse;
3581 break;
3582 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003583 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003584 unaryOp = spv::OpFwidthCoarse;
3585 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003586 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003587 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003588 libCall = spv::GLSLstd450InterpolateAtCentroid;
3589 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003590 case glslang::EOpAny:
3591 unaryOp = spv::OpAny;
3592 break;
3593 case glslang::EOpAll:
3594 unaryOp = spv::OpAll;
3595 break;
3596
3597 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003598 if (isFloat)
3599 libCall = spv::GLSLstd450FAbs;
3600 else
3601 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 if (isFloat)
3605 libCall = spv::GLSLstd450FSign;
3606 else
3607 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003608 break;
3609
John Kessenichfc51d282015-08-19 13:34:18 -06003610 case glslang::EOpAtomicCounterIncrement:
3611 case glslang::EOpAtomicCounterDecrement:
3612 case glslang::EOpAtomicCounter:
3613 {
3614 // Handle all of the atomics in one place, in createAtomicOperation()
3615 std::vector<spv::Id> operands;
3616 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003617 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003618 }
3619
John Kessenichfc51d282015-08-19 13:34:18 -06003620 case glslang::EOpBitFieldReverse:
3621 unaryOp = spv::OpBitReverse;
3622 break;
3623 case glslang::EOpBitCount:
3624 unaryOp = spv::OpBitCount;
3625 break;
3626 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003627 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003628 break;
3629 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003630 if (isUnsigned)
3631 libCall = spv::GLSLstd450FindUMsb;
3632 else
3633 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003634 break;
3635
Rex Xu574ab042016-04-14 16:53:07 +08003636 case glslang::EOpBallot:
3637 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003638 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003639 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003640 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003641#ifdef AMD_EXTENSIONS
3642 case glslang::EOpMinInvocations:
3643 case glslang::EOpMaxInvocations:
3644 case glslang::EOpAddInvocations:
3645 case glslang::EOpMinInvocationsNonUniform:
3646 case glslang::EOpMaxInvocationsNonUniform:
3647 case glslang::EOpAddInvocationsNonUniform:
3648#endif
Rex Xu51596642016-09-21 18:56:12 +08003649 {
3650 std::vector<spv::Id> operands;
3651 operands.push_back(operand);
3652 return createInvocationsOperation(op, typeId, operands, typeProxy);
3653 }
Rex Xu9d93a232016-05-05 12:30:44 +08003654
3655#ifdef AMD_EXTENSIONS
3656 case glslang::EOpMbcnt:
3657 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3658 libCall = spv::MbcntAMD;
3659 break;
3660
3661 case glslang::EOpCubeFaceIndex:
3662 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3663 libCall = spv::CubeFaceIndexAMD;
3664 break;
3665
3666 case glslang::EOpCubeFaceCoord:
3667 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3668 libCall = spv::CubeFaceCoordAMD;
3669 break;
3670#endif
Rex Xu338b1852016-05-05 20:38:33 +08003671
John Kessenich140f3df2015-06-26 16:58:36 -06003672 default:
3673 return 0;
3674 }
3675
3676 spv::Id id;
3677 if (libCall >= 0) {
3678 std::vector<spv::Id> args;
3679 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003680 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003681 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003682 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003683 }
John Kessenich140f3df2015-06-26 16:58:36 -06003684
qining25262b32016-05-06 17:25:16 -04003685 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003686 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003687}
3688
John Kessenich7a53f762016-01-20 11:19:27 -07003689// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003690spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07003691{
3692 // Handle unary operations vector by vector.
3693 // The result type is the same type as the original type.
3694 // The algorithm is to:
3695 // - break the matrix into vectors
3696 // - apply the operation to each vector
3697 // - make a matrix out the vector results
3698
3699 // get the types sorted out
3700 int numCols = builder.getNumColumns(operand);
3701 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003702 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3703 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003704 std::vector<spv::Id> results;
3705
3706 // do each vector op
3707 for (int c = 0; c < numCols; ++c) {
3708 std::vector<unsigned int> indexes;
3709 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003710 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3711 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3712 addDecoration(destVec, noContraction);
3713 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003714 }
3715
3716 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003717 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003718}
3719
Rex Xu73e3ce72016-04-27 18:48:17 +08003720spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003721{
3722 spv::Op convOp = spv::OpNop;
3723 spv::Id zero = 0;
3724 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003725 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003726
3727 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3728
3729 switch (op) {
3730 case glslang::EOpConvIntToBool:
3731 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003732 case glslang::EOpConvInt64ToBool:
3733 case glslang::EOpConvUint64ToBool:
3734 zero = (op == glslang::EOpConvInt64ToBool ||
3735 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003736 zero = makeSmearedConstant(zero, vectorSize);
3737 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3738
3739 case glslang::EOpConvFloatToBool:
3740 zero = builder.makeFloatConstant(0.0F);
3741 zero = makeSmearedConstant(zero, vectorSize);
3742 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3743
3744 case glslang::EOpConvDoubleToBool:
3745 zero = builder.makeDoubleConstant(0.0);
3746 zero = makeSmearedConstant(zero, vectorSize);
3747 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3748
3749 case glslang::EOpConvBoolToFloat:
3750 convOp = spv::OpSelect;
3751 zero = builder.makeFloatConstant(0.0);
3752 one = builder.makeFloatConstant(1.0);
3753 break;
3754 case glslang::EOpConvBoolToDouble:
3755 convOp = spv::OpSelect;
3756 zero = builder.makeDoubleConstant(0.0);
3757 one = builder.makeDoubleConstant(1.0);
3758 break;
3759 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003760 case glslang::EOpConvBoolToInt64:
3761 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3762 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003763 convOp = spv::OpSelect;
3764 break;
3765 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003766 case glslang::EOpConvBoolToUint64:
3767 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3768 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003769 convOp = spv::OpSelect;
3770 break;
3771
3772 case glslang::EOpConvIntToFloat:
3773 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003774 case glslang::EOpConvInt64ToFloat:
3775 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003776 convOp = spv::OpConvertSToF;
3777 break;
3778
3779 case glslang::EOpConvUintToFloat:
3780 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003781 case glslang::EOpConvUint64ToFloat:
3782 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003783 convOp = spv::OpConvertUToF;
3784 break;
3785
3786 case glslang::EOpConvDoubleToFloat:
3787 case glslang::EOpConvFloatToDouble:
3788 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003789 if (builder.isMatrixType(destType))
3790 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003791 break;
3792
3793 case glslang::EOpConvFloatToInt:
3794 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003795 case glslang::EOpConvFloatToInt64:
3796 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003797 convOp = spv::OpConvertFToS;
3798 break;
3799
3800 case glslang::EOpConvUintToInt:
3801 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003802 case glslang::EOpConvUint64ToInt64:
3803 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003804 if (builder.isInSpecConstCodeGenMode()) {
3805 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003806 zero = (op == glslang::EOpConvUint64ToInt64 ||
3807 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003808 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003809 // Use OpIAdd, instead of OpBitcast to do the conversion when
3810 // generating for OpSpecConstantOp instruction.
3811 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3812 }
3813 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003814 convOp = spv::OpBitcast;
3815 break;
3816
3817 case glslang::EOpConvFloatToUint:
3818 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003819 case glslang::EOpConvFloatToUint64:
3820 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003821 convOp = spv::OpConvertFToU;
3822 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003823
3824 case glslang::EOpConvIntToInt64:
3825 case glslang::EOpConvInt64ToInt:
3826 convOp = spv::OpSConvert;
3827 break;
3828
3829 case glslang::EOpConvUintToUint64:
3830 case glslang::EOpConvUint64ToUint:
3831 convOp = spv::OpUConvert;
3832 break;
3833
3834 case glslang::EOpConvIntToUint64:
3835 case glslang::EOpConvInt64ToUint:
3836 case glslang::EOpConvUint64ToInt:
3837 case glslang::EOpConvUintToInt64:
3838 // OpSConvert/OpUConvert + OpBitCast
3839 switch (op) {
3840 case glslang::EOpConvIntToUint64:
3841 convOp = spv::OpSConvert;
3842 type = builder.makeIntType(64);
3843 break;
3844 case glslang::EOpConvInt64ToUint:
3845 convOp = spv::OpSConvert;
3846 type = builder.makeIntType(32);
3847 break;
3848 case glslang::EOpConvUint64ToInt:
3849 convOp = spv::OpUConvert;
3850 type = builder.makeUintType(32);
3851 break;
3852 case glslang::EOpConvUintToInt64:
3853 convOp = spv::OpUConvert;
3854 type = builder.makeUintType(64);
3855 break;
3856 default:
3857 assert(0);
3858 break;
3859 }
3860
3861 if (vectorSize > 0)
3862 type = builder.makeVectorType(type, vectorSize);
3863
3864 operand = builder.createUnaryOp(convOp, type, operand);
3865
3866 if (builder.isInSpecConstCodeGenMode()) {
3867 // Build zero scalar or vector for OpIAdd.
3868 zero = (op == glslang::EOpConvIntToUint64 ||
3869 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3870 zero = makeSmearedConstant(zero, vectorSize);
3871 // Use OpIAdd, instead of OpBitcast to do the conversion when
3872 // generating for OpSpecConstantOp instruction.
3873 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3874 }
3875 // For normal run-time conversion instruction, use OpBitcast.
3876 convOp = spv::OpBitcast;
3877 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003878 default:
3879 break;
3880 }
3881
3882 spv::Id result = 0;
3883 if (convOp == spv::OpNop)
3884 return result;
3885
3886 if (convOp == spv::OpSelect) {
3887 zero = makeSmearedConstant(zero, vectorSize);
3888 one = makeSmearedConstant(one, vectorSize);
3889 result = builder.createTriOp(convOp, destType, operand, one, zero);
3890 } else
3891 result = builder.createUnaryOp(convOp, destType, operand);
3892
John Kessenich32cfd492016-02-02 12:37:46 -07003893 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003894}
3895
3896spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3897{
3898 if (vectorSize == 0)
3899 return constant;
3900
3901 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3902 std::vector<spv::Id> components;
3903 for (int c = 0; c < vectorSize; ++c)
3904 components.push_back(constant);
3905 return builder.makeCompositeConstant(vectorTypeId, components);
3906}
3907
John Kessenich426394d2015-07-23 10:22:48 -06003908// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003909spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06003910{
3911 spv::Op opCode = spv::OpNop;
3912
3913 switch (op) {
3914 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003915 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003916 opCode = spv::OpAtomicIAdd;
3917 break;
3918 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003919 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003920 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003921 break;
3922 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003923 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003924 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003925 break;
3926 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003927 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003928 opCode = spv::OpAtomicAnd;
3929 break;
3930 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003931 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003932 opCode = spv::OpAtomicOr;
3933 break;
3934 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003935 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003936 opCode = spv::OpAtomicXor;
3937 break;
3938 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003939 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003940 opCode = spv::OpAtomicExchange;
3941 break;
3942 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003943 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003944 opCode = spv::OpAtomicCompareExchange;
3945 break;
3946 case glslang::EOpAtomicCounterIncrement:
3947 opCode = spv::OpAtomicIIncrement;
3948 break;
3949 case glslang::EOpAtomicCounterDecrement:
3950 opCode = spv::OpAtomicIDecrement;
3951 break;
3952 case glslang::EOpAtomicCounter:
3953 opCode = spv::OpAtomicLoad;
3954 break;
3955 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003956 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003957 break;
3958 }
3959
3960 // Sort out the operands
3961 // - mapping from glslang -> SPV
3962 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003963 // - compare-exchange swaps the value and comparator
3964 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003965 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3966 auto opIt = operands.begin(); // walk the glslang operands
3967 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003968 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3969 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3970 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003971 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3972 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003973 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003974 spvAtomicOperands.push_back(*(opIt + 1));
3975 spvAtomicOperands.push_back(*opIt);
3976 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003977 }
John Kessenich426394d2015-07-23 10:22:48 -06003978
John Kessenich3e60a6f2015-09-14 22:45:16 -06003979 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003980 for (; opIt != operands.end(); ++opIt)
3981 spvAtomicOperands.push_back(*opIt);
3982
3983 return builder.createOp(opCode, typeId, spvAtomicOperands);
3984}
3985
John Kessenich91cef522016-05-05 16:45:40 -06003986// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08003987spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003988{
Rex Xu9d93a232016-05-05 12:30:44 +08003989 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3990 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3991
Rex Xu51596642016-09-21 18:56:12 +08003992 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06003993
Rex Xu51596642016-09-21 18:56:12 +08003994 std::vector<spv::Id> spvGroupOperands;
3995 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
3996 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
3997 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
3998 } else {
3999 builder.addCapability(spv::CapabilityGroups);
4000
4001 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004002#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004003 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4004 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4005 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004006#endif
Rex Xu51596642016-09-21 18:56:12 +08004007 }
4008
4009 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4010 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004011
4012 switch (op) {
4013 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004014 opCode = spv::OpGroupAny;
4015 break;
John Kessenich91cef522016-05-05 16:45:40 -06004016 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004017 opCode = spv::OpGroupAll;
4018 break;
John Kessenich91cef522016-05-05 16:45:40 -06004019 case glslang::EOpAllInvocationsEqual:
4020 {
Rex Xu51596642016-09-21 18:56:12 +08004021 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4022 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004023
4024 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4025 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4026 }
Rex Xu51596642016-09-21 18:56:12 +08004027
4028 case glslang::EOpReadInvocation:
4029 opCode = spv::OpGroupBroadcast;
4030 break;
4031 case glslang::EOpReadFirstInvocation:
4032 opCode = spv::OpSubgroupFirstInvocationKHR;
4033 break;
4034 case glslang::EOpBallot:
4035 {
4036 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4037 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4038 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4039 //
4040 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4041 //
4042 spv::Id uintType = builder.makeUintType(32);
4043 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4044 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4045
4046 std::vector<spv::Id> components;
4047 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4048 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4049
4050 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4051 return builder.createUnaryOp(spv::OpBitcast, typeId,
4052 builder.createCompositeConstruct(uvec2Type, components));
4053 }
4054
Rex Xu9d93a232016-05-05 12:30:44 +08004055#ifdef AMD_EXTENSIONS
4056 case glslang::EOpMinInvocations:
4057 case glslang::EOpMaxInvocations:
4058 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004059 if (op == glslang::EOpMinInvocations) {
4060 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004061 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004062 else {
4063 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004064 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004065 else
Rex Xu51596642016-09-21 18:56:12 +08004066 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004067 }
4068 } else if (op == glslang::EOpMaxInvocations) {
4069 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004070 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004071 else {
4072 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004073 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004074 else
Rex Xu51596642016-09-21 18:56:12 +08004075 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004076 }
4077 } else {
4078 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004079 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004080 else
Rex Xu51596642016-09-21 18:56:12 +08004081 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004082 }
4083
Rex Xu2bbbe062016-08-23 15:41:05 +08004084 if (builder.isVectorType(typeId))
Rex Xu51596642016-09-21 18:56:12 +08004085 return CreateInvocationsVectorOperation(opCode, typeId, operands[0]);
4086
4087 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004088 case glslang::EOpMinInvocationsNonUniform:
4089 case glslang::EOpMaxInvocationsNonUniform:
4090 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004091 if (op == glslang::EOpMinInvocationsNonUniform) {
4092 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004093 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004094 else {
4095 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004096 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004097 else
Rex Xu51596642016-09-21 18:56:12 +08004098 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004099 }
4100 }
4101 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4102 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004103 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004104 else {
4105 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004106 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004107 else
Rex Xu51596642016-09-21 18:56:12 +08004108 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004109 }
4110 }
4111 else {
4112 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004113 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004114 else
Rex Xu51596642016-09-21 18:56:12 +08004115 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004116 }
4117
Rex Xu2bbbe062016-08-23 15:41:05 +08004118 if (builder.isVectorType(typeId))
Rex Xu51596642016-09-21 18:56:12 +08004119 return CreateInvocationsVectorOperation(opCode, typeId, operands[0]);
4120
4121 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004122#endif
John Kessenich91cef522016-05-05 16:45:40 -06004123 default:
4124 logger->missingFunctionality("invocation operation");
4125 return spv::NoResult;
4126 }
Rex Xu51596642016-09-21 18:56:12 +08004127
4128 assert(opCode != spv::OpNop);
4129 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004130}
4131
Rex Xu2bbbe062016-08-23 15:41:05 +08004132#ifdef AMD_EXTENSIONS
4133// Create group invocation operations on a vector
4134spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand)
4135{
4136 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4137 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4138 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd ||
4139 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4140 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4141 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
4142
4143 // Handle group invocation operations scalar by scalar.
4144 // The result type is the same type as the original type.
4145 // The algorithm is to:
4146 // - break the vector into scalars
4147 // - apply the operation to each scalar
4148 // - make a vector out the scalar results
4149
4150 // get the types sorted out
4151 int numComponents = builder.getNumComponents(operand);
4152 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operand));
4153 std::vector<spv::Id> results;
4154
4155 // do each scalar op
4156 for (int comp = 0; comp < numComponents; ++comp) {
4157 std::vector<unsigned int> indexes;
4158 indexes.push_back(comp);
4159 spv::Id scalar = builder.createCompositeExtract(operand, scalarType, indexes);
4160
4161 std::vector<spv::Id> operands;
4162 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4163 operands.push_back(spv::GroupOperationReduce);
4164 operands.push_back(scalar);
4165
4166 results.push_back(builder.createOp(op, scalarType, operands));
4167 }
4168
4169 // put the pieces together
4170 return builder.createCompositeConstruct(typeId, results);
4171}
4172#endif
4173
John Kessenich5e4b1242015-08-06 22:53:06 -06004174spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004175{
Rex Xu8ff43de2016-04-22 16:51:45 +08004176 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004177 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
4178
John Kessenich140f3df2015-06-26 16:58:36 -06004179 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004180 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004181 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004182 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004183 spv::Id typeId0 = 0;
4184 if (consumedOperands > 0)
4185 typeId0 = builder.getTypeId(operands[0]);
4186 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004187
4188 switch (op) {
4189 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004190 if (isFloat)
4191 libCall = spv::GLSLstd450FMin;
4192 else if (isUnsigned)
4193 libCall = spv::GLSLstd450UMin;
4194 else
4195 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004196 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004197 break;
4198 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004199 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004200 break;
4201 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004202 if (isFloat)
4203 libCall = spv::GLSLstd450FMax;
4204 else if (isUnsigned)
4205 libCall = spv::GLSLstd450UMax;
4206 else
4207 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004208 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004209 break;
4210 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004211 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004212 break;
4213 case glslang::EOpDot:
4214 opCode = spv::OpDot;
4215 break;
4216 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004217 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004218 break;
4219
4220 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004221 if (isFloat)
4222 libCall = spv::GLSLstd450FClamp;
4223 else if (isUnsigned)
4224 libCall = spv::GLSLstd450UClamp;
4225 else
4226 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004227 builder.promoteScalar(precision, operands.front(), operands[1]);
4228 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004229 break;
4230 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004231 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4232 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004233 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004234 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004235 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004236 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004237 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004238 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004239 break;
4240 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004241 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004242 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004243 break;
4244 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004245 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004246 builder.promoteScalar(precision, operands[0], operands[2]);
4247 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004248 break;
4249
4250 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004251 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004252 break;
4253 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004254 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004255 break;
4256 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004257 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004258 break;
4259 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004260 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004261 break;
4262 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004263 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004264 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004265 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004266 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004267 libCall = spv::GLSLstd450InterpolateAtSample;
4268 break;
4269 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004270 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004271 libCall = spv::GLSLstd450InterpolateAtOffset;
4272 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004273 case glslang::EOpAddCarry:
4274 opCode = spv::OpIAddCarry;
4275 typeId = builder.makeStructResultType(typeId0, typeId0);
4276 consumedOperands = 2;
4277 break;
4278 case glslang::EOpSubBorrow:
4279 opCode = spv::OpISubBorrow;
4280 typeId = builder.makeStructResultType(typeId0, typeId0);
4281 consumedOperands = 2;
4282 break;
4283 case glslang::EOpUMulExtended:
4284 opCode = spv::OpUMulExtended;
4285 typeId = builder.makeStructResultType(typeId0, typeId0);
4286 consumedOperands = 2;
4287 break;
4288 case glslang::EOpIMulExtended:
4289 opCode = spv::OpSMulExtended;
4290 typeId = builder.makeStructResultType(typeId0, typeId0);
4291 consumedOperands = 2;
4292 break;
4293 case glslang::EOpBitfieldExtract:
4294 if (isUnsigned)
4295 opCode = spv::OpBitFieldUExtract;
4296 else
4297 opCode = spv::OpBitFieldSExtract;
4298 break;
4299 case glslang::EOpBitfieldInsert:
4300 opCode = spv::OpBitFieldInsert;
4301 break;
4302
4303 case glslang::EOpFma:
4304 libCall = spv::GLSLstd450Fma;
4305 break;
4306 case glslang::EOpFrexp:
4307 libCall = spv::GLSLstd450FrexpStruct;
4308 if (builder.getNumComponents(operands[0]) == 1)
4309 frexpIntType = builder.makeIntegerType(32, true);
4310 else
4311 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4312 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4313 consumedOperands = 1;
4314 break;
4315 case glslang::EOpLdexp:
4316 libCall = spv::GLSLstd450Ldexp;
4317 break;
4318
Rex Xu574ab042016-04-14 16:53:07 +08004319 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004320 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004321
Rex Xu9d93a232016-05-05 12:30:44 +08004322#ifdef AMD_EXTENSIONS
4323 case glslang::EOpSwizzleInvocations:
4324 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4325 libCall = spv::SwizzleInvocationsAMD;
4326 break;
4327 case glslang::EOpSwizzleInvocationsMasked:
4328 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4329 libCall = spv::SwizzleInvocationsMaskedAMD;
4330 break;
4331 case glslang::EOpWriteInvocation:
4332 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4333 libCall = spv::WriteInvocationAMD;
4334 break;
4335
4336 case glslang::EOpMin3:
4337 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4338 if (isFloat)
4339 libCall = spv::FMin3AMD;
4340 else {
4341 if (isUnsigned)
4342 libCall = spv::UMin3AMD;
4343 else
4344 libCall = spv::SMin3AMD;
4345 }
4346 break;
4347 case glslang::EOpMax3:
4348 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4349 if (isFloat)
4350 libCall = spv::FMax3AMD;
4351 else {
4352 if (isUnsigned)
4353 libCall = spv::UMax3AMD;
4354 else
4355 libCall = spv::SMax3AMD;
4356 }
4357 break;
4358 case glslang::EOpMid3:
4359 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4360 if (isFloat)
4361 libCall = spv::FMid3AMD;
4362 else {
4363 if (isUnsigned)
4364 libCall = spv::UMid3AMD;
4365 else
4366 libCall = spv::SMid3AMD;
4367 }
4368 break;
4369
4370 case glslang::EOpInterpolateAtVertex:
4371 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4372 libCall = spv::InterpolateAtVertexAMD;
4373 break;
4374#endif
4375
John Kessenich140f3df2015-06-26 16:58:36 -06004376 default:
4377 return 0;
4378 }
4379
4380 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004381 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004382 // Use an extended instruction from the standard library.
4383 // Construct the call arguments, without modifying the original operands vector.
4384 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4385 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004386 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004387 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004388 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004389 case 0:
4390 // should all be handled by visitAggregate and createNoArgOperation
4391 assert(0);
4392 return 0;
4393 case 1:
4394 // should all be handled by createUnaryOperation
4395 assert(0);
4396 return 0;
4397 case 2:
4398 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4399 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004400 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004401 // anything 3 or over doesn't have l-value operands, so all should be consumed
4402 assert(consumedOperands == operands.size());
4403 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004404 break;
4405 }
4406 }
4407
John Kessenich55e7d112015-11-15 21:33:39 -07004408 // Decode the return types that were structures
4409 switch (op) {
4410 case glslang::EOpAddCarry:
4411 case glslang::EOpSubBorrow:
4412 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4413 id = builder.createCompositeExtract(id, typeId0, 0);
4414 break;
4415 case glslang::EOpUMulExtended:
4416 case glslang::EOpIMulExtended:
4417 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4418 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4419 break;
4420 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004421 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004422 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4423 id = builder.createCompositeExtract(id, typeId0, 0);
4424 break;
4425 default:
4426 break;
4427 }
4428
John Kessenich32cfd492016-02-02 12:37:46 -07004429 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004430}
4431
Rex Xu9d93a232016-05-05 12:30:44 +08004432// Intrinsics with no arguments (or no return value, and no precision).
4433spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004434{
4435 // TODO: get the barrier operands correct
4436
4437 switch (op) {
4438 case glslang::EOpEmitVertex:
4439 builder.createNoResultOp(spv::OpEmitVertex);
4440 return 0;
4441 case glslang::EOpEndPrimitive:
4442 builder.createNoResultOp(spv::OpEndPrimitive);
4443 return 0;
4444 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004445 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004446 return 0;
4447 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004448 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004449 return 0;
4450 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004451 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004452 return 0;
4453 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004454 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004455 return 0;
4456 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004457 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004458 return 0;
4459 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004460 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004461 return 0;
4462 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004463 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004464 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004465 case glslang::EOpAllMemoryBarrierWithGroupSync:
4466 // Control barrier with non-"None" semantic is also a memory barrier.
4467 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4468 return 0;
4469 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4470 // Control barrier with non-"None" semantic is also a memory barrier.
4471 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4472 return 0;
4473 case glslang::EOpWorkgroupMemoryBarrier:
4474 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4475 return 0;
4476 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4477 // Control barrier with non-"None" semantic is also a memory barrier.
4478 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4479 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004480#ifdef AMD_EXTENSIONS
4481 case glslang::EOpTime:
4482 {
4483 std::vector<spv::Id> args; // Dummy arguments
4484 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4485 return builder.setPrecision(id, precision);
4486 }
4487#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004488 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004489 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004490 return 0;
4491 }
4492}
4493
4494spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4495{
John Kessenich2f273362015-07-18 22:34:27 -06004496 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004497 spv::Id id;
4498 if (symbolValues.end() != iter) {
4499 id = iter->second;
4500 return id;
4501 }
4502
4503 // it was not found, create it
4504 id = createSpvVariable(symbol);
4505 symbolValues[symbol->getId()] = id;
4506
Rex Xuc884b4a2016-06-29 15:03:44 +08004507 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004508 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004509 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004510 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004511 if (symbol->getType().getQualifier().hasSpecConstantId())
4512 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004513 if (symbol->getQualifier().hasIndex())
4514 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4515 if (symbol->getQualifier().hasComponent())
4516 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4517 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004518 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004519 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004520 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004521 if (symbol->getQualifier().hasXfbBuffer())
4522 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4523 if (symbol->getQualifier().hasXfbOffset())
4524 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4525 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004526 // atomic counters use this:
4527 if (symbol->getQualifier().hasOffset())
4528 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004529 }
4530
scygan2c864272016-05-18 18:09:17 +02004531 if (symbol->getQualifier().hasLocation())
4532 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004533 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004534 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004535 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004536 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004537 }
John Kessenich140f3df2015-06-26 16:58:36 -06004538 if (symbol->getQualifier().hasSet())
4539 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004540 else if (IsDescriptorResource(symbol->getType())) {
4541 // default to 0
4542 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4543 }
John Kessenich140f3df2015-06-26 16:58:36 -06004544 if (symbol->getQualifier().hasBinding())
4545 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004546 if (symbol->getQualifier().hasAttachment())
4547 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004548 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004549 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004550 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004551 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004552 if (symbol->getQualifier().hasXfbBuffer())
4553 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4554 }
4555
Rex Xu1da878f2016-02-21 20:59:01 +08004556 if (symbol->getType().isImage()) {
4557 std::vector<spv::Decoration> memory;
4558 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4559 for (unsigned int i = 0; i < memory.size(); ++i)
4560 addDecoration(id, memory[i]);
4561 }
4562
John Kessenich140f3df2015-06-26 16:58:36 -06004563 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004564 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004565 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004566 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004567
John Kessenich140f3df2015-06-26 16:58:36 -06004568 return id;
4569}
4570
John Kessenich55e7d112015-11-15 21:33:39 -07004571// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004572void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4573{
John Kessenich4016e382016-07-15 11:53:56 -06004574 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004575 builder.addDecoration(id, dec);
4576}
4577
John Kessenich55e7d112015-11-15 21:33:39 -07004578// If 'dec' is valid, add a one-operand decoration to an object
4579void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4580{
John Kessenich4016e382016-07-15 11:53:56 -06004581 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004582 builder.addDecoration(id, dec, value);
4583}
4584
4585// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004586void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4587{
John Kessenich4016e382016-07-15 11:53:56 -06004588 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004589 builder.addMemberDecoration(id, (unsigned)member, dec);
4590}
4591
John Kessenich92187592016-02-01 13:45:25 -07004592// If 'dec' is valid, add a one-operand decoration to a struct member
4593void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4594{
John Kessenich4016e382016-07-15 11:53:56 -06004595 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004596 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4597}
4598
John Kessenich55e7d112015-11-15 21:33:39 -07004599// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004600// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004601//
4602// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4603//
4604// Recursively walk the nodes. The nodes form a tree whose leaves are
4605// regular constants, which themselves are trees that createSpvConstant()
4606// recursively walks. So, this function walks the "top" of the tree:
4607// - emit specialization constant-building instructions for specConstant
4608// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004609spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004610{
John Kessenich7cc0e282016-03-20 00:46:02 -06004611 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004612
qining4f4bb812016-04-03 23:55:17 -04004613 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004614 if (! node.getQualifier().specConstant) {
4615 // hand off to the non-spec-constant path
4616 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4617 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004618 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004619 nextConst, false);
4620 }
4621
4622 // We now know we have a specialization constant to build
4623
John Kessenichd94c0032016-05-30 19:29:40 -06004624 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004625 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4626 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4627 std::vector<spv::Id> dimConstId;
4628 for (int dim = 0; dim < 3; ++dim) {
4629 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4630 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4631 if (specConst)
4632 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4633 }
4634 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4635 }
4636
4637 // An AST node labelled as specialization constant should be a symbol node.
4638 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4639 if (auto* sn = node.getAsSymbolNode()) {
4640 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004641 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4642 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4643 // will set the builder into spec constant op instruction generating mode.
4644 sub_tree->traverse(this);
4645 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004646 } else if (auto* const_union_array = &sn->getConstArray()){
4647 int nextConst = 0;
4648 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004649 }
4650 }
qining4f4bb812016-04-03 23:55:17 -04004651
4652 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4653 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004654 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004655 exit(1);
4656 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004657}
4658
John Kessenich140f3df2015-06-26 16:58:36 -06004659// Use 'consts' as the flattened glslang source of scalar constants to recursively
4660// build the aggregate SPIR-V constant.
4661//
4662// If there are not enough elements present in 'consts', 0 will be substituted;
4663// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4664//
qining08408382016-03-21 09:51:37 -04004665spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004666{
4667 // vector of constants for SPIR-V
4668 std::vector<spv::Id> spvConsts;
4669
4670 // Type is used for struct and array constants
4671 spv::Id typeId = convertGlslangToSpvType(glslangType);
4672
4673 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004674 glslang::TType elementType(glslangType, 0);
4675 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004676 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004677 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004678 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004679 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004680 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004681 } else if (glslangType.getStruct()) {
4682 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4683 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004684 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004685 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004686 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4687 bool zero = nextConst >= consts.size();
4688 switch (glslangType.getBasicType()) {
4689 case glslang::EbtInt:
4690 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4691 break;
4692 case glslang::EbtUint:
4693 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4694 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004695 case glslang::EbtInt64:
4696 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4697 break;
4698 case glslang::EbtUint64:
4699 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4700 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004701 case glslang::EbtFloat:
4702 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4703 break;
4704 case glslang::EbtDouble:
4705 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4706 break;
4707 case glslang::EbtBool:
4708 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4709 break;
4710 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004711 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004712 break;
4713 }
4714 ++nextConst;
4715 }
4716 } else {
4717 // we have a non-aggregate (scalar) constant
4718 bool zero = nextConst >= consts.size();
4719 spv::Id scalar = 0;
4720 switch (glslangType.getBasicType()) {
4721 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004722 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004723 break;
4724 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004725 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004726 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004727 case glslang::EbtInt64:
4728 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4729 break;
4730 case glslang::EbtUint64:
4731 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4732 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004733 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004734 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004735 break;
4736 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004737 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004738 break;
4739 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004740 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004741 break;
4742 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004743 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004744 break;
4745 }
4746 ++nextConst;
4747 return scalar;
4748 }
4749
4750 return builder.makeCompositeConstant(typeId, spvConsts);
4751}
4752
John Kessenich7c1aa102015-10-15 13:29:11 -06004753// Return true if the node is a constant or symbol whose reading has no
4754// non-trivial observable cost or effect.
4755bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4756{
4757 // don't know what this is
4758 if (node == nullptr)
4759 return false;
4760
4761 // a constant is safe
4762 if (node->getAsConstantUnion() != nullptr)
4763 return true;
4764
4765 // not a symbol means non-trivial
4766 if (node->getAsSymbolNode() == nullptr)
4767 return false;
4768
4769 // a symbol, depends on what's being read
4770 switch (node->getType().getQualifier().storage) {
4771 case glslang::EvqTemporary:
4772 case glslang::EvqGlobal:
4773 case glslang::EvqIn:
4774 case glslang::EvqInOut:
4775 case glslang::EvqConst:
4776 case glslang::EvqConstReadOnly:
4777 case glslang::EvqUniform:
4778 return true;
4779 default:
4780 return false;
4781 }
qining25262b32016-05-06 17:25:16 -04004782}
John Kessenich7c1aa102015-10-15 13:29:11 -06004783
4784// A node is trivial if it is a single operation with no side effects.
4785// Error on the side of saying non-trivial.
4786// Return true if trivial.
4787bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4788{
4789 if (node == nullptr)
4790 return false;
4791
4792 // symbols and constants are trivial
4793 if (isTrivialLeaf(node))
4794 return true;
4795
4796 // otherwise, it needs to be a simple operation or one or two leaf nodes
4797
4798 // not a simple operation
4799 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4800 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4801 if (binaryNode == nullptr && unaryNode == nullptr)
4802 return false;
4803
4804 // not on leaf nodes
4805 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4806 return false;
4807
4808 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4809 return false;
4810 }
4811
4812 switch (node->getAsOperator()->getOp()) {
4813 case glslang::EOpLogicalNot:
4814 case glslang::EOpConvIntToBool:
4815 case glslang::EOpConvUintToBool:
4816 case glslang::EOpConvFloatToBool:
4817 case glslang::EOpConvDoubleToBool:
4818 case glslang::EOpEqual:
4819 case glslang::EOpNotEqual:
4820 case glslang::EOpLessThan:
4821 case glslang::EOpGreaterThan:
4822 case glslang::EOpLessThanEqual:
4823 case glslang::EOpGreaterThanEqual:
4824 case glslang::EOpIndexDirect:
4825 case glslang::EOpIndexDirectStruct:
4826 case glslang::EOpLogicalXor:
4827 case glslang::EOpAny:
4828 case glslang::EOpAll:
4829 return true;
4830 default:
4831 return false;
4832 }
4833}
4834
4835// Emit short-circuiting code, where 'right' is never evaluated unless
4836// the left side is true (for &&) or false (for ||).
4837spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4838{
4839 spv::Id boolTypeId = builder.makeBoolType();
4840
4841 // emit left operand
4842 builder.clearAccessChain();
4843 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004844 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004845
4846 // Operands to accumulate OpPhi operands
4847 std::vector<spv::Id> phiOperands;
4848 // accumulate left operand's phi information
4849 phiOperands.push_back(leftId);
4850 phiOperands.push_back(builder.getBuildPoint()->getId());
4851
4852 // Make the two kinds of operation symmetric with a "!"
4853 // || => emit "if (! left) result = right"
4854 // && => emit "if ( left) result = right"
4855 //
4856 // TODO: this runtime "not" for || could be avoided by adding functionality
4857 // to 'builder' to have an "else" without an "then"
4858 if (op == glslang::EOpLogicalOr)
4859 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4860
4861 // make an "if" based on the left value
4862 spv::Builder::If ifBuilder(leftId, builder);
4863
4864 // emit right operand as the "then" part of the "if"
4865 builder.clearAccessChain();
4866 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004867 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004868
4869 // accumulate left operand's phi information
4870 phiOperands.push_back(rightId);
4871 phiOperands.push_back(builder.getBuildPoint()->getId());
4872
4873 // finish the "if"
4874 ifBuilder.makeEndIf();
4875
4876 // phi together the two results
4877 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4878}
4879
Rex Xu9d93a232016-05-05 12:30:44 +08004880// Return type Id of the imported set of extended instructions corresponds to the name.
4881// Import this set if it has not been imported yet.
4882spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4883{
4884 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4885 return extBuiltinMap[name];
4886 else {
Rex Xu51596642016-09-21 18:56:12 +08004887 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08004888 spv::Id extBuiltins = builder.import(name);
4889 extBuiltinMap[name] = extBuiltins;
4890 return extBuiltins;
4891 }
4892}
4893
John Kessenich140f3df2015-06-26 16:58:36 -06004894}; // end anonymous namespace
4895
4896namespace glslang {
4897
John Kessenich68d78fd2015-07-12 19:28:10 -06004898void GetSpirvVersion(std::string& version)
4899{
John Kessenich9e55f632015-07-15 10:03:39 -06004900 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004901 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004902 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004903 version = buf;
4904}
4905
John Kessenich140f3df2015-06-26 16:58:36 -06004906// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004907void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004908{
4909 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004910 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004911 for (int i = 0; i < (int)spirv.size(); ++i) {
4912 unsigned int word = spirv[i];
4913 out.write((const char*)&word, 4);
4914 }
4915 out.close();
4916}
4917
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004918// Write SPIR-V out to a text file with 32-bit hexadecimal words
4919void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4920{
4921 std::ofstream out;
4922 out.open(baseName, std::ios::binary | std::ios::out);
4923 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4924 const int WORDS_PER_LINE = 8;
4925 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4926 out << "\t";
4927 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4928 const unsigned int word = spirv[i + j];
4929 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4930 if (i + j + 1 < (int)spirv.size()) {
4931 out << ",";
4932 }
4933 }
4934 out << std::endl;
4935 }
4936 out.close();
4937}
4938
John Kessenich140f3df2015-06-26 16:58:36 -06004939//
4940// Set up the glslang traversal
4941//
4942void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4943{
Lei Zhang17535f72016-05-04 15:55:59 -04004944 spv::SpvBuildLogger logger;
4945 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004946}
4947
Lei Zhang17535f72016-05-04 15:55:59 -04004948void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004949{
John Kessenich140f3df2015-06-26 16:58:36 -06004950 TIntermNode* root = intermediate.getTreeRoot();
4951
4952 if (root == 0)
4953 return;
4954
4955 glslang::GetThreadPoolAllocator().push();
4956
Lei Zhang17535f72016-05-04 15:55:59 -04004957 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004958
4959 root->traverse(&it);
4960
4961 it.dumpSpv(spirv);
4962
4963 glslang::GetThreadPoolAllocator().pop();
4964}
4965
4966}; // end namespace glslang