blob: 725aac17215b88a971aff68c2094e56cc920eab2 [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 {
45 #include "GLSL.std.450.h"
46}
John Kessenich140f3df2015-06-26 16:58:36 -060047
48// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020049#include "../glslang/MachineIndependent/localintermediate.h"
50#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060052
John Kessenich140f3df2015-06-26 16:58:36 -060053#include <fstream>
Lei Zhang17535f72016-05-04 15:55:59 -040054#include <list>
55#include <map>
56#include <stack>
57#include <string>
58#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060059
60namespace {
61
John Kessenich55e7d112015-11-15 21:33:39 -070062// For low-order part of the generator's magic number. Bump up
63// when there is a change in the style (e.g., if SSA form changes,
64// or a different instruction sequence to do something gets used).
65const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060066
qining4c912612016-04-01 10:35:16 -040067namespace {
68class SpecConstantOpModeGuard {
69public:
70 SpecConstantOpModeGuard(spv::Builder* builder)
71 : builder_(builder) {
72 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040073 }
74 ~SpecConstantOpModeGuard() {
75 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
76 : builder_->setToNormalCodeGenMode();
77 }
qining40887662016-04-03 22:20:42 -040078 void turnOnSpecConstantOpMode() {
79 builder_->setToSpecConstCodeGenMode();
80 }
qining4c912612016-04-01 10:35:16 -040081
82private:
83 spv::Builder* builder_;
84 bool previous_flag_;
85};
86}
87
John Kessenich140f3df2015-06-26 16:58:36 -060088//
89// The main holder of information for translating glslang to SPIR-V.
90//
91// Derives from the AST walking base class.
92//
93class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
94public:
Lei Zhang17535f72016-05-04 15:55:59 -040095 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060096 virtual ~TGlslangToSpvTraverser();
97
98 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
99 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
100 void visitConstantUnion(glslang::TIntermConstantUnion*);
101 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
102 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
103 void visitSymbol(glslang::TIntermSymbol* symbol);
104 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
105 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
106 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
107
John Kessenich7ba63412015-12-20 17:37:07 -0700108 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110protected:
Rex Xubbceed72016-05-21 09:40:44 +0800111 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700113 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
115 spv::Id getSampledType(const glslang::TSampler&);
116 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700117 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600118 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
119 glslang::TLayoutPacking, const glslang::TQualifier&);
120 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
121 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700122 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700123 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800124 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700125 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700126 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
127 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
128 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 +0100129 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600130
131 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
132 void makeFunctions(const glslang::TIntermSequence&);
133 void makeGlobalInitializers(const glslang::TIntermSequence&);
134 void visitFunctions(const glslang::TIntermSequence&);
135 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800136 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600137 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
138 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600139 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
140
qining25262b32016-05-06 17:25:16 -0400141 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);
142 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
143 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
144 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800145 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 -0600146 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800147 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich91cef522016-05-05 16:45:40 -0600148 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600149 spv::Id 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 -0600150 spv::Id createNoArgOperation(glslang::TOperator op);
151 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
152 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700153 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700155 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400156 spv::Id createSpvConstant(const glslang::TIntermTyped&);
157 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600158 bool isTrivialLeaf(const glslang::TIntermTyped* node);
159 bool isTrivial(const glslang::TIntermTyped* node);
160 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600161
162 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700163 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600164 int sequenceDepth;
165
Lei Zhang17535f72016-05-04 15:55:59 -0400166 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400167
John Kessenich140f3df2015-06-26 16:58:36 -0600168 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
169 spv::Builder builder;
170 bool inMain;
171 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700172 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 -0700173 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600174 const glslang::TIntermediate* glslangIntermediate;
175 spv::Id stdBuiltins;
176
John Kessenich2f273362015-07-18 22:34:27 -0600177 std::unordered_map<int, spv::Id> symbolValues;
178 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
179 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700180 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600181 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 -0600182 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600183};
184
185//
186// Helper functions for translating glslang representations to SPIR-V enumerants.
187//
188
189// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700190spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600191{
John Kessenich66e2faf2016-03-12 18:34:36 -0700192 switch (source) {
193 case glslang::EShSourceGlsl:
194 switch (profile) {
195 case ENoProfile:
196 case ECoreProfile:
197 case ECompatibilityProfile:
198 return spv::SourceLanguageGLSL;
199 case EEsProfile:
200 return spv::SourceLanguageESSL;
201 default:
202 return spv::SourceLanguageUnknown;
203 }
204 case glslang::EShSourceHlsl:
205 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600206 default:
207 return spv::SourceLanguageUnknown;
208 }
209}
210
211// Translate glslang language (stage) to SPIR-V execution model.
212spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
213{
214 switch (stage) {
215 case EShLangVertex: return spv::ExecutionModelVertex;
216 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
217 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
218 case EShLangGeometry: return spv::ExecutionModelGeometry;
219 case EShLangFragment: return spv::ExecutionModelFragment;
220 case EShLangCompute: return spv::ExecutionModelGLCompute;
221 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600223 return spv::ExecutionModelFragment;
224 }
225}
226
227// Translate glslang type to SPIR-V storage class.
228spv::StorageClass TranslateStorageClass(const glslang::TType& type)
229{
230 if (type.getQualifier().isPipeInput())
231 return spv::StorageClassInput;
232 else if (type.getQualifier().isPipeOutput())
233 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700234 else if (type.getBasicType() == glslang::EbtSampler)
235 return spv::StorageClassUniformConstant;
236 else if (type.getBasicType() == glslang::EbtAtomicUint)
237 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700239 if (type.getQualifier().layoutPushConstant)
240 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 if (type.getBasicType() == glslang::EbtBlock)
242 return spv::StorageClassUniform;
243 else
244 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600245 // 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 -0600246 } else {
247 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700248 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
249 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600250 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
251 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400252 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700253 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600254 return spv::StorageClassFunction;
255 }
256 }
257}
258
259// Translate glslang sampler type to SPIR-V dimensionality.
260spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
261{
262 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::Esd1D: return spv::Dim1D;
264 case glslang::Esd2D: return spv::Dim2D;
265 case glslang::Esd3D: return spv::Dim3D;
266 case glslang::EsdCube: return spv::DimCube;
267 case glslang::EsdRect: return spv::DimRect;
268 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700269 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700271 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600272 return spv::Dim2D;
273 }
274}
275
276// Translate glslang type to SPIR-V precision decorations.
277spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
278{
279 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700280 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600281 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 default:
283 return spv::NoPrecision;
284 }
285}
286
287// Translate glslang type to SPIR-V block decorations.
288spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
289{
290 if (type.getBasicType() == glslang::EbtBlock) {
291 switch (type.getQualifier().storage) {
292 case glslang::EvqUniform: return spv::DecorationBlock;
293 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
294 case glslang::EvqVaryingIn: return spv::DecorationBlock;
295 case glslang::EvqVaryingOut: return spv::DecorationBlock;
296 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600298 break;
299 }
300 }
301
302 return (spv::Decoration)spv::BadValue;
303}
304
Rex Xu1da878f2016-02-21 20:59:01 +0800305// Translate glslang type to SPIR-V memory decorations.
306void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
307{
308 if (qualifier.coherent)
309 memory.push_back(spv::DecorationCoherent);
310 if (qualifier.volatil)
311 memory.push_back(spv::DecorationVolatile);
312 if (qualifier.restrict)
313 memory.push_back(spv::DecorationRestrict);
314 if (qualifier.readonly)
315 memory.push_back(spv::DecorationNonWritable);
316 if (qualifier.writeonly)
317 memory.push_back(spv::DecorationNonReadable);
318}
319
John Kessenich140f3df2015-06-26 16:58:36 -0600320// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700321spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600322{
323 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700324 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600325 case glslang::ElmRowMajor:
326 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700329 default:
330 // opaque layouts don't need a majorness
331 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600332 }
333 } else {
334 switch (type.getBasicType()) {
335 default:
336 return (spv::Decoration)spv::BadValue;
337 break;
338 case glslang::EbtBlock:
339 switch (type.getQualifier().storage) {
340 case glslang::EvqUniform:
341 case glslang::EvqBuffer:
342 switch (type.getQualifier().layoutPacking) {
343 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
345 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600346 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 }
348 case glslang::EvqVaryingIn:
349 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700350 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600351 return (spv::Decoration)spv::BadValue;
352 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700353 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return (spv::Decoration)spv::BadValue;
355 }
356 }
357 }
358}
359
360// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700361// Returns spv::Decoration(spv::BadValue) when no decoration
362// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800363spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600364{
Rex Xubbceed72016-05-21 09:40:44 +0800365 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700366 // Smooth decoration doesn't exist in SPIR-V 1.0
367 return (spv::Decoration)spv::BadValue;
Rex Xubbceed72016-05-21 09:40:44 +0800368 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700369 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700370 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600371 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800372 else
373 return (spv::Decoration)spv::BadValue;
374}
375
376// Translate glslang type to SPIR-V auxiliary storage decorations.
377// Returns spv::Decoration(spv::BadValue) when no decoration
378// should be applied.
379spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
380{
381 if (qualifier.patch)
382 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700383 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600384 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700385 else if (qualifier.sample) {
386 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700388 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return (spv::Decoration)spv::BadValue;
390}
391
John Kessenich92187592016-02-01 13:45:25 -0700392// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700393spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600394{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationInvariant;
397 else
398 return (spv::Decoration)spv::BadValue;
399}
400
qining9220dbb2016-05-04 17:34:38 -0400401// If glslang type is noContraction, return SPIR-V NoContraction decoration.
402spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
403{
404 if (qualifier.noContraction)
405 return spv::DecorationNoContraction;
406 else
407 return (spv::Decoration)spv::BadValue;
408}
409
David Netoa901ffe2016-06-08 14:11:40 +0100410// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
411// associated capabilities when required. For some built-in variables, a capability
412// is generated only when using the variable in an executable instruction, but not when
413// just declaring a struct member variable with it. This is true for PointSize,
414// ClipDistance, and CullDistance.
415spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600416{
417 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700418 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600419 // Defer adding the capability until the built-in is actually used.
420 if (! memberDeclaration) {
421 switch (glslangIntermediate->getStage()) {
422 case EShLangGeometry:
423 builder.addCapability(spv::CapabilityGeometryPointSize);
424 break;
425 case EShLangTessControl:
426 case EShLangTessEvaluation:
427 builder.addCapability(spv::CapabilityTessellationPointSize);
428 break;
429 default:
430 break;
431 }
John Kessenich92187592016-02-01 13:45:25 -0700432 }
433 return spv::BuiltInPointSize;
434
John Kessenichebb50532016-05-16 19:22:05 -0600435 // These *Distance capabilities logically belong here, but if the member is declared and
436 // then never used, consumers of SPIR-V prefer the capability not be declared.
437 // They are now generated when used, rather than here when declared.
438 // Potentially, the specification should be more clear what the minimum
439 // use needed is to trigger the capability.
440 //
John Kessenich92187592016-02-01 13:45:25 -0700441 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100442 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600443 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700444 return spv::BuiltInClipDistance;
445
446 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100447 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600448 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700449 return spv::BuiltInCullDistance;
450
451 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500452 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInViewportIndex;
454
John Kessenich5e801132016-02-15 11:09:46 -0700455 case glslang::EbvSampleId:
456 builder.addCapability(spv::CapabilitySampleRateShading);
457 return spv::BuiltInSampleId;
458
459 case glslang::EbvSamplePosition:
460 builder.addCapability(spv::CapabilitySampleRateShading);
461 return spv::BuiltInSamplePosition;
462
463 case glslang::EbvSampleMask:
464 builder.addCapability(spv::CapabilitySampleRateShading);
465 return spv::BuiltInSampleMask;
466
John Kessenich78a45572016-07-08 14:05:15 -0600467 case glslang::EbvLayer:
468 builder.addCapability(spv::CapabilityGeometry);
469 return spv::BuiltInLayer;
470
John Kessenich140f3df2015-06-26 16:58:36 -0600471 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600472 case glslang::EbvVertexId: return spv::BuiltInVertexId;
473 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700474 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
475 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600476 case glslang::EbvBaseVertex:
477 case glslang::EbvBaseInstance:
478 case glslang::EbvDrawId:
479 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600480 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600481 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600482 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
483 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600484 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
485 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
486 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
487 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
488 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
489 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
490 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600491 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
492 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
493 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
494 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
495 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
496 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
497 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
498 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800499 case glslang::EbvSubGroupSize:
500 case glslang::EbvSubGroupInvocation:
501 case glslang::EbvSubGroupEqMask:
502 case glslang::EbvSubGroupGeMask:
503 case glslang::EbvSubGroupGtMask:
504 case glslang::EbvSubGroupLeMask:
505 case glslang::EbvSubGroupLtMask:
506 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600507 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800508 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600509 default: return (spv::BuiltIn)spv::BadValue;
510 }
511}
512
Rex Xufc618912015-09-09 16:42:49 +0800513// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700514spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800515{
516 assert(type.getBasicType() == glslang::EbtSampler);
517
John Kessenich5d0fa972016-02-15 11:57:00 -0700518 // Check for capabilities
519 switch (type.getQualifier().layoutFormat) {
520 case glslang::ElfRg32f:
521 case glslang::ElfRg16f:
522 case glslang::ElfR11fG11fB10f:
523 case glslang::ElfR16f:
524 case glslang::ElfRgba16:
525 case glslang::ElfRgb10A2:
526 case glslang::ElfRg16:
527 case glslang::ElfRg8:
528 case glslang::ElfR16:
529 case glslang::ElfR8:
530 case glslang::ElfRgba16Snorm:
531 case glslang::ElfRg16Snorm:
532 case glslang::ElfRg8Snorm:
533 case glslang::ElfR16Snorm:
534 case glslang::ElfR8Snorm:
535
536 case glslang::ElfRg32i:
537 case glslang::ElfRg16i:
538 case glslang::ElfRg8i:
539 case glslang::ElfR16i:
540 case glslang::ElfR8i:
541
542 case glslang::ElfRgb10a2ui:
543 case glslang::ElfRg32ui:
544 case glslang::ElfRg16ui:
545 case glslang::ElfRg8ui:
546 case glslang::ElfR16ui:
547 case glslang::ElfR8ui:
548 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
549 break;
550
551 default:
552 break;
553 }
554
555 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800556 switch (type.getQualifier().layoutFormat) {
557 case glslang::ElfNone: return spv::ImageFormatUnknown;
558 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
559 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
560 case glslang::ElfR32f: return spv::ImageFormatR32f;
561 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
562 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
563 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
564 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
565 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
566 case glslang::ElfR16f: return spv::ImageFormatR16f;
567 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
568 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
569 case glslang::ElfRg16: return spv::ImageFormatRg16;
570 case glslang::ElfRg8: return spv::ImageFormatRg8;
571 case glslang::ElfR16: return spv::ImageFormatR16;
572 case glslang::ElfR8: return spv::ImageFormatR8;
573 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
574 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
575 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
576 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
577 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
578 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
579 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
580 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
581 case glslang::ElfR32i: return spv::ImageFormatR32i;
582 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
583 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
584 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
585 case glslang::ElfR16i: return spv::ImageFormatR16i;
586 case glslang::ElfR8i: return spv::ImageFormatR8i;
587 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
588 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
589 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
590 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
591 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
592 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
593 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
594 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
595 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
596 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
597 default: return (spv::ImageFormat)spv::BadValue;
598 }
599}
600
qining25262b32016-05-06 17:25:16 -0400601// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700602// descriptor set.
603bool IsDescriptorResource(const glslang::TType& type)
604{
John Kessenichf7497e22016-03-08 21:36:22 -0700605 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700606 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700607 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700608
609 // non block...
610 // basically samplerXXX/subpass/sampler/texture are all included
611 // if they are the global-scope-class, not the function parameter
612 // (or local, if they ever exist) class.
613 if (type.getBasicType() == glslang::EbtSampler)
614 return type.getQualifier().isUniformOrBuffer();
615
616 // None of the above.
617 return false;
618}
619
John Kesseniche0b6cad2015-12-24 10:30:13 -0700620void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
621{
622 if (child.layoutMatrix == glslang::ElmNone)
623 child.layoutMatrix = parent.layoutMatrix;
624
625 if (parent.invariant)
626 child.invariant = true;
627 if (parent.nopersp)
628 child.nopersp = true;
629 if (parent.flat)
630 child.flat = true;
631 if (parent.centroid)
632 child.centroid = true;
633 if (parent.patch)
634 child.patch = true;
635 if (parent.sample)
636 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800637 if (parent.coherent)
638 child.coherent = true;
639 if (parent.volatil)
640 child.volatil = true;
641 if (parent.restrict)
642 child.restrict = true;
643 if (parent.readonly)
644 child.readonly = true;
645 if (parent.writeonly)
646 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700647}
648
649bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
650{
John Kessenich7b9fa252016-01-21 18:56:57 -0700651 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700652 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600653 // - affect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700654 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600655 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700656}
657
John Kessenich140f3df2015-06-26 16:58:36 -0600658//
659// Implement the TGlslangToSpvTraverser class.
660//
661
Lei Zhang17535f72016-05-04 15:55:59 -0400662TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
663 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
664 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600665 inMain(false), mainTerminated(false), linkageOnly(false),
666 glslangIntermediate(glslangIntermediate)
667{
668 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
669
670 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700671 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600672 stdBuiltins = builder.import("GLSL.std.450");
673 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700674 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
675 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600676
677 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600678 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
679 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600680 builder.addSourceExtension(it->c_str());
681
682 // Add the top-level modes for this shader.
683
John Kessenich92187592016-02-01 13:45:25 -0700684 if (glslangIntermediate->getXfbMode()) {
685 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600686 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700687 }
John Kessenich140f3df2015-06-26 16:58:36 -0600688
689 unsigned int mode;
690 switch (glslangIntermediate->getStage()) {
691 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600692 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600693 break;
694
695 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600696 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600697 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
698 break;
699
700 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600701 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600702 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700703 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
704 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
705 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600706 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600707 }
708 if (mode != spv::BadValue)
709 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
710
John Kesseniche6903322015-10-13 16:29:02 -0600711 switch (glslangIntermediate->getVertexSpacing()) {
712 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
713 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
714 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
715 default: mode = spv::BadValue; break;
716 }
717 if (mode != spv::BadValue)
718 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
719
720 switch (glslangIntermediate->getVertexOrder()) {
721 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
722 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
723 default: mode = spv::BadValue; break;
724 }
725 if (mode != spv::BadValue)
726 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
727
728 if (glslangIntermediate->getPointMode())
729 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600730 break;
731
732 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600733 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600734 switch (glslangIntermediate->getInputPrimitive()) {
735 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
736 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
737 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700738 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600739 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
740 default: mode = spv::BadValue; break;
741 }
742 if (mode != spv::BadValue)
743 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600744
John Kessenich140f3df2015-06-26 16:58:36 -0600745 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
746
747 switch (glslangIntermediate->getOutputPrimitive()) {
748 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
749 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
750 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
751 default: mode = spv::BadValue; break;
752 }
753 if (mode != spv::BadValue)
754 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
755 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
756 break;
757
758 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600759 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600760 if (glslangIntermediate->getPixelCenterInteger())
761 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600762
John Kessenich140f3df2015-06-26 16:58:36 -0600763 if (glslangIntermediate->getOriginUpperLeft())
764 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600765 else
766 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600767
768 if (glslangIntermediate->getEarlyFragmentTests())
769 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
770
771 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600772 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
773 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
774 default: mode = spv::BadValue; break;
775 }
776 if (mode != spv::BadValue)
777 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
778
779 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
780 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600781 break;
782
783 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600784 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600785 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
786 glslangIntermediate->getLocalSize(1),
787 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600788 break;
789
790 default:
791 break;
792 }
793
794}
795
John Kessenich7ba63412015-12-20 17:37:07 -0700796// Finish everything and dump
797void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
798{
799 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100800 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
801 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700802
qiningda397332016-03-09 19:54:03 -0500803 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700804 builder.dump(out);
805}
806
John Kessenich140f3df2015-06-26 16:58:36 -0600807TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
808{
809 if (! mainTerminated) {
810 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
811 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600812 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600813 }
814}
815
816//
817// Implement the traversal functions.
818//
819// Return true from interior nodes to have the external traversal
820// continue on to children. Return false if children were
821// already processed.
822//
823
824//
qining25262b32016-05-06 17:25:16 -0400825// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600826// - uniform/input reads
827// - output writes
828// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
829// - something simple that degenerates into the last bullet
830//
831void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
832{
qining75d1d802016-04-06 14:42:01 -0400833 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
834 if (symbol->getType().getQualifier().isSpecConstant())
835 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
836
John Kessenich140f3df2015-06-26 16:58:36 -0600837 // getSymbolId() will set up all the IO decorations on the first call.
838 // Formal function parameters were mapped during makeFunctions().
839 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700840
841 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
842 if (builder.isPointer(id)) {
843 spv::StorageClass sc = builder.getStorageClass(id);
844 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
845 iOSet.insert(id);
846 }
847
848 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700849 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600850 // Prepare to generate code for the access
851
852 // L-value chains will be computed left to right. We're on the symbol now,
853 // which is the left-most part of the access chain, so now is "clear" time,
854 // followed by setting the base.
855 builder.clearAccessChain();
856
857 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700858 // except for
859 // A) "const in" arguments to a function, which are an intermediate object.
860 // See comments in handleUserFunctionCall().
861 // B) Specialization constants (normal constant don't even come in as a variable),
862 // These are also pure R-values.
863 glslang::TQualifier qualifier = symbol->getQualifier();
864 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
865 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600866 builder.setAccessChainRValue(id);
867 else
868 builder.setAccessChainLValue(id);
869 }
870}
871
872bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
873{
qining40887662016-04-03 22:20:42 -0400874 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
875 if (node->getType().getQualifier().isSpecConstant())
876 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
877
John Kessenich140f3df2015-06-26 16:58:36 -0600878 // First, handle special cases
879 switch (node->getOp()) {
880 case glslang::EOpAssign:
881 case glslang::EOpAddAssign:
882 case glslang::EOpSubAssign:
883 case glslang::EOpMulAssign:
884 case glslang::EOpVectorTimesMatrixAssign:
885 case glslang::EOpVectorTimesScalarAssign:
886 case glslang::EOpMatrixTimesScalarAssign:
887 case glslang::EOpMatrixTimesMatrixAssign:
888 case glslang::EOpDivAssign:
889 case glslang::EOpModAssign:
890 case glslang::EOpAndAssign:
891 case glslang::EOpInclusiveOrAssign:
892 case glslang::EOpExclusiveOrAssign:
893 case glslang::EOpLeftShiftAssign:
894 case glslang::EOpRightShiftAssign:
895 // A bin-op assign "a += b" means the same thing as "a = a + b"
896 // where a is evaluated before b. For a simple assignment, GLSL
897 // says to evaluate the left before the right. So, always, left
898 // node then right node.
899 {
900 // get the left l-value, save it away
901 builder.clearAccessChain();
902 node->getLeft()->traverse(this);
903 spv::Builder::AccessChain lValue = builder.getAccessChain();
904
905 // evaluate the right
906 builder.clearAccessChain();
907 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700908 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600909
910 if (node->getOp() != glslang::EOpAssign) {
911 // the left is also an r-value
912 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700913 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600914
915 // do the operation
qining25262b32016-05-06 17:25:16 -0400916 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
917 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600918 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
919 node->getType().getBasicType());
920
921 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700922 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600923 }
924
925 // store the result
926 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800927 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600928
929 // assignments are expressions having an rValue after they are evaluated...
930 builder.clearAccessChain();
931 builder.setAccessChainRValue(rValue);
932 }
933 return false;
934 case glslang::EOpIndexDirect:
935 case glslang::EOpIndexDirectStruct:
936 {
937 // Get the left part of the access chain.
938 node->getLeft()->traverse(this);
939
940 // Add the next element in the chain
941
David Netoa901ffe2016-06-08 14:11:40 +0100942 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600943 if (! node->getLeft()->getType().isArray() &&
944 node->getLeft()->getType().isVector() &&
945 node->getOp() == glslang::EOpIndexDirect) {
946 // This is essentially a hard-coded vector swizzle of size 1,
947 // so short circuit the access-chain stuff with a swizzle.
948 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100949 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600950 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600951 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100952 int spvIndex = glslangIndex;
953 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
954 node->getOp() == glslang::EOpIndexDirectStruct)
955 {
956 // This may be, e.g., an anonymous block-member selection, which generally need
957 // index remapping due to hidden members in anonymous blocks.
958 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
959 assert(remapper.size() > 0);
960 spvIndex = remapper[glslangIndex];
961 }
John Kessenichebb50532016-05-16 19:22:05 -0600962
David Netoa901ffe2016-06-08 14:11:40 +0100963 // normal case for indexing array or structure or block
964 builder.accessChainPush(builder.makeIntConstant(spvIndex));
965
966 // Add capabilities here for accessing PointSize and clip/cull distance.
967 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600968 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100969 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600970 }
971 }
972 return false;
973 case glslang::EOpIndexIndirect:
974 {
975 // Structure or array or vector indirection.
976 // Will use native SPIR-V access-chain for struct and array indirection;
977 // matrices are arrays of vectors, so will also work for a matrix.
978 // Will use the access chain's 'component' for variable index into a vector.
979
980 // This adapter is building access chains left to right.
981 // Set up the access chain to the left.
982 node->getLeft()->traverse(this);
983
984 // save it so that computing the right side doesn't trash it
985 spv::Builder::AccessChain partial = builder.getAccessChain();
986
987 // compute the next index in the chain
988 builder.clearAccessChain();
989 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700990 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600991
992 // restore the saved access chain
993 builder.setAccessChain(partial);
994
995 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600996 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600997 else
John Kessenichfa668da2015-09-13 14:46:30 -0600998 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600999 }
1000 return false;
1001 case glslang::EOpVectorSwizzle:
1002 {
1003 node->getLeft()->traverse(this);
1004 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
1005 std::vector<unsigned> swizzle;
1006 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1007 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -06001008 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001009 }
1010 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001011 case glslang::EOpLogicalOr:
1012 case glslang::EOpLogicalAnd:
1013 {
1014
1015 // These may require short circuiting, but can sometimes be done as straight
1016 // binary operations. The right operand must be short circuited if it has
1017 // side effects, and should probably be if it is complex.
1018 if (isTrivial(node->getRight()->getAsTyped()))
1019 break; // handle below as a normal binary operation
1020 // otherwise, we need to do dynamic short circuiting on the right operand
1021 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1022 builder.clearAccessChain();
1023 builder.setAccessChainRValue(result);
1024 }
1025 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001026 default:
1027 break;
1028 }
1029
1030 // Assume generic binary op...
1031
John Kessenich32cfd492016-02-02 12:37:46 -07001032 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001033 builder.clearAccessChain();
1034 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001035 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001036
John Kessenich32cfd492016-02-02 12:37:46 -07001037 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001038 builder.clearAccessChain();
1039 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001040 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001041
John Kessenich32cfd492016-02-02 12:37:46 -07001042 // get result
1043 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001044 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001045 convertGlslangToSpvType(node->getType()), left, right,
1046 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001047
John Kessenich50e57562015-12-21 21:21:11 -07001048 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001049 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001050 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001051 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001052 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001053 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001054 return false;
1055 }
John Kessenich140f3df2015-06-26 16:58:36 -06001056}
1057
1058bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1059{
qining40887662016-04-03 22:20:42 -04001060 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1061 if (node->getType().getQualifier().isSpecConstant())
1062 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1063
John Kessenichfc51d282015-08-19 13:34:18 -06001064 spv::Id result = spv::NoResult;
1065
1066 // try texturing first
1067 result = createImageTextureFunctionCall(node);
1068 if (result != spv::NoResult) {
1069 builder.clearAccessChain();
1070 builder.setAccessChainRValue(result);
1071
1072 return false; // done with this node
1073 }
1074
1075 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001076
1077 if (node->getOp() == glslang::EOpArrayLength) {
1078 // Quite special; won't want to evaluate the operand.
1079
1080 // Normal .length() would have been constant folded by the front-end.
1081 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001082 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001083 assert(node->getOperand()->getType().isRuntimeSizedArray());
1084 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1085 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001086 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1087 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001088
1089 builder.clearAccessChain();
1090 builder.setAccessChainRValue(length);
1091
1092 return false;
1093 }
1094
John Kessenichfc51d282015-08-19 13:34:18 -06001095 // Start by evaluating the operand
1096
John Kessenich140f3df2015-06-26 16:58:36 -06001097 builder.clearAccessChain();
1098 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001099
Rex Xufc618912015-09-09 16:42:49 +08001100 spv::Id operand = spv::NoResult;
1101
1102 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1103 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001104 node->getOp() == glslang::EOpAtomicCounter ||
1105 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001106 operand = builder.accessChainGetLValue(); // Special case l-value operands
1107 else
John Kessenich32cfd492016-02-02 12:37:46 -07001108 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001109
1110 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001111 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001112
1113 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001114 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001115 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001116
1117 // if not, then possibly an operation
1118 if (! result)
qining25262b32016-05-06 17:25:16 -04001119 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001120
1121 if (result) {
1122 builder.clearAccessChain();
1123 builder.setAccessChainRValue(result);
1124
1125 return false; // done with this node
1126 }
1127
1128 // it must be a special case, check...
1129 switch (node->getOp()) {
1130 case glslang::EOpPostIncrement:
1131 case glslang::EOpPostDecrement:
1132 case glslang::EOpPreIncrement:
1133 case glslang::EOpPreDecrement:
1134 {
1135 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001136 spv::Id one = 0;
1137 if (node->getBasicType() == glslang::EbtFloat)
1138 one = builder.makeFloatConstant(1.0F);
1139 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1140 one = builder.makeInt64Constant(1);
1141 else
1142 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001143 glslang::TOperator op;
1144 if (node->getOp() == glslang::EOpPreIncrement ||
1145 node->getOp() == glslang::EOpPostIncrement)
1146 op = glslang::EOpAdd;
1147 else
1148 op = glslang::EOpSub;
1149
qining25262b32016-05-06 17:25:16 -04001150 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1151 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001152 convertGlslangToSpvType(node->getType()), operand, one,
1153 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001154 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001155
1156 // The result of operation is always stored, but conditionally the
1157 // consumed result. The consumed result is always an r-value.
1158 builder.accessChainStore(result);
1159 builder.clearAccessChain();
1160 if (node->getOp() == glslang::EOpPreIncrement ||
1161 node->getOp() == glslang::EOpPreDecrement)
1162 builder.setAccessChainRValue(result);
1163 else
1164 builder.setAccessChainRValue(operand);
1165 }
1166
1167 return false;
1168
1169 case glslang::EOpEmitStreamVertex:
1170 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1171 return false;
1172 case glslang::EOpEndStreamPrimitive:
1173 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1174 return false;
1175
1176 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001177 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001178 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001179 }
John Kessenich140f3df2015-06-26 16:58:36 -06001180}
1181
1182bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1183{
qining27e04a02016-04-14 16:40:20 -04001184 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1185 if (node->getType().getQualifier().isSpecConstant())
1186 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1187
John Kessenichfc51d282015-08-19 13:34:18 -06001188 spv::Id result = spv::NoResult;
1189
1190 // try texturing
1191 result = createImageTextureFunctionCall(node);
1192 if (result != spv::NoResult) {
1193 builder.clearAccessChain();
1194 builder.setAccessChainRValue(result);
1195
1196 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001197 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001198 // "imageStore" is a special case, which has no result
1199 return false;
1200 }
John Kessenichfc51d282015-08-19 13:34:18 -06001201
John Kessenich140f3df2015-06-26 16:58:36 -06001202 glslang::TOperator binOp = glslang::EOpNull;
1203 bool reduceComparison = true;
1204 bool isMatrix = false;
1205 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001206 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001207
1208 assert(node->getOp());
1209
1210 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1211
1212 switch (node->getOp()) {
1213 case glslang::EOpSequence:
1214 {
1215 if (preVisit)
1216 ++sequenceDepth;
1217 else
1218 --sequenceDepth;
1219
1220 if (sequenceDepth == 1) {
1221 // If this is the parent node of all the functions, we want to see them
1222 // early, so all call points have actual SPIR-V functions to reference.
1223 // In all cases, still let the traverser visit the children for us.
1224 makeFunctions(node->getAsAggregate()->getSequence());
1225
1226 // Also, we want all globals initializers to go into the entry of main(), before
1227 // anything else gets there, so visit out of order, doing them all now.
1228 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1229
1230 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1231 // so do them manually.
1232 visitFunctions(node->getAsAggregate()->getSequence());
1233
1234 return false;
1235 }
1236
1237 return true;
1238 }
1239 case glslang::EOpLinkerObjects:
1240 {
1241 if (visit == glslang::EvPreVisit)
1242 linkageOnly = true;
1243 else
1244 linkageOnly = false;
1245
1246 return true;
1247 }
1248 case glslang::EOpComma:
1249 {
1250 // processing from left to right naturally leaves the right-most
1251 // lying around in the access chain
1252 glslang::TIntermSequence& glslangOperands = node->getSequence();
1253 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1254 glslangOperands[i]->traverse(this);
1255
1256 return false;
1257 }
1258 case glslang::EOpFunction:
1259 if (visit == glslang::EvPreVisit) {
1260 if (isShaderEntrypoint(node)) {
1261 inMain = true;
1262 builder.setBuildPoint(shaderEntry->getLastBlock());
1263 } else {
1264 handleFunctionEntry(node);
1265 }
1266 } else {
1267 if (inMain)
1268 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001269 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001270 inMain = false;
1271 }
1272
1273 return true;
1274 case glslang::EOpParameters:
1275 // Parameters will have been consumed by EOpFunction processing, but not
1276 // the body, so we still visited the function node's children, making this
1277 // child redundant.
1278 return false;
1279 case glslang::EOpFunctionCall:
1280 {
1281 if (node->isUserDefined())
1282 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001283 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1284 if (result) {
1285 builder.clearAccessChain();
1286 builder.setAccessChainRValue(result);
1287 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001288 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001289
1290 return false;
1291 }
1292 case glslang::EOpConstructMat2x2:
1293 case glslang::EOpConstructMat2x3:
1294 case glslang::EOpConstructMat2x4:
1295 case glslang::EOpConstructMat3x2:
1296 case glslang::EOpConstructMat3x3:
1297 case glslang::EOpConstructMat3x4:
1298 case glslang::EOpConstructMat4x2:
1299 case glslang::EOpConstructMat4x3:
1300 case glslang::EOpConstructMat4x4:
1301 case glslang::EOpConstructDMat2x2:
1302 case glslang::EOpConstructDMat2x3:
1303 case glslang::EOpConstructDMat2x4:
1304 case glslang::EOpConstructDMat3x2:
1305 case glslang::EOpConstructDMat3x3:
1306 case glslang::EOpConstructDMat3x4:
1307 case glslang::EOpConstructDMat4x2:
1308 case glslang::EOpConstructDMat4x3:
1309 case glslang::EOpConstructDMat4x4:
1310 isMatrix = true;
1311 // fall through
1312 case glslang::EOpConstructFloat:
1313 case glslang::EOpConstructVec2:
1314 case glslang::EOpConstructVec3:
1315 case glslang::EOpConstructVec4:
1316 case glslang::EOpConstructDouble:
1317 case glslang::EOpConstructDVec2:
1318 case glslang::EOpConstructDVec3:
1319 case glslang::EOpConstructDVec4:
1320 case glslang::EOpConstructBool:
1321 case glslang::EOpConstructBVec2:
1322 case glslang::EOpConstructBVec3:
1323 case glslang::EOpConstructBVec4:
1324 case glslang::EOpConstructInt:
1325 case glslang::EOpConstructIVec2:
1326 case glslang::EOpConstructIVec3:
1327 case glslang::EOpConstructIVec4:
1328 case glslang::EOpConstructUint:
1329 case glslang::EOpConstructUVec2:
1330 case glslang::EOpConstructUVec3:
1331 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001332 case glslang::EOpConstructInt64:
1333 case glslang::EOpConstructI64Vec2:
1334 case glslang::EOpConstructI64Vec3:
1335 case glslang::EOpConstructI64Vec4:
1336 case glslang::EOpConstructUint64:
1337 case glslang::EOpConstructU64Vec2:
1338 case glslang::EOpConstructU64Vec3:
1339 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001340 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001341 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001342 {
1343 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001344 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001345 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1346 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001347 if (node->getOp() == glslang::EOpConstructTextureSampler)
1348 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1349 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001350 std::vector<spv::Id> constituents;
1351 for (int c = 0; c < (int)arguments.size(); ++c)
1352 constituents.push_back(arguments[c]);
1353 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001354 } else if (isMatrix)
1355 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1356 else
1357 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001358
1359 builder.clearAccessChain();
1360 builder.setAccessChainRValue(constructed);
1361
1362 return false;
1363 }
1364
1365 // These six are component-wise compares with component-wise results.
1366 // Forward on to createBinaryOperation(), requesting a vector result.
1367 case glslang::EOpLessThan:
1368 case glslang::EOpGreaterThan:
1369 case glslang::EOpLessThanEqual:
1370 case glslang::EOpGreaterThanEqual:
1371 case glslang::EOpVectorEqual:
1372 case glslang::EOpVectorNotEqual:
1373 {
1374 // Map the operation to a binary
1375 binOp = node->getOp();
1376 reduceComparison = false;
1377 switch (node->getOp()) {
1378 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1379 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1380 default: binOp = node->getOp(); break;
1381 }
1382
1383 break;
1384 }
1385 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001386 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001387 binOp = glslang::EOpMul;
1388 break;
1389 case glslang::EOpOuterProduct:
1390 // two vectors multiplied to make a matrix
1391 binOp = glslang::EOpOuterProduct;
1392 break;
1393 case glslang::EOpDot:
1394 {
qining25262b32016-05-06 17:25:16 -04001395 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001396 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001397 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001398 binOp = glslang::EOpMul;
1399 break;
1400 }
1401 case glslang::EOpMod:
1402 // when an aggregate, this is the floating-point mod built-in function,
1403 // which can be emitted by the one in createBinaryOperation()
1404 binOp = glslang::EOpMod;
1405 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001406 case glslang::EOpEmitVertex:
1407 case glslang::EOpEndPrimitive:
1408 case glslang::EOpBarrier:
1409 case glslang::EOpMemoryBarrier:
1410 case glslang::EOpMemoryBarrierAtomicCounter:
1411 case glslang::EOpMemoryBarrierBuffer:
1412 case glslang::EOpMemoryBarrierImage:
1413 case glslang::EOpMemoryBarrierShared:
1414 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001415 case glslang::EOpAllMemoryBarrierWithGroupSync:
1416 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1417 case glslang::EOpWorkgroupMemoryBarrier:
1418 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001419 noReturnValue = true;
1420 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1421 break;
1422
John Kessenich426394d2015-07-23 10:22:48 -06001423 case glslang::EOpAtomicAdd:
1424 case glslang::EOpAtomicMin:
1425 case glslang::EOpAtomicMax:
1426 case glslang::EOpAtomicAnd:
1427 case glslang::EOpAtomicOr:
1428 case glslang::EOpAtomicXor:
1429 case glslang::EOpAtomicExchange:
1430 case glslang::EOpAtomicCompSwap:
1431 atomic = true;
1432 break;
1433
John Kessenich140f3df2015-06-26 16:58:36 -06001434 default:
1435 break;
1436 }
1437
1438 //
1439 // See if it maps to a regular operation.
1440 //
John Kessenich140f3df2015-06-26 16:58:36 -06001441 if (binOp != glslang::EOpNull) {
1442 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1443 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1444 assert(left && right);
1445
1446 builder.clearAccessChain();
1447 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001448 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001449
1450 builder.clearAccessChain();
1451 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001452 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001453
qining25262b32016-05-06 17:25:16 -04001454 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1455 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001456 left->getType().getBasicType(), reduceComparison);
1457
1458 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001459 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001460 builder.clearAccessChain();
1461 builder.setAccessChainRValue(result);
1462
1463 return false;
1464 }
1465
John Kessenich426394d2015-07-23 10:22:48 -06001466 //
1467 // Create the list of operands.
1468 //
John Kessenich140f3df2015-06-26 16:58:36 -06001469 glslang::TIntermSequence& glslangOperands = node->getSequence();
1470 std::vector<spv::Id> operands;
1471 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1472 builder.clearAccessChain();
1473 glslangOperands[arg]->traverse(this);
1474
1475 // special case l-value operands; there are just a few
1476 bool lvalue = false;
1477 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001478 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001479 case glslang::EOpModf:
1480 if (arg == 1)
1481 lvalue = true;
1482 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001483 case glslang::EOpInterpolateAtSample:
1484 case glslang::EOpInterpolateAtOffset:
1485 if (arg == 0)
1486 lvalue = true;
1487 break;
Rex Xud4782c12015-09-06 16:30:11 +08001488 case glslang::EOpAtomicAdd:
1489 case glslang::EOpAtomicMin:
1490 case glslang::EOpAtomicMax:
1491 case glslang::EOpAtomicAnd:
1492 case glslang::EOpAtomicOr:
1493 case glslang::EOpAtomicXor:
1494 case glslang::EOpAtomicExchange:
1495 case glslang::EOpAtomicCompSwap:
1496 if (arg == 0)
1497 lvalue = true;
1498 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001499 case glslang::EOpAddCarry:
1500 case glslang::EOpSubBorrow:
1501 if (arg == 2)
1502 lvalue = true;
1503 break;
1504 case glslang::EOpUMulExtended:
1505 case glslang::EOpIMulExtended:
1506 if (arg >= 2)
1507 lvalue = true;
1508 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001509 default:
1510 break;
1511 }
1512 if (lvalue)
1513 operands.push_back(builder.accessChainGetLValue());
1514 else
John Kessenich32cfd492016-02-02 12:37:46 -07001515 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001516 }
John Kessenich426394d2015-07-23 10:22:48 -06001517
1518 if (atomic) {
1519 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001520 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001521 } else {
1522 // Pass through to generic operations.
1523 switch (glslangOperands.size()) {
1524 case 0:
1525 result = createNoArgOperation(node->getOp());
1526 break;
1527 case 1:
qining25262b32016-05-06 17:25:16 -04001528 result = createUnaryOperation(
1529 node->getOp(), precision,
1530 TranslateNoContractionDecoration(node->getType().getQualifier()),
1531 convertGlslangToSpvType(node->getType()), operands.front(),
1532 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001533 break;
1534 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001535 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001536 break;
1537 }
John Kessenich140f3df2015-06-26 16:58:36 -06001538 }
1539
1540 if (noReturnValue)
1541 return false;
1542
1543 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001544 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001545 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001546 } else {
1547 builder.clearAccessChain();
1548 builder.setAccessChainRValue(result);
1549 return false;
1550 }
1551}
1552
1553bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1554{
1555 // This path handles both if-then-else and ?:
1556 // The if-then-else has a node type of void, while
1557 // ?: has a non-void node type
1558 spv::Id result = 0;
1559 if (node->getBasicType() != glslang::EbtVoid) {
1560 // don't handle this as just on-the-fly temporaries, because there will be two names
1561 // and better to leave SSA to later passes
1562 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1563 }
1564
1565 // emit the condition before doing anything with selection
1566 node->getCondition()->traverse(this);
1567
1568 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001569 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001570
1571 if (node->getTrueBlock()) {
1572 // emit the "then" statement
1573 node->getTrueBlock()->traverse(this);
1574 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001575 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001576 }
1577
1578 if (node->getFalseBlock()) {
1579 ifBuilder.makeBeginElse();
1580 // emit the "else" statement
1581 node->getFalseBlock()->traverse(this);
1582 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001583 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001584 }
1585
1586 ifBuilder.makeEndIf();
1587
1588 if (result) {
1589 // GLSL only has r-values as the result of a :?, but
1590 // if we have an l-value, that can be more efficient if it will
1591 // become the base of a complex r-value expression, because the
1592 // next layer copies r-values into memory to use the access-chain mechanism
1593 builder.clearAccessChain();
1594 builder.setAccessChainLValue(result);
1595 }
1596
1597 return false;
1598}
1599
1600bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1601{
1602 // emit and get the condition before doing anything with switch
1603 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001604 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001605
1606 // browse the children to sort out code segments
1607 int defaultSegment = -1;
1608 std::vector<TIntermNode*> codeSegments;
1609 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1610 std::vector<int> caseValues;
1611 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1612 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1613 TIntermNode* child = *c;
1614 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001615 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001616 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001617 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001618 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1619 } else
1620 codeSegments.push_back(child);
1621 }
1622
qining25262b32016-05-06 17:25:16 -04001623 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001624 // statements between the last case and the end of the switch statement
1625 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1626 (int)codeSegments.size() == defaultSegment)
1627 codeSegments.push_back(nullptr);
1628
1629 // make the switch statement
1630 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001631 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001632
1633 // emit all the code in the segments
1634 breakForLoop.push(false);
1635 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1636 builder.nextSwitchSegment(segmentBlocks, s);
1637 if (codeSegments[s])
1638 codeSegments[s]->traverse(this);
1639 else
1640 builder.addSwitchBreak();
1641 }
1642 breakForLoop.pop();
1643
1644 builder.endSwitch(segmentBlocks);
1645
1646 return false;
1647}
1648
1649void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1650{
1651 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001652 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001653
1654 builder.clearAccessChain();
1655 builder.setAccessChainRValue(constant);
1656}
1657
1658bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1659{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001660 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001661 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001662 // Spec requires back edges to target header blocks, and every header block
1663 // must dominate its merge block. Make a header block first to ensure these
1664 // conditions are met. By definition, it will contain OpLoopMerge, followed
1665 // by a block-ending branch. But we don't want to put any other body/test
1666 // instructions in it, since the body/test may have arbitrary instructions,
1667 // including merges of its own.
1668 builder.setBuildPoint(&blocks.head);
1669 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001670 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001671 spv::Block& test = builder.makeNewBlock();
1672 builder.createBranch(&test);
1673
1674 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001676 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001677 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001678 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1679
1680 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001681 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001682 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001683 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001684 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001685 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001686
1687 builder.setBuildPoint(&blocks.continue_target);
1688 if (node->getTerminal())
1689 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001690 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001691 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001692 builder.createBranch(&blocks.body);
1693
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001694 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001695 builder.setBuildPoint(&blocks.body);
1696 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001697 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001698 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001699 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001700
1701 builder.setBuildPoint(&blocks.continue_target);
1702 if (node->getTerminal())
1703 node->getTerminal()->traverse(this);
1704 if (node->getTest()) {
1705 node->getTest()->traverse(this);
1706 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001707 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001708 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001709 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001710 // TODO: unless there was a break/return/discard instruction
1711 // somewhere in the body, this is an infinite loop, so we should
1712 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001713 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001714 }
John Kessenich140f3df2015-06-26 16:58:36 -06001715 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001716 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001717 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001718 return false;
1719}
1720
1721bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1722{
1723 if (node->getExpression())
1724 node->getExpression()->traverse(this);
1725
1726 switch (node->getFlowOp()) {
1727 case glslang::EOpKill:
1728 builder.makeDiscard();
1729 break;
1730 case glslang::EOpBreak:
1731 if (breakForLoop.top())
1732 builder.createLoopExit();
1733 else
1734 builder.addSwitchBreak();
1735 break;
1736 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001737 builder.createLoopContinue();
1738 break;
1739 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001740 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001741 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001742 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001743 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001744
1745 builder.clearAccessChain();
1746 break;
1747
1748 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001749 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001750 break;
1751 }
1752
1753 return false;
1754}
1755
1756spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1757{
qining25262b32016-05-06 17:25:16 -04001758 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001759 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001760 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001761 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001762 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001763 }
1764
1765 // Now, handle actual variables
1766 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1767 spv::Id spvType = convertGlslangToSpvType(node->getType());
1768
1769 const char* name = node->getName().c_str();
1770 if (glslang::IsAnonymous(name))
1771 name = "";
1772
1773 return builder.createVariable(storageClass, spvType, name);
1774}
1775
1776// Return type Id of the sampled type.
1777spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1778{
1779 switch (sampler.type) {
1780 case glslang::EbtFloat: return builder.makeFloatType(32);
1781 case glslang::EbtInt: return builder.makeIntType(32);
1782 case glslang::EbtUint: return builder.makeUintType(32);
1783 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001784 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001785 return builder.makeFloatType(32);
1786 }
1787}
1788
John Kessenich3ac051e2015-12-20 11:29:16 -07001789// Convert from a glslang type to an SPV type, by calling into a
1790// recursive version of this function. This establishes the inherited
1791// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001792spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1793{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001794 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001795}
1796
1797// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001798// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001799// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001800spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001801{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001802 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001803
1804 switch (type.getBasicType()) {
1805 case glslang::EbtVoid:
1806 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001807 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001808 break;
1809 case glslang::EbtFloat:
1810 spvType = builder.makeFloatType(32);
1811 break;
1812 case glslang::EbtDouble:
1813 spvType = builder.makeFloatType(64);
1814 break;
1815 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001816 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1817 // a 32-bit int where non-0 means true.
1818 if (explicitLayout != glslang::ElpNone)
1819 spvType = builder.makeUintType(32);
1820 else
1821 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001822 break;
1823 case glslang::EbtInt:
1824 spvType = builder.makeIntType(32);
1825 break;
1826 case glslang::EbtUint:
1827 spvType = builder.makeUintType(32);
1828 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001829 case glslang::EbtInt64:
1830 builder.addCapability(spv::CapabilityInt64);
1831 spvType = builder.makeIntType(64);
1832 break;
1833 case glslang::EbtUint64:
1834 builder.addCapability(spv::CapabilityInt64);
1835 spvType = builder.makeUintType(64);
1836 break;
John Kessenich426394d2015-07-23 10:22:48 -06001837 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001838 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001839 spvType = builder.makeUintType(32);
1840 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001841 case glslang::EbtSampler:
1842 {
1843 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001844 if (sampler.sampler) {
1845 // pure sampler
1846 spvType = builder.makeSamplerType();
1847 } else {
1848 // an image is present, make its type
1849 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1850 sampler.image ? 2 : 1, TranslateImageFormat(type));
1851 if (sampler.combined) {
1852 // already has both image and sampler, make the combined type
1853 spvType = builder.makeSampledImageType(spvType);
1854 }
John Kessenich55e7d112015-11-15 21:33:39 -07001855 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001856 }
John Kessenich140f3df2015-06-26 16:58:36 -06001857 break;
1858 case glslang::EbtStruct:
1859 case glslang::EbtBlock:
1860 {
1861 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001862 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001863
1864 // Try to share structs for different layouts, but not yet for other
1865 // kinds of qualification (primarily not yet including interpolant qualification).
1866 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001867 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001868 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001869 break;
1870
1871 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001872 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001873 memberRemapper[glslangMembers].resize(glslangMembers->size());
1874 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
1876 break;
1877 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001878 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001879 break;
1880 }
1881
1882 if (type.isMatrix())
1883 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1884 else {
1885 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1886 if (type.getVectorSize() > 1)
1887 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1888 }
1889
1890 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001891 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1892
John Kessenichc9a80832015-09-12 12:17:44 -06001893 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001894 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001895 // We need to decorate array strides for types needing explicit layout, except blocks.
1896 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001897 // Use a dummy glslang type for querying internal strides of
1898 // arrays of arrays, but using just a one-dimensional array.
1899 glslang::TType simpleArrayType(type, 0); // deference type of the array
1900 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1901 simpleArrayType.getArraySizes().dereference();
1902
1903 // Will compute the higher-order strides here, rather than making a whole
1904 // pile of types and doing repetitive recursion on their contents.
1905 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1906 }
John Kessenichf8842e52016-01-04 19:22:56 -07001907
1908 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001909 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001910 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001911 if (stride > 0)
1912 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001913 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001914 }
1915 } else {
1916 // single-dimensional array, and don't yet have stride
1917
John Kessenichf8842e52016-01-04 19:22:56 -07001918 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001919 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1920 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001921 }
John Kessenich31ed4832015-09-09 17:51:38 -06001922
John Kessenichc9a80832015-09-12 12:17:44 -06001923 // Do the outer dimension, which might not be known for a runtime-sized array
1924 if (type.isRuntimeSizedArray()) {
1925 spvType = builder.makeRuntimeArray(spvType);
1926 } else {
1927 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001928 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001929 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001930 if (stride > 0)
1931 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001932 }
1933
1934 return spvType;
1935}
1936
John Kessenich6090df02016-06-30 21:18:02 -06001937
1938// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
1939// explicitLayout can be kept the same throughout the hierarchical recursive walk.
1940// Mutually recursive with convertGlslangToSpvType().
1941spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
1942 const glslang::TTypeList* glslangMembers,
1943 glslang::TLayoutPacking explicitLayout,
1944 const glslang::TQualifier& qualifier)
1945{
1946 // Create a vector of struct types for SPIR-V to consume
1947 std::vector<spv::Id> spvMembers;
1948 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1949 int locationOffset = 0; // for use across struct members, when they are called recursively
1950 for (int i = 0; i < (int)glslangMembers->size(); i++) {
1951 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
1952 if (glslangMember.hiddenMember()) {
1953 ++memberDelta;
1954 if (type.getBasicType() == glslang::EbtBlock)
1955 memberRemapper[glslangMembers][i] = -1;
1956 } else {
1957 if (type.getBasicType() == glslang::EbtBlock)
1958 memberRemapper[glslangMembers][i] = i - memberDelta;
1959 // modify just this child's view of the qualifier
1960 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
1961 InheritQualifiers(memberQualifier, qualifier);
1962
1963 // manually inherit location; it's more complex
1964 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
1965 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1966 if (qualifier.hasLocation())
1967 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
1968
1969 // recurse
1970 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
1971 }
1972 }
1973
1974 // Make the SPIR-V type
1975 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
1976 if (! HasNonLayoutQualifiers(qualifier))
1977 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
1978
1979 // Decorate it
1980 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
1981
1982 return spvType;
1983}
1984
1985void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
1986 const glslang::TTypeList* glslangMembers,
1987 glslang::TLayoutPacking explicitLayout,
1988 const glslang::TQualifier& qualifier,
1989 spv::Id spvType)
1990{
1991 // Name and decorate the non-hidden members
1992 int offset = -1;
1993 int locationOffset = 0; // for use within the members of this struct
1994 for (int i = 0; i < (int)glslangMembers->size(); i++) {
1995 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
1996 int member = i;
1997 if (type.getBasicType() == glslang::EbtBlock)
1998 member = memberRemapper[glslangMembers][i];
1999
2000 // modify just this child's view of the qualifier
2001 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2002 InheritQualifiers(memberQualifier, qualifier);
2003
2004 // using -1 above to indicate a hidden member
2005 if (member >= 0) {
2006 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2007 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2008 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2009 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2010 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2011 if (type.getBasicType() == glslang::EbtBlock) {
2012 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2013 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2014 }
2015 }
2016 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2017
2018 if (qualifier.storage == glslang::EvqBuffer) {
2019 std::vector<spv::Decoration> memory;
2020 TranslateMemoryDecoration(memberQualifier, memory);
2021 for (unsigned int i = 0; i < memory.size(); ++i)
2022 addMemberDecoration(spvType, member, memory[i]);
2023 }
2024
John Kessenich2f47bc92016-06-30 21:47:35 -06002025 // Compute location decoration; tricky based on whether inheritance is at play and
2026 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002027 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2028 // probably move to the linker stage of the front end proper, and just have the
2029 // answer sitting already distributed throughout the individual member locations.
2030 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002031 // Ignore member locations if the container is an array, as that's
2032 // ill-specified and decisions have been made to not allow this anyway.
2033 // The object itself must have a location, and that comes out from decorating the object,
2034 // not the type (this code decorates types).
2035 if (! type.isArray()) {
2036 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2037 // struct members should not have explicit locations
2038 assert(type.getBasicType() != glslang::EbtStruct);
2039 location = memberQualifier.layoutLocation;
2040 } else if (type.getBasicType() != glslang::EbtBlock) {
2041 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2042 // The members, and their nested types, must not themselves have Location decorations.
2043 } else if (qualifier.hasLocation()) // inheritance
2044 location = qualifier.layoutLocation + locationOffset;
2045 }
John Kessenich6090df02016-06-30 21:18:02 -06002046 if (location >= 0)
2047 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2048
John Kessenich2f47bc92016-06-30 21:47:35 -06002049 if (qualifier.hasLocation()) // track for upcoming inheritance
2050 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2051
John Kessenich6090df02016-06-30 21:18:02 -06002052 // component, XFB, others
2053 if (glslangMember.getQualifier().hasComponent())
2054 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2055 if (glslangMember.getQualifier().hasXfbOffset())
2056 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2057 else if (explicitLayout != glslang::ElpNone) {
2058 // figure out what to do with offset, which is accumulating
2059 int nextOffset;
2060 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2061 if (offset >= 0)
2062 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2063 offset = nextOffset;
2064 }
2065
2066 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2067 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2068
2069 // built-in variable decorations
2070 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2071 if (builtIn != spv::BadValue)
2072 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2073 }
2074 }
2075
2076 // Decorate the structure
2077 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2078 addDecoration(spvType, TranslateBlockDecoration(type));
2079 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2080 builder.addCapability(spv::CapabilityGeometryStreams);
2081 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2082 }
2083 if (glslangIntermediate->getXfbMode()) {
2084 builder.addCapability(spv::CapabilityTransformFeedback);
2085 if (type.getQualifier().hasXfbStride())
2086 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2087 if (type.getQualifier().hasXfbBuffer())
2088 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2089 }
2090}
2091
John Kessenich6c292d32016-02-15 20:58:50 -07002092// Turn the expression forming the array size into an id.
2093// This is not quite trivial, because of specialization constants.
2094// Sometimes, a raw constant is turned into an Id, and sometimes
2095// a specialization constant expression is.
2096spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2097{
2098 // First, see if this is sized with a node, meaning a specialization constant:
2099 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2100 if (specNode != nullptr) {
2101 builder.clearAccessChain();
2102 specNode->traverse(this);
2103 return accessChainLoad(specNode->getAsTyped()->getType());
2104 }
qining25262b32016-05-06 17:25:16 -04002105
John Kessenich6c292d32016-02-15 20:58:50 -07002106 // Otherwise, need a compile-time (front end) size, get it:
2107 int size = arraySizes.getDimSize(dim);
2108 assert(size > 0);
2109 return builder.makeUintConstant(size);
2110}
2111
John Kessenich103bef92016-02-08 21:38:15 -07002112// Wrap the builder's accessChainLoad to:
2113// - localize handling of RelaxedPrecision
2114// - use the SPIR-V inferred type instead of another conversion of the glslang type
2115// (avoids unnecessary work and possible type punning for structures)
2116// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002117spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2118{
John Kessenich103bef92016-02-08 21:38:15 -07002119 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2120 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2121
2122 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002123 if (type.getBasicType() == glslang::EbtBool) {
2124 if (builder.isScalarType(nominalTypeId)) {
2125 // Conversion for bool
2126 spv::Id boolType = builder.makeBoolType();
2127 if (nominalTypeId != boolType)
2128 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2129 } else if (builder.isVectorType(nominalTypeId)) {
2130 // Conversion for bvec
2131 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2132 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2133 if (nominalTypeId != bvecType)
2134 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2135 }
2136 }
John Kessenich103bef92016-02-08 21:38:15 -07002137
2138 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002139}
2140
Rex Xu27253232016-02-23 17:51:09 +08002141// Wrap the builder's accessChainStore to:
2142// - do conversion of concrete to abstract type
2143void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2144{
2145 // Need to convert to abstract types when necessary
2146 if (type.getBasicType() == glslang::EbtBool) {
2147 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2148
2149 if (builder.isScalarType(nominalTypeId)) {
2150 // Conversion for bool
2151 spv::Id boolType = builder.makeBoolType();
2152 if (nominalTypeId != boolType) {
2153 spv::Id zero = builder.makeUintConstant(0);
2154 spv::Id one = builder.makeUintConstant(1);
2155 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2156 }
2157 } else if (builder.isVectorType(nominalTypeId)) {
2158 // Conversion for bvec
2159 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2160 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2161 if (nominalTypeId != bvecType) {
2162 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2163 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2164 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2165 }
2166 }
2167 }
2168
2169 builder.accessChainStore(rvalue);
2170}
2171
John Kessenichf85e8062015-12-19 13:57:10 -07002172// Decide whether or not this type should be
2173// decorated with offsets and strides, and if so
2174// whether std140 or std430 rules should be applied.
2175glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002176{
John Kessenichf85e8062015-12-19 13:57:10 -07002177 // has to be a block
2178 if (type.getBasicType() != glslang::EbtBlock)
2179 return glslang::ElpNone;
2180
2181 // has to be a uniform or buffer block
2182 if (type.getQualifier().storage != glslang::EvqUniform &&
2183 type.getQualifier().storage != glslang::EvqBuffer)
2184 return glslang::ElpNone;
2185
2186 // return the layout to use
2187 switch (type.getQualifier().layoutPacking) {
2188 case glslang::ElpStd140:
2189 case glslang::ElpStd430:
2190 return type.getQualifier().layoutPacking;
2191 default:
2192 return glslang::ElpNone;
2193 }
John Kessenich31ed4832015-09-09 17:51:38 -06002194}
2195
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002196// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002197int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002198{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002199 int size;
John Kessenich49987892015-12-29 17:11:44 -07002200 int stride;
2201 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002202
2203 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002204}
2205
John Kessenich49987892015-12-29 17:11:44 -07002206// 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 -07002207// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002208int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002209{
John Kessenich49987892015-12-29 17:11:44 -07002210 glslang::TType elementType;
2211 elementType.shallowCopy(matrixType);
2212 elementType.clearArraySizes();
2213
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002214 int size;
John Kessenich49987892015-12-29 17:11:44 -07002215 int stride;
2216 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2217
2218 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002219}
2220
John Kessenich5e4b1242015-08-06 22:53:06 -06002221// Given a member type of a struct, realign the current offset for it, and compute
2222// the next (not yet aligned) offset for the next member, which will get aligned
2223// on the next call.
2224// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2225// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2226// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002227void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002228 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002229{
2230 // this will get a positive value when deemed necessary
2231 nextOffset = -1;
2232
John Kessenich5e4b1242015-08-06 22:53:06 -06002233 // override anything in currentOffset with user-set offset
2234 if (memberType.getQualifier().hasOffset())
2235 currentOffset = memberType.getQualifier().layoutOffset;
2236
2237 // It could be that current linker usage in glslang updated all the layoutOffset,
2238 // in which case the following code does not matter. But, that's not quite right
2239 // once cross-compilation unit GLSL validation is done, as the original user
2240 // settings are needed in layoutOffset, and then the following will come into play.
2241
John Kessenichf85e8062015-12-19 13:57:10 -07002242 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002243 if (! memberType.getQualifier().hasOffset())
2244 currentOffset = -1;
2245
2246 return;
2247 }
2248
John Kessenichf85e8062015-12-19 13:57:10 -07002249 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002250 if (currentOffset < 0)
2251 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002252
John Kessenich5e4b1242015-08-06 22:53:06 -06002253 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2254 // but possibly not yet correctly aligned.
2255
2256 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002257 int dummyStride;
2258 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002259 glslang::RoundToPow2(currentOffset, memberAlignment);
2260 nextOffset = currentOffset + memberSize;
2261}
2262
David Netoa901ffe2016-06-08 14:11:40 +01002263void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002264{
David Netoa901ffe2016-06-08 14:11:40 +01002265 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2266 switch (glslangBuiltIn)
2267 {
2268 case glslang::EbvClipDistance:
2269 case glslang::EbvCullDistance:
2270 case glslang::EbvPointSize:
2271 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2272 // Alternately, we could just call this for any glslang built-in, since the
2273 // capability already guards against duplicates.
2274 TranslateBuiltInDecoration(glslangBuiltIn, false);
2275 break;
2276 default:
2277 // Capabilities were already generated when the struct was declared.
2278 break;
2279 }
John Kessenichebb50532016-05-16 19:22:05 -06002280}
2281
John Kessenich140f3df2015-06-26 16:58:36 -06002282bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2283{
John Kessenich4d65ee32016-03-12 18:17:47 -07002284 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002285 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002286 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002287}
2288
2289// Make all the functions, skeletally, without actually visiting their bodies.
2290void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2291{
2292 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2293 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2294 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2295 continue;
2296
2297 // We're on a user function. Set up the basic interface for the function now,
2298 // so that it's available to call.
2299 // Translating the body will happen later.
2300 //
qining25262b32016-05-06 17:25:16 -04002301 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002302 // function. What it is an address of varies:
2303 //
2304 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2305 // so that write needs to be to a copy, hence the address of a copy works.
2306 //
2307 // - "const in" parameters can just be the r-value, as no writes need occur.
2308 //
2309 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2310 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2311
2312 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002313 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002314 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2315
2316 for (int p = 0; p < (int)parameters.size(); ++p) {
2317 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2318 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002319 if (paramType.isOpaque())
2320 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2321 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002322 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2323 else
2324 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002325 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002326 paramTypes.push_back(typeId);
2327 }
2328
2329 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002330 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2331 convertGlslangToSpvType(glslFunction->getType()),
2332 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002333
2334 // Track function to emit/call later
2335 functionMap[glslFunction->getName().c_str()] = function;
2336
2337 // Set the parameter id's
2338 for (int p = 0; p < (int)parameters.size(); ++p) {
2339 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2340 // give a name too
2341 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2342 }
2343 }
2344}
2345
2346// Process all the initializers, while skipping the functions and link objects
2347void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2348{
2349 builder.setBuildPoint(shaderEntry->getLastBlock());
2350 for (int i = 0; i < (int)initializers.size(); ++i) {
2351 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2352 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2353
2354 // We're on a top-level node that's not a function. Treat as an initializer, whose
2355 // code goes into the beginning of main.
2356 initializer->traverse(this);
2357 }
2358 }
2359}
2360
2361// Process all the functions, while skipping initializers.
2362void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2363{
2364 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2365 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2366 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2367 node->traverse(this);
2368 }
2369}
2370
2371void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2372{
qining25262b32016-05-06 17:25:16 -04002373 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002374 // that called makeFunctions().
2375 spv::Function* function = functionMap[node->getName().c_str()];
2376 spv::Block* functionBlock = function->getEntryBlock();
2377 builder.setBuildPoint(functionBlock);
2378}
2379
Rex Xu04db3f52015-09-16 11:44:02 +08002380void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002381{
Rex Xufc618912015-09-09 16:42:49 +08002382 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002383
2384 glslang::TSampler sampler = {};
2385 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002386 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002387 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2388 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2389 }
2390
John Kessenich140f3df2015-06-26 16:58:36 -06002391 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2392 builder.clearAccessChain();
2393 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002394
2395 // Special case l-value operands
2396 bool lvalue = false;
2397 switch (node.getOp()) {
2398 case glslang::EOpImageAtomicAdd:
2399 case glslang::EOpImageAtomicMin:
2400 case glslang::EOpImageAtomicMax:
2401 case glslang::EOpImageAtomicAnd:
2402 case glslang::EOpImageAtomicOr:
2403 case glslang::EOpImageAtomicXor:
2404 case glslang::EOpImageAtomicExchange:
2405 case glslang::EOpImageAtomicCompSwap:
2406 if (i == 0)
2407 lvalue = true;
2408 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002409 case glslang::EOpSparseImageLoad:
2410 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2411 lvalue = true;
2412 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002413 case glslang::EOpSparseTexture:
2414 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2415 lvalue = true;
2416 break;
2417 case glslang::EOpSparseTextureClamp:
2418 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2419 lvalue = true;
2420 break;
2421 case glslang::EOpSparseTextureLod:
2422 case glslang::EOpSparseTextureOffset:
2423 if (i == 3)
2424 lvalue = true;
2425 break;
2426 case glslang::EOpSparseTextureFetch:
2427 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2428 lvalue = true;
2429 break;
2430 case glslang::EOpSparseTextureFetchOffset:
2431 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2432 lvalue = true;
2433 break;
2434 case glslang::EOpSparseTextureLodOffset:
2435 case glslang::EOpSparseTextureGrad:
2436 case glslang::EOpSparseTextureOffsetClamp:
2437 if (i == 4)
2438 lvalue = true;
2439 break;
2440 case glslang::EOpSparseTextureGradOffset:
2441 case glslang::EOpSparseTextureGradClamp:
2442 if (i == 5)
2443 lvalue = true;
2444 break;
2445 case glslang::EOpSparseTextureGradOffsetClamp:
2446 if (i == 6)
2447 lvalue = true;
2448 break;
2449 case glslang::EOpSparseTextureGather:
2450 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2451 lvalue = true;
2452 break;
2453 case glslang::EOpSparseTextureGatherOffset:
2454 case glslang::EOpSparseTextureGatherOffsets:
2455 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2456 lvalue = true;
2457 break;
Rex Xufc618912015-09-09 16:42:49 +08002458 default:
2459 break;
2460 }
2461
Rex Xu6b86d492015-09-16 17:48:22 +08002462 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002463 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002464 else
John Kessenich32cfd492016-02-02 12:37:46 -07002465 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002466 }
2467}
2468
John Kessenichfc51d282015-08-19 13:34:18 -06002469void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002470{
John Kessenichfc51d282015-08-19 13:34:18 -06002471 builder.clearAccessChain();
2472 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002473 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002474}
John Kessenich140f3df2015-06-26 16:58:36 -06002475
John Kessenichfc51d282015-08-19 13:34:18 -06002476spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2477{
Rex Xufc618912015-09-09 16:42:49 +08002478 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002479 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002480 }
2481
John Kessenichfc51d282015-08-19 13:34:18 -06002482 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002483 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2484 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2485 std::vector<spv::Id> arguments;
2486 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002487 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002488 else
2489 translateArguments(*node->getAsUnaryNode(), arguments);
2490 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2491
2492 spv::Builder::TextureParameters params = { };
2493 params.sampler = arguments[0];
2494
Rex Xu04db3f52015-09-16 11:44:02 +08002495 glslang::TCrackedTextureOp cracked;
2496 node->crackTexture(sampler, cracked);
2497
John Kessenichfc51d282015-08-19 13:34:18 -06002498 // Check for queries
2499 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002500 // a sampled image needs to have the image extracted first
2501 if (builder.isSampledImage(params.sampler))
2502 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002503 switch (node->getOp()) {
2504 case glslang::EOpImageQuerySize:
2505 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002506 if (arguments.size() > 1) {
2507 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002508 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002509 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002510 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002511 case glslang::EOpImageQuerySamples:
2512 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002513 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002514 case glslang::EOpTextureQueryLod:
2515 params.coords = arguments[1];
2516 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2517 case glslang::EOpTextureQueryLevels:
2518 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002519 case glslang::EOpSparseTexelsResident:
2520 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002521 default:
2522 assert(0);
2523 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002524 }
John Kessenich140f3df2015-06-26 16:58:36 -06002525 }
2526
Rex Xufc618912015-09-09 16:42:49 +08002527 // Check for image functions other than queries
2528 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002529 std::vector<spv::Id> operands;
2530 auto opIt = arguments.begin();
2531 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002532
2533 // Handle subpass operations
2534 // TODO: GLSL should change to have the "MS" only on the type rather than the
2535 // built-in function.
2536 if (cracked.subpass) {
2537 // add on the (0,0) coordinate
2538 spv::Id zero = builder.makeIntConstant(0);
2539 std::vector<spv::Id> comps;
2540 comps.push_back(zero);
2541 comps.push_back(zero);
2542 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2543 if (sampler.ms) {
2544 operands.push_back(spv::ImageOperandsSampleMask);
2545 operands.push_back(*(opIt++));
2546 }
2547 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2548 }
2549
John Kessenich56bab042015-09-16 10:54:31 -06002550 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002551 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002552 if (sampler.ms) {
2553 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002554 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002555 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002556 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2557 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002558 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002559 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002560 if (sampler.ms) {
2561 operands.push_back(*(opIt + 1));
2562 operands.push_back(spv::ImageOperandsSampleMask);
2563 operands.push_back(*opIt);
2564 } else
2565 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002566 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002567 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2568 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002569 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002570 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2571 builder.addCapability(spv::CapabilitySparseResidency);
2572 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2573 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2574
2575 if (sampler.ms) {
2576 operands.push_back(spv::ImageOperandsSampleMask);
2577 operands.push_back(*opIt++);
2578 }
2579
2580 // Create the return type that was a special structure
2581 spv::Id texelOut = *opIt;
2582 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2583 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2584 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2585
2586 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2587
2588 // Decode the return type
2589 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2590 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002591 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002592 // Process image atomic operations
2593
2594 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2595 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002596 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002597
Rex Xufc618912015-09-09 16:42:49 +08002598 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002599 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002600
2601 std::vector<spv::Id> operands;
2602 operands.push_back(pointer);
2603 for (; opIt != arguments.end(); ++opIt)
2604 operands.push_back(*opIt);
2605
Rex Xu04db3f52015-09-16 11:44:02 +08002606 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002607 }
2608 }
2609
2610 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002611 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002612 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2613
John Kessenichfc51d282015-08-19 13:34:18 -06002614 // check for bias argument
2615 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002616 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002617 int nonBiasArgCount = 2;
2618 if (cracked.offset)
2619 ++nonBiasArgCount;
2620 if (cracked.grad)
2621 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002622 if (cracked.lodClamp)
2623 ++nonBiasArgCount;
2624 if (sparse)
2625 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002626
2627 if ((int)arguments.size() > nonBiasArgCount)
2628 bias = true;
2629 }
2630
John Kessenicha5c33d62016-06-02 23:45:21 -06002631 // See if the sampler param should really be just the SPV image part
2632 if (cracked.fetch) {
2633 // a fetch needs to have the image extracted first
2634 if (builder.isSampledImage(params.sampler))
2635 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2636 }
2637
John Kessenichfc51d282015-08-19 13:34:18 -06002638 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002639
John Kessenichfc51d282015-08-19 13:34:18 -06002640 params.coords = arguments[1];
2641 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002642 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002643
2644 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002645 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002646 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002647 ++extraArgs;
2648 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002649 params.Dref = arguments[2];
2650 ++extraArgs;
2651 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002652 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002653 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002654 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002655 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002656 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002657 dRefComp = builder.getNumComponents(params.coords) - 1;
2658 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002659 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2660 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002661
2662 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002663 if (cracked.lod) {
2664 params.lod = arguments[2];
2665 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002666 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2667 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2668 noImplicitLod = true;
2669 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002670
2671 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002672 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002673 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002674 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002675 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002676
2677 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002678 if (cracked.grad) {
2679 params.gradX = arguments[2 + extraArgs];
2680 params.gradY = arguments[3 + extraArgs];
2681 extraArgs += 2;
2682 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002683
2684 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002685 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002686 params.offset = arguments[2 + extraArgs];
2687 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002688 } else if (cracked.offsets) {
2689 params.offsets = arguments[2 + extraArgs];
2690 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002691 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002692
2693 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002694 if (cracked.lodClamp) {
2695 params.lodClamp = arguments[2 + extraArgs];
2696 ++extraArgs;
2697 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002698
2699 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002700 if (sparse) {
2701 params.texelOut = arguments[2 + extraArgs];
2702 ++extraArgs;
2703 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002704
2705 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002706 if (bias) {
2707 params.bias = arguments[2 + extraArgs];
2708 ++extraArgs;
2709 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002710
2711 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002712 if (cracked.gather && ! sampler.shadow) {
2713 // default component is 0, if missing, otherwise an argument
2714 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002715 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002716 ++extraArgs;
2717 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002718 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002719 }
2720 }
John Kessenichfc51d282015-08-19 13:34:18 -06002721
John Kessenich65336482016-06-16 14:06:26 -06002722 // projective component (might not to move)
2723 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2724 // are divided by the last component of P."
2725 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2726 // unused components will appear after all used components."
2727 if (cracked.proj) {
2728 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2729 int projTargetComp;
2730 switch (sampler.dim) {
2731 case glslang::Esd1D: projTargetComp = 1; break;
2732 case glslang::Esd2D: projTargetComp = 2; break;
2733 case glslang::EsdRect: projTargetComp = 2; break;
2734 default: projTargetComp = projSourceComp; break;
2735 }
2736 // copy the projective coordinate if we have to
2737 if (projTargetComp != projSourceComp) {
2738 spv::Id projComp = builder.createCompositeExtract(params.coords,
2739 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2740 projSourceComp);
2741 params.coords = builder.createCompositeInsert(projComp, params.coords,
2742 builder.getTypeId(params.coords), projTargetComp);
2743 }
2744 }
2745
John Kessenich019f08f2016-02-15 15:40:42 -07002746 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002747}
2748
2749spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2750{
2751 // Grab the function's pointer from the previously created function
2752 spv::Function* function = functionMap[node->getName().c_str()];
2753 if (! function)
2754 return 0;
2755
2756 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2757 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2758
2759 // See comments in makeFunctions() for details about the semantics for parameter passing.
2760 //
2761 // These imply we need a four step process:
2762 // 1. Evaluate the arguments
2763 // 2. Allocate and make copies of in, out, and inout arguments
2764 // 3. Make the call
2765 // 4. Copy back the results
2766
2767 // 1. Evaluate the arguments
2768 std::vector<spv::Builder::AccessChain> lValues;
2769 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002770 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002771 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002772 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002773 // build l-value
2774 builder.clearAccessChain();
2775 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002776 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002777 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2778 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002779 // save l-value
2780 lValues.push_back(builder.getAccessChain());
2781 } else {
2782 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002783 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002784 }
2785 }
2786
2787 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2788 // copy the original into that space.
2789 //
2790 // Also, build up the list of actual arguments to pass in for the call
2791 int lValueCount = 0;
2792 int rValueCount = 0;
2793 std::vector<spv::Id> spvArgs;
2794 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002795 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002796 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002797 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002798 builder.setAccessChain(lValues[lValueCount]);
2799 arg = builder.accessChainGetLValue();
2800 ++lValueCount;
2801 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002802 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002803 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2804 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2805 // need to copy the input into output space
2806 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002807 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002808 builder.createStore(copy, arg);
2809 }
2810 ++lValueCount;
2811 } else {
2812 arg = rValues[rValueCount];
2813 ++rValueCount;
2814 }
2815 spvArgs.push_back(arg);
2816 }
2817
2818 // 3. Make the call.
2819 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002820 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002821
2822 // 4. Copy back out an "out" arguments.
2823 lValueCount = 0;
2824 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2825 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2826 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2827 spv::Id copy = builder.createLoad(spvArgs[a]);
2828 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002829 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002830 }
2831 ++lValueCount;
2832 }
2833 }
2834
2835 return result;
2836}
2837
2838// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002839spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2840 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002841 spv::Id typeId, spv::Id left, spv::Id right,
2842 glslang::TBasicType typeProxy, bool reduceComparison)
2843{
Rex Xu8ff43de2016-04-22 16:51:45 +08002844 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002845 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002846 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002847
2848 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002849 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002850 bool comparison = false;
2851
2852 switch (op) {
2853 case glslang::EOpAdd:
2854 case glslang::EOpAddAssign:
2855 if (isFloat)
2856 binOp = spv::OpFAdd;
2857 else
2858 binOp = spv::OpIAdd;
2859 break;
2860 case glslang::EOpSub:
2861 case glslang::EOpSubAssign:
2862 if (isFloat)
2863 binOp = spv::OpFSub;
2864 else
2865 binOp = spv::OpISub;
2866 break;
2867 case glslang::EOpMul:
2868 case glslang::EOpMulAssign:
2869 if (isFloat)
2870 binOp = spv::OpFMul;
2871 else
2872 binOp = spv::OpIMul;
2873 break;
2874 case glslang::EOpVectorTimesScalar:
2875 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002876 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002877 if (builder.isVector(right))
2878 std::swap(left, right);
2879 assert(builder.isScalar(right));
2880 needMatchingVectors = false;
2881 binOp = spv::OpVectorTimesScalar;
2882 } else
2883 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002884 break;
2885 case glslang::EOpVectorTimesMatrix:
2886 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002887 binOp = spv::OpVectorTimesMatrix;
2888 break;
2889 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002890 binOp = spv::OpMatrixTimesVector;
2891 break;
2892 case glslang::EOpMatrixTimesScalar:
2893 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002894 binOp = spv::OpMatrixTimesScalar;
2895 break;
2896 case glslang::EOpMatrixTimesMatrix:
2897 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002898 binOp = spv::OpMatrixTimesMatrix;
2899 break;
2900 case glslang::EOpOuterProduct:
2901 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002902 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002903 break;
2904
2905 case glslang::EOpDiv:
2906 case glslang::EOpDivAssign:
2907 if (isFloat)
2908 binOp = spv::OpFDiv;
2909 else if (isUnsigned)
2910 binOp = spv::OpUDiv;
2911 else
2912 binOp = spv::OpSDiv;
2913 break;
2914 case glslang::EOpMod:
2915 case glslang::EOpModAssign:
2916 if (isFloat)
2917 binOp = spv::OpFMod;
2918 else if (isUnsigned)
2919 binOp = spv::OpUMod;
2920 else
2921 binOp = spv::OpSMod;
2922 break;
2923 case glslang::EOpRightShift:
2924 case glslang::EOpRightShiftAssign:
2925 if (isUnsigned)
2926 binOp = spv::OpShiftRightLogical;
2927 else
2928 binOp = spv::OpShiftRightArithmetic;
2929 break;
2930 case glslang::EOpLeftShift:
2931 case glslang::EOpLeftShiftAssign:
2932 binOp = spv::OpShiftLeftLogical;
2933 break;
2934 case glslang::EOpAnd:
2935 case glslang::EOpAndAssign:
2936 binOp = spv::OpBitwiseAnd;
2937 break;
2938 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002939 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002940 binOp = spv::OpLogicalAnd;
2941 break;
2942 case glslang::EOpInclusiveOr:
2943 case glslang::EOpInclusiveOrAssign:
2944 binOp = spv::OpBitwiseOr;
2945 break;
2946 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002947 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002948 binOp = spv::OpLogicalOr;
2949 break;
2950 case glslang::EOpExclusiveOr:
2951 case glslang::EOpExclusiveOrAssign:
2952 binOp = spv::OpBitwiseXor;
2953 break;
2954 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002955 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002956 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002957 break;
2958
2959 case glslang::EOpLessThan:
2960 case glslang::EOpGreaterThan:
2961 case glslang::EOpLessThanEqual:
2962 case glslang::EOpGreaterThanEqual:
2963 case glslang::EOpEqual:
2964 case glslang::EOpNotEqual:
2965 case glslang::EOpVectorEqual:
2966 case glslang::EOpVectorNotEqual:
2967 comparison = true;
2968 break;
2969 default:
2970 break;
2971 }
2972
John Kessenich7c1aa102015-10-15 13:29:11 -06002973 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002974 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002975 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002976 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002977 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002978
2979 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002980 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002981 builder.promoteScalar(precision, left, right);
2982
qining25262b32016-05-06 17:25:16 -04002983 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2984 addDecoration(result, noContraction);
2985 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002986 }
2987
2988 if (! comparison)
2989 return 0;
2990
John Kessenich7c1aa102015-10-15 13:29:11 -06002991 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002992
2993 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2994 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2995
John Kessenich22118352015-12-21 20:54:09 -07002996 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002997 }
2998
2999 switch (op) {
3000 case glslang::EOpLessThan:
3001 if (isFloat)
3002 binOp = spv::OpFOrdLessThan;
3003 else if (isUnsigned)
3004 binOp = spv::OpULessThan;
3005 else
3006 binOp = spv::OpSLessThan;
3007 break;
3008 case glslang::EOpGreaterThan:
3009 if (isFloat)
3010 binOp = spv::OpFOrdGreaterThan;
3011 else if (isUnsigned)
3012 binOp = spv::OpUGreaterThan;
3013 else
3014 binOp = spv::OpSGreaterThan;
3015 break;
3016 case glslang::EOpLessThanEqual:
3017 if (isFloat)
3018 binOp = spv::OpFOrdLessThanEqual;
3019 else if (isUnsigned)
3020 binOp = spv::OpULessThanEqual;
3021 else
3022 binOp = spv::OpSLessThanEqual;
3023 break;
3024 case glslang::EOpGreaterThanEqual:
3025 if (isFloat)
3026 binOp = spv::OpFOrdGreaterThanEqual;
3027 else if (isUnsigned)
3028 binOp = spv::OpUGreaterThanEqual;
3029 else
3030 binOp = spv::OpSGreaterThanEqual;
3031 break;
3032 case glslang::EOpEqual:
3033 case glslang::EOpVectorEqual:
3034 if (isFloat)
3035 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003036 else if (isBool)
3037 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003038 else
3039 binOp = spv::OpIEqual;
3040 break;
3041 case glslang::EOpNotEqual:
3042 case glslang::EOpVectorNotEqual:
3043 if (isFloat)
3044 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003045 else if (isBool)
3046 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003047 else
3048 binOp = spv::OpINotEqual;
3049 break;
3050 default:
3051 break;
3052 }
3053
qining25262b32016-05-06 17:25:16 -04003054 if (binOp != spv::OpNop) {
3055 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3056 addDecoration(result, noContraction);
3057 return builder.setPrecision(result, precision);
3058 }
John Kessenich140f3df2015-06-26 16:58:36 -06003059
3060 return 0;
3061}
3062
John Kessenich04bb8a02015-12-12 12:28:14 -07003063//
3064// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3065// These can be any of:
3066//
3067// matrix * scalar
3068// scalar * matrix
3069// matrix * matrix linear algebraic
3070// matrix * vector
3071// vector * matrix
3072// matrix * matrix componentwise
3073// matrix op matrix op in {+, -, /}
3074// matrix op scalar op in {+, -, /}
3075// scalar op matrix op in {+, -, /}
3076//
qining25262b32016-05-06 17:25:16 -04003077spv::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 -07003078{
3079 bool firstClass = true;
3080
3081 // First, handle first-class matrix operations (* and matrix/scalar)
3082 switch (op) {
3083 case spv::OpFDiv:
3084 if (builder.isMatrix(left) && builder.isScalar(right)) {
3085 // turn matrix / scalar into a multiply...
3086 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3087 op = spv::OpMatrixTimesScalar;
3088 } else
3089 firstClass = false;
3090 break;
3091 case spv::OpMatrixTimesScalar:
3092 if (builder.isMatrix(right))
3093 std::swap(left, right);
3094 assert(builder.isScalar(right));
3095 break;
3096 case spv::OpVectorTimesMatrix:
3097 assert(builder.isVector(left));
3098 assert(builder.isMatrix(right));
3099 break;
3100 case spv::OpMatrixTimesVector:
3101 assert(builder.isMatrix(left));
3102 assert(builder.isVector(right));
3103 break;
3104 case spv::OpMatrixTimesMatrix:
3105 assert(builder.isMatrix(left));
3106 assert(builder.isMatrix(right));
3107 break;
3108 default:
3109 firstClass = false;
3110 break;
3111 }
3112
qining25262b32016-05-06 17:25:16 -04003113 if (firstClass) {
3114 spv::Id result = builder.createBinOp(op, typeId, left, right);
3115 addDecoration(result, noContraction);
3116 return builder.setPrecision(result, precision);
3117 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003118
LoopDawg592860c2016-06-09 08:57:35 -06003119 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003120 // The result type of all of them is the same type as the (a) matrix operand.
3121 // The algorithm is to:
3122 // - break the matrix(es) into vectors
3123 // - smear any scalar to a vector
3124 // - do vector operations
3125 // - make a matrix out the vector results
3126 switch (op) {
3127 case spv::OpFAdd:
3128 case spv::OpFSub:
3129 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003130 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003131 case spv::OpFMul:
3132 {
3133 // one time set up...
3134 bool leftMat = builder.isMatrix(left);
3135 bool rightMat = builder.isMatrix(right);
3136 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3137 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3138 spv::Id scalarType = builder.getScalarTypeId(typeId);
3139 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3140 std::vector<spv::Id> results;
3141 spv::Id smearVec = spv::NoResult;
3142 if (builder.isScalar(left))
3143 smearVec = builder.smearScalar(precision, left, vecType);
3144 else if (builder.isScalar(right))
3145 smearVec = builder.smearScalar(precision, right, vecType);
3146
3147 // do each vector op
3148 for (unsigned int c = 0; c < numCols; ++c) {
3149 std::vector<unsigned int> indexes;
3150 indexes.push_back(c);
3151 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3152 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003153 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3154 addDecoration(result, noContraction);
3155 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003156 }
3157
3158 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003159 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003160 }
3161 default:
3162 assert(0);
3163 return spv::NoResult;
3164 }
3165}
3166
qining25262b32016-05-06 17:25:16 -04003167spv::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 -06003168{
3169 spv::Op unaryOp = spv::OpNop;
3170 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003171 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003172 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003173
3174 switch (op) {
3175 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003176 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003177 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003178 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003179 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003180 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003181 unaryOp = spv::OpSNegate;
3182 break;
3183
3184 case glslang::EOpLogicalNot:
3185 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003186 unaryOp = spv::OpLogicalNot;
3187 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003188 case glslang::EOpBitwiseNot:
3189 unaryOp = spv::OpNot;
3190 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003191
John Kessenich140f3df2015-06-26 16:58:36 -06003192 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
3195 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003196 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003197 break;
3198 case glslang::EOpTranspose:
3199 unaryOp = spv::OpTranspose;
3200 break;
3201
3202 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003203 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003204 break;
3205 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003206 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003207 break;
3208 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003209 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003210 break;
3211 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003212 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003213 break;
3214 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003215 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003216 break;
3217 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003218 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003219 break;
3220 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003221 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 break;
3223 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003224 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003225 break;
3226
3227 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003228 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003229 break;
3230 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003231 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 break;
3233 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003234 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003235 break;
3236 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003237 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003238 break;
3239 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003240 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 break;
3242 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003243 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003244 break;
3245
3246 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003247 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003248 break;
3249 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003250 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003251 break;
3252
3253 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003254 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003255 break;
3256 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003257 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003258 break;
3259 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003260 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003261 break;
3262 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003263 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003264 break;
3265 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003266 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003267 break;
3268 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003269 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003270 break;
3271
3272 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003273 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003274 break;
3275 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003276 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003277 break;
3278 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003279 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003280 break;
3281 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003282 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003283 break;
3284 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003285 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003286 break;
3287 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003288 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003289 break;
3290
3291 case glslang::EOpIsNan:
3292 unaryOp = spv::OpIsNan;
3293 break;
3294 case glslang::EOpIsInf:
3295 unaryOp = spv::OpIsInf;
3296 break;
LoopDawg592860c2016-06-09 08:57:35 -06003297 case glslang::EOpIsFinite:
3298 unaryOp = spv::OpIsFinite;
3299 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003300
Rex Xucbc426e2015-12-15 16:03:10 +08003301 case glslang::EOpFloatBitsToInt:
3302 case glslang::EOpFloatBitsToUint:
3303 case glslang::EOpIntBitsToFloat:
3304 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003305 case glslang::EOpDoubleBitsToInt64:
3306 case glslang::EOpDoubleBitsToUint64:
3307 case glslang::EOpInt64BitsToDouble:
3308 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003309 unaryOp = spv::OpBitcast;
3310 break;
3311
John Kessenich140f3df2015-06-26 16:58:36 -06003312 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
3318 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003319 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003322 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003323 break;
3324 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003325 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003326 break;
3327 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003328 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003329 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003330 case glslang::EOpPackSnorm4x8:
3331 libCall = spv::GLSLstd450PackSnorm4x8;
3332 break;
3333 case glslang::EOpUnpackSnorm4x8:
3334 libCall = spv::GLSLstd450UnpackSnorm4x8;
3335 break;
3336 case glslang::EOpPackUnorm4x8:
3337 libCall = spv::GLSLstd450PackUnorm4x8;
3338 break;
3339 case glslang::EOpUnpackUnorm4x8:
3340 libCall = spv::GLSLstd450UnpackUnorm4x8;
3341 break;
3342 case glslang::EOpPackDouble2x32:
3343 libCall = spv::GLSLstd450PackDouble2x32;
3344 break;
3345 case glslang::EOpUnpackDouble2x32:
3346 libCall = spv::GLSLstd450UnpackDouble2x32;
3347 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003348
Rex Xu8ff43de2016-04-22 16:51:45 +08003349 case glslang::EOpPackInt2x32:
3350 case glslang::EOpUnpackInt2x32:
3351 case glslang::EOpPackUint2x32:
3352 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003353 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003354 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3355 break;
3356
John Kessenich140f3df2015-06-26 16:58:36 -06003357 case glslang::EOpDPdx:
3358 unaryOp = spv::OpDPdx;
3359 break;
3360 case glslang::EOpDPdy:
3361 unaryOp = spv::OpDPdy;
3362 break;
3363 case glslang::EOpFwidth:
3364 unaryOp = spv::OpFwidth;
3365 break;
3366 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003367 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003368 unaryOp = spv::OpDPdxFine;
3369 break;
3370 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003371 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003372 unaryOp = spv::OpDPdyFine;
3373 break;
3374 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003375 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003376 unaryOp = spv::OpFwidthFine;
3377 break;
3378 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003379 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003380 unaryOp = spv::OpDPdxCoarse;
3381 break;
3382 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003383 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003384 unaryOp = spv::OpDPdyCoarse;
3385 break;
3386 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003387 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003388 unaryOp = spv::OpFwidthCoarse;
3389 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003390 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003391 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003392 libCall = spv::GLSLstd450InterpolateAtCentroid;
3393 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003394 case glslang::EOpAny:
3395 unaryOp = spv::OpAny;
3396 break;
3397 case glslang::EOpAll:
3398 unaryOp = spv::OpAll;
3399 break;
3400
3401 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003402 if (isFloat)
3403 libCall = spv::GLSLstd450FAbs;
3404 else
3405 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003406 break;
3407 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003408 if (isFloat)
3409 libCall = spv::GLSLstd450FSign;
3410 else
3411 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003412 break;
3413
John Kessenichfc51d282015-08-19 13:34:18 -06003414 case glslang::EOpAtomicCounterIncrement:
3415 case glslang::EOpAtomicCounterDecrement:
3416 case glslang::EOpAtomicCounter:
3417 {
3418 // Handle all of the atomics in one place, in createAtomicOperation()
3419 std::vector<spv::Id> operands;
3420 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003421 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003422 }
3423
John Kessenichfc51d282015-08-19 13:34:18 -06003424 case glslang::EOpBitFieldReverse:
3425 unaryOp = spv::OpBitReverse;
3426 break;
3427 case glslang::EOpBitCount:
3428 unaryOp = spv::OpBitCount;
3429 break;
3430 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003431 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003432 break;
3433 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003434 if (isUnsigned)
3435 libCall = spv::GLSLstd450FindUMsb;
3436 else
3437 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003438 break;
3439
Rex Xu574ab042016-04-14 16:53:07 +08003440 case glslang::EOpBallot:
3441 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003442 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003443 libCall = spv::GLSLstd450Bad;
3444 break;
3445
Rex Xu338b1852016-05-05 20:38:33 +08003446 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003447 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003448 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003449 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003450
John Kessenich140f3df2015-06-26 16:58:36 -06003451 default:
3452 return 0;
3453 }
3454
3455 spv::Id id;
3456 if (libCall >= 0) {
3457 std::vector<spv::Id> args;
3458 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003459 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003460 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003461 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003462 }
John Kessenich140f3df2015-06-26 16:58:36 -06003463
qining25262b32016-05-06 17:25:16 -04003464 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003465 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003466}
3467
John Kessenich7a53f762016-01-20 11:19:27 -07003468// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003469spv::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 -07003470{
3471 // Handle unary operations vector by vector.
3472 // The result type is the same type as the original type.
3473 // The algorithm is to:
3474 // - break the matrix into vectors
3475 // - apply the operation to each vector
3476 // - make a matrix out the vector results
3477
3478 // get the types sorted out
3479 int numCols = builder.getNumColumns(operand);
3480 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003481 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3482 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003483 std::vector<spv::Id> results;
3484
3485 // do each vector op
3486 for (int c = 0; c < numCols; ++c) {
3487 std::vector<unsigned int> indexes;
3488 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003489 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3490 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3491 addDecoration(destVec, noContraction);
3492 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003493 }
3494
3495 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003496 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003497}
3498
Rex Xu73e3ce72016-04-27 18:48:17 +08003499spv::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 -06003500{
3501 spv::Op convOp = spv::OpNop;
3502 spv::Id zero = 0;
3503 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003504 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003505
3506 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3507
3508 switch (op) {
3509 case glslang::EOpConvIntToBool:
3510 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003511 case glslang::EOpConvInt64ToBool:
3512 case glslang::EOpConvUint64ToBool:
3513 zero = (op == glslang::EOpConvInt64ToBool ||
3514 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003515 zero = makeSmearedConstant(zero, vectorSize);
3516 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3517
3518 case glslang::EOpConvFloatToBool:
3519 zero = builder.makeFloatConstant(0.0F);
3520 zero = makeSmearedConstant(zero, vectorSize);
3521 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3522
3523 case glslang::EOpConvDoubleToBool:
3524 zero = builder.makeDoubleConstant(0.0);
3525 zero = makeSmearedConstant(zero, vectorSize);
3526 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3527
3528 case glslang::EOpConvBoolToFloat:
3529 convOp = spv::OpSelect;
3530 zero = builder.makeFloatConstant(0.0);
3531 one = builder.makeFloatConstant(1.0);
3532 break;
3533 case glslang::EOpConvBoolToDouble:
3534 convOp = spv::OpSelect;
3535 zero = builder.makeDoubleConstant(0.0);
3536 one = builder.makeDoubleConstant(1.0);
3537 break;
3538 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003539 case glslang::EOpConvBoolToInt64:
3540 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3541 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003542 convOp = spv::OpSelect;
3543 break;
3544 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003545 case glslang::EOpConvBoolToUint64:
3546 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3547 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003548 convOp = spv::OpSelect;
3549 break;
3550
3551 case glslang::EOpConvIntToFloat:
3552 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003553 case glslang::EOpConvInt64ToFloat:
3554 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003555 convOp = spv::OpConvertSToF;
3556 break;
3557
3558 case glslang::EOpConvUintToFloat:
3559 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003560 case glslang::EOpConvUint64ToFloat:
3561 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003562 convOp = spv::OpConvertUToF;
3563 break;
3564
3565 case glslang::EOpConvDoubleToFloat:
3566 case glslang::EOpConvFloatToDouble:
3567 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003568 if (builder.isMatrixType(destType))
3569 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003570 break;
3571
3572 case glslang::EOpConvFloatToInt:
3573 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003574 case glslang::EOpConvFloatToInt64:
3575 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003576 convOp = spv::OpConvertFToS;
3577 break;
3578
3579 case glslang::EOpConvUintToInt:
3580 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003581 case glslang::EOpConvUint64ToInt64:
3582 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003583 if (builder.isInSpecConstCodeGenMode()) {
3584 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003585 zero = (op == glslang::EOpConvUintToInt64 ||
3586 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003587 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003588 // Use OpIAdd, instead of OpBitcast to do the conversion when
3589 // generating for OpSpecConstantOp instruction.
3590 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3591 }
3592 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003593 convOp = spv::OpBitcast;
3594 break;
3595
3596 case glslang::EOpConvFloatToUint:
3597 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003598 case glslang::EOpConvFloatToUint64:
3599 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003600 convOp = spv::OpConvertFToU;
3601 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003602
3603 case glslang::EOpConvIntToInt64:
3604 case glslang::EOpConvInt64ToInt:
3605 convOp = spv::OpSConvert;
3606 break;
3607
3608 case glslang::EOpConvUintToUint64:
3609 case glslang::EOpConvUint64ToUint:
3610 convOp = spv::OpUConvert;
3611 break;
3612
3613 case glslang::EOpConvIntToUint64:
3614 case glslang::EOpConvInt64ToUint:
3615 case glslang::EOpConvUint64ToInt:
3616 case glslang::EOpConvUintToInt64:
3617 // OpSConvert/OpUConvert + OpBitCast
3618 switch (op) {
3619 case glslang::EOpConvIntToUint64:
3620 convOp = spv::OpSConvert;
3621 type = builder.makeIntType(64);
3622 break;
3623 case glslang::EOpConvInt64ToUint:
3624 convOp = spv::OpSConvert;
3625 type = builder.makeIntType(32);
3626 break;
3627 case glslang::EOpConvUint64ToInt:
3628 convOp = spv::OpUConvert;
3629 type = builder.makeUintType(32);
3630 break;
3631 case glslang::EOpConvUintToInt64:
3632 convOp = spv::OpUConvert;
3633 type = builder.makeUintType(64);
3634 break;
3635 default:
3636 assert(0);
3637 break;
3638 }
3639
3640 if (vectorSize > 0)
3641 type = builder.makeVectorType(type, vectorSize);
3642
3643 operand = builder.createUnaryOp(convOp, type, operand);
3644
3645 if (builder.isInSpecConstCodeGenMode()) {
3646 // Build zero scalar or vector for OpIAdd.
3647 zero = (op == glslang::EOpConvIntToUint64 ||
3648 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3649 zero = makeSmearedConstant(zero, vectorSize);
3650 // Use OpIAdd, instead of OpBitcast to do the conversion when
3651 // generating for OpSpecConstantOp instruction.
3652 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3653 }
3654 // For normal run-time conversion instruction, use OpBitcast.
3655 convOp = spv::OpBitcast;
3656 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003657 default:
3658 break;
3659 }
3660
3661 spv::Id result = 0;
3662 if (convOp == spv::OpNop)
3663 return result;
3664
3665 if (convOp == spv::OpSelect) {
3666 zero = makeSmearedConstant(zero, vectorSize);
3667 one = makeSmearedConstant(one, vectorSize);
3668 result = builder.createTriOp(convOp, destType, operand, one, zero);
3669 } else
3670 result = builder.createUnaryOp(convOp, destType, operand);
3671
John Kessenich32cfd492016-02-02 12:37:46 -07003672 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003673}
3674
3675spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3676{
3677 if (vectorSize == 0)
3678 return constant;
3679
3680 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3681 std::vector<spv::Id> components;
3682 for (int c = 0; c < vectorSize; ++c)
3683 components.push_back(constant);
3684 return builder.makeCompositeConstant(vectorTypeId, components);
3685}
3686
John Kessenich426394d2015-07-23 10:22:48 -06003687// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003688spv::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 -06003689{
3690 spv::Op opCode = spv::OpNop;
3691
3692 switch (op) {
3693 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003694 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003695 opCode = spv::OpAtomicIAdd;
3696 break;
3697 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003698 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003699 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003700 break;
3701 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003702 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003703 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003704 break;
3705 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003706 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003707 opCode = spv::OpAtomicAnd;
3708 break;
3709 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003710 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003711 opCode = spv::OpAtomicOr;
3712 break;
3713 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003714 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003715 opCode = spv::OpAtomicXor;
3716 break;
3717 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003718 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003719 opCode = spv::OpAtomicExchange;
3720 break;
3721 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003722 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003723 opCode = spv::OpAtomicCompareExchange;
3724 break;
3725 case glslang::EOpAtomicCounterIncrement:
3726 opCode = spv::OpAtomicIIncrement;
3727 break;
3728 case glslang::EOpAtomicCounterDecrement:
3729 opCode = spv::OpAtomicIDecrement;
3730 break;
3731 case glslang::EOpAtomicCounter:
3732 opCode = spv::OpAtomicLoad;
3733 break;
3734 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003735 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003736 break;
3737 }
3738
3739 // Sort out the operands
3740 // - mapping from glslang -> SPV
3741 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003742 // - compare-exchange swaps the value and comparator
3743 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003744 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3745 auto opIt = operands.begin(); // walk the glslang operands
3746 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003747 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3748 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3749 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003750 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3751 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003752 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003753 spvAtomicOperands.push_back(*(opIt + 1));
3754 spvAtomicOperands.push_back(*opIt);
3755 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003756 }
John Kessenich426394d2015-07-23 10:22:48 -06003757
John Kessenich3e60a6f2015-09-14 22:45:16 -06003758 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003759 for (; opIt != operands.end(); ++opIt)
3760 spvAtomicOperands.push_back(*opIt);
3761
3762 return builder.createOp(opCode, typeId, spvAtomicOperands);
3763}
3764
John Kessenich91cef522016-05-05 16:45:40 -06003765// Create group invocation operations.
3766spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3767{
3768 builder.addCapability(spv::CapabilityGroups);
3769
3770 std::vector<spv::Id> operands;
3771 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3772 operands.push_back(operand);
3773
3774 switch (op) {
3775 case glslang::EOpAnyInvocation:
3776 case glslang::EOpAllInvocations:
3777 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3778
3779 case glslang::EOpAllInvocationsEqual:
3780 {
3781 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3782 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3783
3784 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3785 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3786 }
3787 default:
3788 logger->missingFunctionality("invocation operation");
3789 return spv::NoResult;
3790 }
3791}
3792
John Kessenich5e4b1242015-08-06 22:53:06 -06003793spv::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 -06003794{
Rex Xu8ff43de2016-04-22 16:51:45 +08003795 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003796 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3797
John Kessenich140f3df2015-06-26 16:58:36 -06003798 spv::Op opCode = spv::OpNop;
3799 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003800 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003801 spv::Id typeId0 = 0;
3802 if (consumedOperands > 0)
3803 typeId0 = builder.getTypeId(operands[0]);
3804 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003805
3806 switch (op) {
3807 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003808 if (isFloat)
3809 libCall = spv::GLSLstd450FMin;
3810 else if (isUnsigned)
3811 libCall = spv::GLSLstd450UMin;
3812 else
3813 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003814 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003815 break;
3816 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003818 break;
3819 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003820 if (isFloat)
3821 libCall = spv::GLSLstd450FMax;
3822 else if (isUnsigned)
3823 libCall = spv::GLSLstd450UMax;
3824 else
3825 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003826 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
3828 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003829 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003830 break;
3831 case glslang::EOpDot:
3832 opCode = spv::OpDot;
3833 break;
3834 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003835 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837
3838 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003839 if (isFloat)
3840 libCall = spv::GLSLstd450FClamp;
3841 else if (isUnsigned)
3842 libCall = spv::GLSLstd450UClamp;
3843 else
3844 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003845 builder.promoteScalar(precision, operands.front(), operands[1]);
3846 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003847 break;
3848 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003849 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3850 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003851 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003852 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003853 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003854 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003855 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003856 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003857 break;
3858 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003859 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003860 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003861 break;
3862 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003863 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003864 builder.promoteScalar(precision, operands[0], operands[2]);
3865 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003866 break;
3867
3868 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003869 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003870 break;
3871 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003872 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003873 break;
3874 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003875 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003876 break;
3877 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003878 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003879 break;
3880 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003881 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003882 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003883 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003884 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003885 libCall = spv::GLSLstd450InterpolateAtSample;
3886 break;
3887 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003888 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003889 libCall = spv::GLSLstd450InterpolateAtOffset;
3890 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003891 case glslang::EOpAddCarry:
3892 opCode = spv::OpIAddCarry;
3893 typeId = builder.makeStructResultType(typeId0, typeId0);
3894 consumedOperands = 2;
3895 break;
3896 case glslang::EOpSubBorrow:
3897 opCode = spv::OpISubBorrow;
3898 typeId = builder.makeStructResultType(typeId0, typeId0);
3899 consumedOperands = 2;
3900 break;
3901 case glslang::EOpUMulExtended:
3902 opCode = spv::OpUMulExtended;
3903 typeId = builder.makeStructResultType(typeId0, typeId0);
3904 consumedOperands = 2;
3905 break;
3906 case glslang::EOpIMulExtended:
3907 opCode = spv::OpSMulExtended;
3908 typeId = builder.makeStructResultType(typeId0, typeId0);
3909 consumedOperands = 2;
3910 break;
3911 case glslang::EOpBitfieldExtract:
3912 if (isUnsigned)
3913 opCode = spv::OpBitFieldUExtract;
3914 else
3915 opCode = spv::OpBitFieldSExtract;
3916 break;
3917 case glslang::EOpBitfieldInsert:
3918 opCode = spv::OpBitFieldInsert;
3919 break;
3920
3921 case glslang::EOpFma:
3922 libCall = spv::GLSLstd450Fma;
3923 break;
3924 case glslang::EOpFrexp:
3925 libCall = spv::GLSLstd450FrexpStruct;
3926 if (builder.getNumComponents(operands[0]) == 1)
3927 frexpIntType = builder.makeIntegerType(32, true);
3928 else
3929 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3930 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3931 consumedOperands = 1;
3932 break;
3933 case glslang::EOpLdexp:
3934 libCall = spv::GLSLstd450Ldexp;
3935 break;
3936
Rex Xu574ab042016-04-14 16:53:07 +08003937 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003938 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003939 libCall = spv::GLSLstd450Bad;
3940 break;
3941
John Kessenich140f3df2015-06-26 16:58:36 -06003942 default:
3943 return 0;
3944 }
3945
3946 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003947 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003948 // Use an extended instruction from the standard library.
3949 // Construct the call arguments, without modifying the original operands vector.
3950 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3951 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003952 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003953 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003954 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003955 case 0:
3956 // should all be handled by visitAggregate and createNoArgOperation
3957 assert(0);
3958 return 0;
3959 case 1:
3960 // should all be handled by createUnaryOperation
3961 assert(0);
3962 return 0;
3963 case 2:
3964 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3965 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003966 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003967 // anything 3 or over doesn't have l-value operands, so all should be consumed
3968 assert(consumedOperands == operands.size());
3969 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003970 break;
3971 }
3972 }
3973
John Kessenich55e7d112015-11-15 21:33:39 -07003974 // Decode the return types that were structures
3975 switch (op) {
3976 case glslang::EOpAddCarry:
3977 case glslang::EOpSubBorrow:
3978 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3979 id = builder.createCompositeExtract(id, typeId0, 0);
3980 break;
3981 case glslang::EOpUMulExtended:
3982 case glslang::EOpIMulExtended:
3983 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3984 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3985 break;
3986 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003987 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003988 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3989 id = builder.createCompositeExtract(id, typeId0, 0);
3990 break;
3991 default:
3992 break;
3993 }
3994
John Kessenich32cfd492016-02-02 12:37:46 -07003995 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003996}
3997
3998// Intrinsics with no arguments, no return value, and no precision.
3999spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
4000{
4001 // TODO: get the barrier operands correct
4002
4003 switch (op) {
4004 case glslang::EOpEmitVertex:
4005 builder.createNoResultOp(spv::OpEmitVertex);
4006 return 0;
4007 case glslang::EOpEndPrimitive:
4008 builder.createNoResultOp(spv::OpEndPrimitive);
4009 return 0;
4010 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004012 return 0;
4013 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004015 return 0;
4016 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004017 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004018 return 0;
4019 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004020 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004021 return 0;
4022 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004023 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004024 return 0;
4025 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004026 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004027 return 0;
4028 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004029 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004030 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004031 case glslang::EOpAllMemoryBarrierWithGroupSync:
4032 // Control barrier with non-"None" semantic is also a memory barrier.
4033 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4034 return 0;
4035 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4036 // Control barrier with non-"None" semantic is also a memory barrier.
4037 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4038 return 0;
4039 case glslang::EOpWorkgroupMemoryBarrier:
4040 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4041 return 0;
4042 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4043 // Control barrier with non-"None" semantic is also a memory barrier.
4044 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4045 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004046 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004047 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004048 return 0;
4049 }
4050}
4051
4052spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4053{
John Kessenich2f273362015-07-18 22:34:27 -06004054 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004055 spv::Id id;
4056 if (symbolValues.end() != iter) {
4057 id = iter->second;
4058 return id;
4059 }
4060
4061 // it was not found, create it
4062 id = createSpvVariable(symbol);
4063 symbolValues[symbol->getId()] = id;
4064
Rex Xuc884b4a2016-06-29 15:03:44 +08004065 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004066 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004067 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004068 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004069 if (symbol->getType().getQualifier().hasSpecConstantId())
4070 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004071 if (symbol->getQualifier().hasIndex())
4072 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4073 if (symbol->getQualifier().hasComponent())
4074 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4075 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004076 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004077 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004079 if (symbol->getQualifier().hasXfbBuffer())
4080 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4081 if (symbol->getQualifier().hasXfbOffset())
4082 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4083 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004084 // atomic counters use this:
4085 if (symbol->getQualifier().hasOffset())
4086 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004087 }
4088
scygan2c864272016-05-18 18:09:17 +02004089 if (symbol->getQualifier().hasLocation())
4090 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004091 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004092 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004093 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004094 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004095 }
John Kessenich140f3df2015-06-26 16:58:36 -06004096 if (symbol->getQualifier().hasSet())
4097 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004098 else if (IsDescriptorResource(symbol->getType())) {
4099 // default to 0
4100 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4101 }
John Kessenich140f3df2015-06-26 16:58:36 -06004102 if (symbol->getQualifier().hasBinding())
4103 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004104 if (symbol->getQualifier().hasAttachment())
4105 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004106 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004107 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004108 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004109 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004110 if (symbol->getQualifier().hasXfbBuffer())
4111 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4112 }
4113
Rex Xu1da878f2016-02-21 20:59:01 +08004114 if (symbol->getType().isImage()) {
4115 std::vector<spv::Decoration> memory;
4116 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4117 for (unsigned int i = 0; i < memory.size(); ++i)
4118 addDecoration(id, memory[i]);
4119 }
4120
John Kessenich140f3df2015-06-26 16:58:36 -06004121 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004122 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07004124 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004125
John Kessenich140f3df2015-06-26 16:58:36 -06004126 return id;
4127}
4128
John Kessenich55e7d112015-11-15 21:33:39 -07004129// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004130void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4131{
4132 if (dec != spv::BadValue)
4133 builder.addDecoration(id, dec);
4134}
4135
John Kessenich55e7d112015-11-15 21:33:39 -07004136// If 'dec' is valid, add a one-operand decoration to an object
4137void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4138{
4139 if (dec != spv::BadValue)
4140 builder.addDecoration(id, dec, value);
4141}
4142
4143// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004144void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4145{
4146 if (dec != spv::BadValue)
4147 builder.addMemberDecoration(id, (unsigned)member, dec);
4148}
4149
John Kessenich92187592016-02-01 13:45:25 -07004150// If 'dec' is valid, add a one-operand decoration to a struct member
4151void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4152{
4153 if (dec != spv::BadValue)
4154 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4155}
4156
John Kessenich55e7d112015-11-15 21:33:39 -07004157// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004158// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004159//
4160// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4161//
4162// Recursively walk the nodes. The nodes form a tree whose leaves are
4163// regular constants, which themselves are trees that createSpvConstant()
4164// recursively walks. So, this function walks the "top" of the tree:
4165// - emit specialization constant-building instructions for specConstant
4166// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004167spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004168{
John Kessenich7cc0e282016-03-20 00:46:02 -06004169 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004170
qining4f4bb812016-04-03 23:55:17 -04004171 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004172 if (! node.getQualifier().specConstant) {
4173 // hand off to the non-spec-constant path
4174 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4175 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004176 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004177 nextConst, false);
4178 }
4179
4180 // We now know we have a specialization constant to build
4181
John Kessenichd94c0032016-05-30 19:29:40 -06004182 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004183 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4184 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4185 std::vector<spv::Id> dimConstId;
4186 for (int dim = 0; dim < 3; ++dim) {
4187 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4188 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4189 if (specConst)
4190 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4191 }
4192 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4193 }
4194
4195 // An AST node labelled as specialization constant should be a symbol node.
4196 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4197 if (auto* sn = node.getAsSymbolNode()) {
4198 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004199 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4200 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4201 // will set the builder into spec constant op instruction generating mode.
4202 sub_tree->traverse(this);
4203 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004204 } else if (auto* const_union_array = &sn->getConstArray()){
4205 int nextConst = 0;
4206 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004207 }
4208 }
qining4f4bb812016-04-03 23:55:17 -04004209
4210 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4211 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004212 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004213 exit(1);
4214 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004215}
4216
John Kessenich140f3df2015-06-26 16:58:36 -06004217// Use 'consts' as the flattened glslang source of scalar constants to recursively
4218// build the aggregate SPIR-V constant.
4219//
4220// If there are not enough elements present in 'consts', 0 will be substituted;
4221// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4222//
qining08408382016-03-21 09:51:37 -04004223spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004224{
4225 // vector of constants for SPIR-V
4226 std::vector<spv::Id> spvConsts;
4227
4228 // Type is used for struct and array constants
4229 spv::Id typeId = convertGlslangToSpvType(glslangType);
4230
4231 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004232 glslang::TType elementType(glslangType, 0);
4233 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004234 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004235 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004236 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004237 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004238 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004239 } else if (glslangType.getStruct()) {
4240 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4241 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004242 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004243 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004244 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4245 bool zero = nextConst >= consts.size();
4246 switch (glslangType.getBasicType()) {
4247 case glslang::EbtInt:
4248 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4249 break;
4250 case glslang::EbtUint:
4251 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4252 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004253 case glslang::EbtInt64:
4254 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4255 break;
4256 case glslang::EbtUint64:
4257 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004259 case glslang::EbtFloat:
4260 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4261 break;
4262 case glslang::EbtDouble:
4263 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4264 break;
4265 case glslang::EbtBool:
4266 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4267 break;
4268 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004269 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004270 break;
4271 }
4272 ++nextConst;
4273 }
4274 } else {
4275 // we have a non-aggregate (scalar) constant
4276 bool zero = nextConst >= consts.size();
4277 spv::Id scalar = 0;
4278 switch (glslangType.getBasicType()) {
4279 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004280 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004281 break;
4282 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004283 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004284 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004285 case glslang::EbtInt64:
4286 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4287 break;
4288 case glslang::EbtUint64:
4289 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4290 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004291 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004292 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004293 break;
4294 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004295 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004296 break;
4297 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004298 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004299 break;
4300 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004301 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004302 break;
4303 }
4304 ++nextConst;
4305 return scalar;
4306 }
4307
4308 return builder.makeCompositeConstant(typeId, spvConsts);
4309}
4310
John Kessenich7c1aa102015-10-15 13:29:11 -06004311// Return true if the node is a constant or symbol whose reading has no
4312// non-trivial observable cost or effect.
4313bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4314{
4315 // don't know what this is
4316 if (node == nullptr)
4317 return false;
4318
4319 // a constant is safe
4320 if (node->getAsConstantUnion() != nullptr)
4321 return true;
4322
4323 // not a symbol means non-trivial
4324 if (node->getAsSymbolNode() == nullptr)
4325 return false;
4326
4327 // a symbol, depends on what's being read
4328 switch (node->getType().getQualifier().storage) {
4329 case glslang::EvqTemporary:
4330 case glslang::EvqGlobal:
4331 case glslang::EvqIn:
4332 case glslang::EvqInOut:
4333 case glslang::EvqConst:
4334 case glslang::EvqConstReadOnly:
4335 case glslang::EvqUniform:
4336 return true;
4337 default:
4338 return false;
4339 }
qining25262b32016-05-06 17:25:16 -04004340}
John Kessenich7c1aa102015-10-15 13:29:11 -06004341
4342// A node is trivial if it is a single operation with no side effects.
4343// Error on the side of saying non-trivial.
4344// Return true if trivial.
4345bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4346{
4347 if (node == nullptr)
4348 return false;
4349
4350 // symbols and constants are trivial
4351 if (isTrivialLeaf(node))
4352 return true;
4353
4354 // otherwise, it needs to be a simple operation or one or two leaf nodes
4355
4356 // not a simple operation
4357 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4358 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4359 if (binaryNode == nullptr && unaryNode == nullptr)
4360 return false;
4361
4362 // not on leaf nodes
4363 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4364 return false;
4365
4366 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4367 return false;
4368 }
4369
4370 switch (node->getAsOperator()->getOp()) {
4371 case glslang::EOpLogicalNot:
4372 case glslang::EOpConvIntToBool:
4373 case glslang::EOpConvUintToBool:
4374 case glslang::EOpConvFloatToBool:
4375 case glslang::EOpConvDoubleToBool:
4376 case glslang::EOpEqual:
4377 case glslang::EOpNotEqual:
4378 case glslang::EOpLessThan:
4379 case glslang::EOpGreaterThan:
4380 case glslang::EOpLessThanEqual:
4381 case glslang::EOpGreaterThanEqual:
4382 case glslang::EOpIndexDirect:
4383 case glslang::EOpIndexDirectStruct:
4384 case glslang::EOpLogicalXor:
4385 case glslang::EOpAny:
4386 case glslang::EOpAll:
4387 return true;
4388 default:
4389 return false;
4390 }
4391}
4392
4393// Emit short-circuiting code, where 'right' is never evaluated unless
4394// the left side is true (for &&) or false (for ||).
4395spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4396{
4397 spv::Id boolTypeId = builder.makeBoolType();
4398
4399 // emit left operand
4400 builder.clearAccessChain();
4401 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004402 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004403
4404 // Operands to accumulate OpPhi operands
4405 std::vector<spv::Id> phiOperands;
4406 // accumulate left operand's phi information
4407 phiOperands.push_back(leftId);
4408 phiOperands.push_back(builder.getBuildPoint()->getId());
4409
4410 // Make the two kinds of operation symmetric with a "!"
4411 // || => emit "if (! left) result = right"
4412 // && => emit "if ( left) result = right"
4413 //
4414 // TODO: this runtime "not" for || could be avoided by adding functionality
4415 // to 'builder' to have an "else" without an "then"
4416 if (op == glslang::EOpLogicalOr)
4417 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4418
4419 // make an "if" based on the left value
4420 spv::Builder::If ifBuilder(leftId, builder);
4421
4422 // emit right operand as the "then" part of the "if"
4423 builder.clearAccessChain();
4424 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004425 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004426
4427 // accumulate left operand's phi information
4428 phiOperands.push_back(rightId);
4429 phiOperands.push_back(builder.getBuildPoint()->getId());
4430
4431 // finish the "if"
4432 ifBuilder.makeEndIf();
4433
4434 // phi together the two results
4435 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4436}
4437
John Kessenich140f3df2015-06-26 16:58:36 -06004438}; // end anonymous namespace
4439
4440namespace glslang {
4441
John Kessenich68d78fd2015-07-12 19:28:10 -06004442void GetSpirvVersion(std::string& version)
4443{
John Kessenich9e55f632015-07-15 10:03:39 -06004444 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004445 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004446 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004447 version = buf;
4448}
4449
John Kessenich140f3df2015-06-26 16:58:36 -06004450// Write SPIR-V out to a binary file
4451void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4452{
4453 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004454 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004455 for (int i = 0; i < (int)spirv.size(); ++i) {
4456 unsigned int word = spirv[i];
4457 out.write((const char*)&word, 4);
4458 }
4459 out.close();
4460}
4461
4462//
4463// Set up the glslang traversal
4464//
4465void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4466{
Lei Zhang17535f72016-05-04 15:55:59 -04004467 spv::SpvBuildLogger logger;
4468 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004469}
4470
Lei Zhang17535f72016-05-04 15:55:59 -04004471void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004472{
John Kessenich140f3df2015-06-26 16:58:36 -06004473 TIntermNode* root = intermediate.getTreeRoot();
4474
4475 if (root == 0)
4476 return;
4477
4478 glslang::GetThreadPoolAllocator().push();
4479
Lei Zhang17535f72016-05-04 15:55:59 -04004480 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004481
4482 root->traverse(&it);
4483
4484 it.dumpSpv(spirv);
4485
4486 glslang::GetThreadPoolAllocator().pop();
4487}
4488
4489}; // end namespace glslang