blob: 39b4ea6e3ebdfdb5e3f7cdfdc6891026fc108e12 [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 Kessenich6c292d32016-02-15 20:58:50 -0700118 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700119 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800120 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700121 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700122 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
123 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
124 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 +0100125 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
128 void makeFunctions(const glslang::TIntermSequence&);
129 void makeGlobalInitializers(const glslang::TIntermSequence&);
130 void visitFunctions(const glslang::TIntermSequence&);
131 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800132 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600133 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
134 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600135 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
136
qining25262b32016-05-06 17:25:16 -0400137 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);
138 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
139 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
140 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 +0800141 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 -0600142 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800143 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 -0600144 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 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 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600154 bool isTrivialLeaf(const glslang::TIntermTyped* node);
155 bool isTrivial(const glslang::TIntermTyped* node);
156 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
158 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700159 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600160 int sequenceDepth;
161
Lei Zhang17535f72016-05-04 15:55:59 -0400162 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400163
John Kessenich140f3df2015-06-26 16:58:36 -0600164 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
165 spv::Builder builder;
166 bool inMain;
167 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700168 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 -0700169 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600170 const glslang::TIntermediate* glslangIntermediate;
171 spv::Id stdBuiltins;
172
John Kessenich2f273362015-07-18 22:34:27 -0600173 std::unordered_map<int, spv::Id> symbolValues;
174 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
175 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700176 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600177 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 -0600178 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600179};
180
181//
182// Helper functions for translating glslang representations to SPIR-V enumerants.
183//
184
185// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700186spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600187{
John Kessenich66e2faf2016-03-12 18:34:36 -0700188 switch (source) {
189 case glslang::EShSourceGlsl:
190 switch (profile) {
191 case ENoProfile:
192 case ECoreProfile:
193 case ECompatibilityProfile:
194 return spv::SourceLanguageGLSL;
195 case EEsProfile:
196 return spv::SourceLanguageESSL;
197 default:
198 return spv::SourceLanguageUnknown;
199 }
200 case glslang::EShSourceHlsl:
201 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 default:
203 return spv::SourceLanguageUnknown;
204 }
205}
206
207// Translate glslang language (stage) to SPIR-V execution model.
208spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
209{
210 switch (stage) {
211 case EShLangVertex: return spv::ExecutionModelVertex;
212 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
213 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
214 case EShLangGeometry: return spv::ExecutionModelGeometry;
215 case EShLangFragment: return spv::ExecutionModelFragment;
216 case EShLangCompute: return spv::ExecutionModelGLCompute;
217 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600219 return spv::ExecutionModelFragment;
220 }
221}
222
223// Translate glslang type to SPIR-V storage class.
224spv::StorageClass TranslateStorageClass(const glslang::TType& type)
225{
226 if (type.getQualifier().isPipeInput())
227 return spv::StorageClassInput;
228 else if (type.getQualifier().isPipeOutput())
229 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700230 else if (type.getBasicType() == glslang::EbtSampler)
231 return spv::StorageClassUniformConstant;
232 else if (type.getBasicType() == glslang::EbtAtomicUint)
233 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700235 if (type.getQualifier().layoutPushConstant)
236 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 if (type.getBasicType() == glslang::EbtBlock)
238 return spv::StorageClassUniform;
239 else
240 return spv::StorageClassUniformConstant;
241 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
242 } else {
243 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700244 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
245 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
247 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400248 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700249 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600250 return spv::StorageClassFunction;
251 }
252 }
253}
254
255// Translate glslang sampler type to SPIR-V dimensionality.
256spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
257{
258 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700259 case glslang::Esd1D: return spv::Dim1D;
260 case glslang::Esd2D: return spv::Dim2D;
261 case glslang::Esd3D: return spv::Dim3D;
262 case glslang::EsdCube: return spv::DimCube;
263 case glslang::EsdRect: return spv::DimRect;
264 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700265 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600268 return spv::Dim2D;
269 }
270}
271
272// Translate glslang type to SPIR-V precision decorations.
273spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
274{
275 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700276 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600277 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 default:
279 return spv::NoPrecision;
280 }
281}
282
283// Translate glslang type to SPIR-V block decorations.
284spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
289 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
298 return (spv::Decoration)spv::BadValue;
299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
327 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
332 return (spv::Decoration)spv::BadValue;
333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600342 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600347 return (spv::Decoration)spv::BadValue;
348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600350 return (spv::Decoration)spv::BadValue;
351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700357// Returns spv::Decoration(spv::BadValue) when no decoration
358// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800359spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
Rex Xubbceed72016-05-21 09:40:44 +0800361 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
363 return (spv::Decoration)spv::BadValue;
Rex Xubbceed72016-05-21 09:40:44 +0800364 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800368 else
369 return (spv::Decoration)spv::BadValue;
370}
371
372// Translate glslang type to SPIR-V auxiliary storage decorations.
373// Returns spv::Decoration(spv::BadValue) when no decoration
374// should be applied.
375spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
376{
377 if (qualifier.patch)
378 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700381 else if (qualifier.sample) {
382 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700384 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600385 return (spv::Decoration)spv::BadValue;
386}
387
John Kessenich92187592016-02-01 13:45:25 -0700388// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700389spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700391 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600392 return spv::DecorationInvariant;
393 else
394 return (spv::Decoration)spv::BadValue;
395}
396
qining9220dbb2016-05-04 17:34:38 -0400397// If glslang type is noContraction, return SPIR-V NoContraction decoration.
398spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
399{
400 if (qualifier.noContraction)
401 return spv::DecorationNoContraction;
402 else
403 return (spv::Decoration)spv::BadValue;
404}
405
David Netoa901ffe2016-06-08 14:11:40 +0100406// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
407// associated capabilities when required. For some built-in variables, a capability
408// is generated only when using the variable in an executable instruction, but not when
409// just declaring a struct member variable with it. This is true for PointSize,
410// ClipDistance, and CullDistance.
411spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600412{
413 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700414 case glslang::EbvPointSize:
David Netoa901ffe2016-06-08 14:11:40 +0100415 // Defer adding the capability until the built-in is actually used.
416 if (!memberDeclaration) {
417 switch (glslangIntermediate->getStage()) {
418 case EShLangGeometry:
419 builder.addCapability(spv::CapabilityGeometryPointSize);
420 break;
421 case EShLangTessControl:
422 case EShLangTessEvaluation:
423 builder.addCapability(spv::CapabilityTessellationPointSize);
424 break;
425 default:
426 break;
427 }
John Kessenich92187592016-02-01 13:45:25 -0700428 }
429 return spv::BuiltInPointSize;
430
John Kessenichebb50532016-05-16 19:22:05 -0600431 // These *Distance capabilities logically belong here, but if the member is declared and
432 // then never used, consumers of SPIR-V prefer the capability not be declared.
433 // They are now generated when used, rather than here when declared.
434 // Potentially, the specification should be more clear what the minimum
435 // use needed is to trigger the capability.
436 //
John Kessenich92187592016-02-01 13:45:25 -0700437 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100438 if (!memberDeclaration)
439 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700440 return spv::BuiltInClipDistance;
441
442 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100443 if (!memberDeclaration)
444 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700445 return spv::BuiltInCullDistance;
446
447 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500448 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700449 return spv::BuiltInViewportIndex;
450
John Kessenich5e801132016-02-15 11:09:46 -0700451 case glslang::EbvSampleId:
452 builder.addCapability(spv::CapabilitySampleRateShading);
453 return spv::BuiltInSampleId;
454
455 case glslang::EbvSamplePosition:
456 builder.addCapability(spv::CapabilitySampleRateShading);
457 return spv::BuiltInSamplePosition;
458
459 case glslang::EbvSampleMask:
460 builder.addCapability(spv::CapabilitySampleRateShading);
461 return spv::BuiltInSampleMask;
462
John Kessenich140f3df2015-06-26 16:58:36 -0600463 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600464 case glslang::EbvVertexId: return spv::BuiltInVertexId;
465 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700466 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
467 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600468 case glslang::EbvBaseVertex:
469 case glslang::EbvBaseInstance:
470 case glslang::EbvDrawId:
471 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600472 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600473 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600474 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
475 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
476 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600477 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
478 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
479 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
480 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
481 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
482 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
483 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600484 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
485 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
486 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
487 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
488 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
489 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
490 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
491 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800492 case glslang::EbvSubGroupSize:
493 case glslang::EbvSubGroupInvocation:
494 case glslang::EbvSubGroupEqMask:
495 case glslang::EbvSubGroupGeMask:
496 case glslang::EbvSubGroupGtMask:
497 case glslang::EbvSubGroupLeMask:
498 case glslang::EbvSubGroupLtMask:
499 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600500 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800501 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600502 default: return (spv::BuiltIn)spv::BadValue;
503 }
504}
505
Rex Xufc618912015-09-09 16:42:49 +0800506// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700507spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800508{
509 assert(type.getBasicType() == glslang::EbtSampler);
510
John Kessenich5d0fa972016-02-15 11:57:00 -0700511 // Check for capabilities
512 switch (type.getQualifier().layoutFormat) {
513 case glslang::ElfRg32f:
514 case glslang::ElfRg16f:
515 case glslang::ElfR11fG11fB10f:
516 case glslang::ElfR16f:
517 case glslang::ElfRgba16:
518 case glslang::ElfRgb10A2:
519 case glslang::ElfRg16:
520 case glslang::ElfRg8:
521 case glslang::ElfR16:
522 case glslang::ElfR8:
523 case glslang::ElfRgba16Snorm:
524 case glslang::ElfRg16Snorm:
525 case glslang::ElfRg8Snorm:
526 case glslang::ElfR16Snorm:
527 case glslang::ElfR8Snorm:
528
529 case glslang::ElfRg32i:
530 case glslang::ElfRg16i:
531 case glslang::ElfRg8i:
532 case glslang::ElfR16i:
533 case glslang::ElfR8i:
534
535 case glslang::ElfRgb10a2ui:
536 case glslang::ElfRg32ui:
537 case glslang::ElfRg16ui:
538 case glslang::ElfRg8ui:
539 case glslang::ElfR16ui:
540 case glslang::ElfR8ui:
541 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
542 break;
543
544 default:
545 break;
546 }
547
548 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800549 switch (type.getQualifier().layoutFormat) {
550 case glslang::ElfNone: return spv::ImageFormatUnknown;
551 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
552 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
553 case glslang::ElfR32f: return spv::ImageFormatR32f;
554 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
555 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
556 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
557 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
558 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
559 case glslang::ElfR16f: return spv::ImageFormatR16f;
560 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
561 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
562 case glslang::ElfRg16: return spv::ImageFormatRg16;
563 case glslang::ElfRg8: return spv::ImageFormatRg8;
564 case glslang::ElfR16: return spv::ImageFormatR16;
565 case glslang::ElfR8: return spv::ImageFormatR8;
566 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
567 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
568 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
569 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
570 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
571 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
572 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
573 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
574 case glslang::ElfR32i: return spv::ImageFormatR32i;
575 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
576 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
577 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
578 case glslang::ElfR16i: return spv::ImageFormatR16i;
579 case glslang::ElfR8i: return spv::ImageFormatR8i;
580 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
581 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
582 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
583 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
584 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
585 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
586 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
587 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
588 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
589 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
590 default: return (spv::ImageFormat)spv::BadValue;
591 }
592}
593
qining25262b32016-05-06 17:25:16 -0400594// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700595// descriptor set.
596bool IsDescriptorResource(const glslang::TType& type)
597{
John Kessenichf7497e22016-03-08 21:36:22 -0700598 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700599 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700600 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700601
602 // non block...
603 // basically samplerXXX/subpass/sampler/texture are all included
604 // if they are the global-scope-class, not the function parameter
605 // (or local, if they ever exist) class.
606 if (type.getBasicType() == glslang::EbtSampler)
607 return type.getQualifier().isUniformOrBuffer();
608
609 // None of the above.
610 return false;
611}
612
John Kesseniche0b6cad2015-12-24 10:30:13 -0700613void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
614{
615 if (child.layoutMatrix == glslang::ElmNone)
616 child.layoutMatrix = parent.layoutMatrix;
617
618 if (parent.invariant)
619 child.invariant = true;
620 if (parent.nopersp)
621 child.nopersp = true;
622 if (parent.flat)
623 child.flat = true;
624 if (parent.centroid)
625 child.centroid = true;
626 if (parent.patch)
627 child.patch = true;
628 if (parent.sample)
629 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800630 if (parent.coherent)
631 child.coherent = true;
632 if (parent.volatil)
633 child.volatil = true;
634 if (parent.restrict)
635 child.restrict = true;
636 if (parent.readonly)
637 child.readonly = true;
638 if (parent.writeonly)
639 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700640}
641
642bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
643{
John Kessenich7b9fa252016-01-21 18:56:57 -0700644 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700645 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600646 // - 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 -0700647 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600648 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700649}
650
John Kessenich140f3df2015-06-26 16:58:36 -0600651//
652// Implement the TGlslangToSpvTraverser class.
653//
654
Lei Zhang17535f72016-05-04 15:55:59 -0400655TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
656 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
657 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600658 inMain(false), mainTerminated(false), linkageOnly(false),
659 glslangIntermediate(glslangIntermediate)
660{
661 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
662
663 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700664 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600665 stdBuiltins = builder.import("GLSL.std.450");
666 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700667 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
668 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600669
670 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600671 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
672 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600673 builder.addSourceExtension(it->c_str());
674
675 // Add the top-level modes for this shader.
676
John Kessenich92187592016-02-01 13:45:25 -0700677 if (glslangIntermediate->getXfbMode()) {
678 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600679 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700680 }
John Kessenich140f3df2015-06-26 16:58:36 -0600681
682 unsigned int mode;
683 switch (glslangIntermediate->getStage()) {
684 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600685 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600686 break;
687
688 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600689 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600690 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
691 break;
692
693 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600694 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600695 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700696 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
697 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
698 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600699 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600700 }
701 if (mode != spv::BadValue)
702 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
703
John Kesseniche6903322015-10-13 16:29:02 -0600704 switch (glslangIntermediate->getVertexSpacing()) {
705 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
706 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
707 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
708 default: mode = spv::BadValue; break;
709 }
710 if (mode != spv::BadValue)
711 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
712
713 switch (glslangIntermediate->getVertexOrder()) {
714 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
715 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
716 default: mode = spv::BadValue; break;
717 }
718 if (mode != spv::BadValue)
719 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
720
721 if (glslangIntermediate->getPointMode())
722 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600723 break;
724
725 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600726 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 switch (glslangIntermediate->getInputPrimitive()) {
728 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
729 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
730 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700731 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600732 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
733 default: mode = spv::BadValue; break;
734 }
735 if (mode != spv::BadValue)
736 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600737
John Kessenich140f3df2015-06-26 16:58:36 -0600738 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
739
740 switch (glslangIntermediate->getOutputPrimitive()) {
741 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
742 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
743 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
744 default: mode = spv::BadValue; break;
745 }
746 if (mode != spv::BadValue)
747 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
748 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
749 break;
750
751 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600752 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600753 if (glslangIntermediate->getPixelCenterInteger())
754 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600755
John Kessenich140f3df2015-06-26 16:58:36 -0600756 if (glslangIntermediate->getOriginUpperLeft())
757 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600758 else
759 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600760
761 if (glslangIntermediate->getEarlyFragmentTests())
762 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
763
764 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600765 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
766 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
767 default: mode = spv::BadValue; break;
768 }
769 if (mode != spv::BadValue)
770 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
771
772 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
773 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600774 break;
775
776 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600777 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600778 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
779 glslangIntermediate->getLocalSize(1),
780 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600781 break;
782
783 default:
784 break;
785 }
786
787}
788
John Kessenich7ba63412015-12-20 17:37:07 -0700789// Finish everything and dump
790void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
791{
792 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100793 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
794 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700795
qiningda397332016-03-09 19:54:03 -0500796 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700797 builder.dump(out);
798}
799
John Kessenich140f3df2015-06-26 16:58:36 -0600800TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
801{
802 if (! mainTerminated) {
803 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
804 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600805 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600806 }
807}
808
809//
810// Implement the traversal functions.
811//
812// Return true from interior nodes to have the external traversal
813// continue on to children. Return false if children were
814// already processed.
815//
816
817//
qining25262b32016-05-06 17:25:16 -0400818// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600819// - uniform/input reads
820// - output writes
821// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
822// - something simple that degenerates into the last bullet
823//
824void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
825{
qining75d1d802016-04-06 14:42:01 -0400826 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
827 if (symbol->getType().getQualifier().isSpecConstant())
828 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
829
John Kessenich140f3df2015-06-26 16:58:36 -0600830 // getSymbolId() will set up all the IO decorations on the first call.
831 // Formal function parameters were mapped during makeFunctions().
832 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700833
834 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
835 if (builder.isPointer(id)) {
836 spv::StorageClass sc = builder.getStorageClass(id);
837 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
838 iOSet.insert(id);
839 }
840
841 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700842 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600843 // Prepare to generate code for the access
844
845 // L-value chains will be computed left to right. We're on the symbol now,
846 // which is the left-most part of the access chain, so now is "clear" time,
847 // followed by setting the base.
848 builder.clearAccessChain();
849
850 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700851 // except for
852 // A) "const in" arguments to a function, which are an intermediate object.
853 // See comments in handleUserFunctionCall().
854 // B) Specialization constants (normal constant don't even come in as a variable),
855 // These are also pure R-values.
856 glslang::TQualifier qualifier = symbol->getQualifier();
857 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
858 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600859 builder.setAccessChainRValue(id);
860 else
861 builder.setAccessChainLValue(id);
862 }
863}
864
865bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
866{
qining40887662016-04-03 22:20:42 -0400867 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
868 if (node->getType().getQualifier().isSpecConstant())
869 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
870
John Kessenich140f3df2015-06-26 16:58:36 -0600871 // First, handle special cases
872 switch (node->getOp()) {
873 case glslang::EOpAssign:
874 case glslang::EOpAddAssign:
875 case glslang::EOpSubAssign:
876 case glslang::EOpMulAssign:
877 case glslang::EOpVectorTimesMatrixAssign:
878 case glslang::EOpVectorTimesScalarAssign:
879 case glslang::EOpMatrixTimesScalarAssign:
880 case glslang::EOpMatrixTimesMatrixAssign:
881 case glslang::EOpDivAssign:
882 case glslang::EOpModAssign:
883 case glslang::EOpAndAssign:
884 case glslang::EOpInclusiveOrAssign:
885 case glslang::EOpExclusiveOrAssign:
886 case glslang::EOpLeftShiftAssign:
887 case glslang::EOpRightShiftAssign:
888 // A bin-op assign "a += b" means the same thing as "a = a + b"
889 // where a is evaluated before b. For a simple assignment, GLSL
890 // says to evaluate the left before the right. So, always, left
891 // node then right node.
892 {
893 // get the left l-value, save it away
894 builder.clearAccessChain();
895 node->getLeft()->traverse(this);
896 spv::Builder::AccessChain lValue = builder.getAccessChain();
897
898 // evaluate the right
899 builder.clearAccessChain();
900 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700901 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600902
903 if (node->getOp() != glslang::EOpAssign) {
904 // the left is also an r-value
905 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700906 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600907
908 // do the operation
qining25262b32016-05-06 17:25:16 -0400909 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
910 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600911 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
912 node->getType().getBasicType());
913
914 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700915 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600916 }
917
918 // store the result
919 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800920 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600921
922 // assignments are expressions having an rValue after they are evaluated...
923 builder.clearAccessChain();
924 builder.setAccessChainRValue(rValue);
925 }
926 return false;
927 case glslang::EOpIndexDirect:
928 case glslang::EOpIndexDirectStruct:
929 {
930 // Get the left part of the access chain.
931 node->getLeft()->traverse(this);
932
933 // Add the next element in the chain
934
David Netoa901ffe2016-06-08 14:11:40 +0100935 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600936 if (! node->getLeft()->getType().isArray() &&
937 node->getLeft()->getType().isVector() &&
938 node->getOp() == glslang::EOpIndexDirect) {
939 // This is essentially a hard-coded vector swizzle of size 1,
940 // so short circuit the access-chain stuff with a swizzle.
941 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100942 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600943 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600944 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100945 int spvIndex = glslangIndex;
946 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
947 node->getOp() == glslang::EOpIndexDirectStruct)
948 {
949 // This may be, e.g., an anonymous block-member selection, which generally need
950 // index remapping due to hidden members in anonymous blocks.
951 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
952 assert(remapper.size() > 0);
953 spvIndex = remapper[glslangIndex];
954 }
John Kessenichebb50532016-05-16 19:22:05 -0600955
David Netoa901ffe2016-06-08 14:11:40 +0100956 // normal case for indexing array or structure or block
957 builder.accessChainPush(builder.makeIntConstant(spvIndex));
958
959 // Add capabilities here for accessing PointSize and clip/cull distance.
960 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600961 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100962 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600963 }
964 }
965 return false;
966 case glslang::EOpIndexIndirect:
967 {
968 // Structure or array or vector indirection.
969 // Will use native SPIR-V access-chain for struct and array indirection;
970 // matrices are arrays of vectors, so will also work for a matrix.
971 // Will use the access chain's 'component' for variable index into a vector.
972
973 // This adapter is building access chains left to right.
974 // Set up the access chain to the left.
975 node->getLeft()->traverse(this);
976
977 // save it so that computing the right side doesn't trash it
978 spv::Builder::AccessChain partial = builder.getAccessChain();
979
980 // compute the next index in the chain
981 builder.clearAccessChain();
982 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700983 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600984
985 // restore the saved access chain
986 builder.setAccessChain(partial);
987
988 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600989 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600990 else
John Kessenichfa668da2015-09-13 14:46:30 -0600991 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600992 }
993 return false;
994 case glslang::EOpVectorSwizzle:
995 {
996 node->getLeft()->traverse(this);
997 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
998 std::vector<unsigned> swizzle;
999 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1000 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -06001001 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001002 }
1003 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001004 case glslang::EOpLogicalOr:
1005 case glslang::EOpLogicalAnd:
1006 {
1007
1008 // These may require short circuiting, but can sometimes be done as straight
1009 // binary operations. The right operand must be short circuited if it has
1010 // side effects, and should probably be if it is complex.
1011 if (isTrivial(node->getRight()->getAsTyped()))
1012 break; // handle below as a normal binary operation
1013 // otherwise, we need to do dynamic short circuiting on the right operand
1014 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1015 builder.clearAccessChain();
1016 builder.setAccessChainRValue(result);
1017 }
1018 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001019 default:
1020 break;
1021 }
1022
1023 // Assume generic binary op...
1024
John Kessenich32cfd492016-02-02 12:37:46 -07001025 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001026 builder.clearAccessChain();
1027 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001028 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001029
John Kessenich32cfd492016-02-02 12:37:46 -07001030 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001031 builder.clearAccessChain();
1032 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001033 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001034
John Kessenich32cfd492016-02-02 12:37:46 -07001035 // get result
1036 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001037 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001038 convertGlslangToSpvType(node->getType()), left, right,
1039 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001040
John Kessenich50e57562015-12-21 21:21:11 -07001041 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001042 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001043 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001044 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001045 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001046 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001047 return false;
1048 }
John Kessenich140f3df2015-06-26 16:58:36 -06001049}
1050
1051bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1052{
qining40887662016-04-03 22:20:42 -04001053 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1054 if (node->getType().getQualifier().isSpecConstant())
1055 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1056
John Kessenichfc51d282015-08-19 13:34:18 -06001057 spv::Id result = spv::NoResult;
1058
1059 // try texturing first
1060 result = createImageTextureFunctionCall(node);
1061 if (result != spv::NoResult) {
1062 builder.clearAccessChain();
1063 builder.setAccessChainRValue(result);
1064
1065 return false; // done with this node
1066 }
1067
1068 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001069
1070 if (node->getOp() == glslang::EOpArrayLength) {
1071 // Quite special; won't want to evaluate the operand.
1072
1073 // Normal .length() would have been constant folded by the front-end.
1074 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001075 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001076 assert(node->getOperand()->getType().isRuntimeSizedArray());
1077 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1078 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001079 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1080 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001081
1082 builder.clearAccessChain();
1083 builder.setAccessChainRValue(length);
1084
1085 return false;
1086 }
1087
John Kessenichfc51d282015-08-19 13:34:18 -06001088 // Start by evaluating the operand
1089
John Kessenich140f3df2015-06-26 16:58:36 -06001090 builder.clearAccessChain();
1091 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001092
Rex Xufc618912015-09-09 16:42:49 +08001093 spv::Id operand = spv::NoResult;
1094
1095 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1096 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001097 node->getOp() == glslang::EOpAtomicCounter ||
1098 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001099 operand = builder.accessChainGetLValue(); // Special case l-value operands
1100 else
John Kessenich32cfd492016-02-02 12:37:46 -07001101 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001102
1103 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001104 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001105
1106 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001107 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001108 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001109
1110 // if not, then possibly an operation
1111 if (! result)
qining25262b32016-05-06 17:25:16 -04001112 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001113
1114 if (result) {
1115 builder.clearAccessChain();
1116 builder.setAccessChainRValue(result);
1117
1118 return false; // done with this node
1119 }
1120
1121 // it must be a special case, check...
1122 switch (node->getOp()) {
1123 case glslang::EOpPostIncrement:
1124 case glslang::EOpPostDecrement:
1125 case glslang::EOpPreIncrement:
1126 case glslang::EOpPreDecrement:
1127 {
1128 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001129 spv::Id one = 0;
1130 if (node->getBasicType() == glslang::EbtFloat)
1131 one = builder.makeFloatConstant(1.0F);
1132 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1133 one = builder.makeInt64Constant(1);
1134 else
1135 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001136 glslang::TOperator op;
1137 if (node->getOp() == glslang::EOpPreIncrement ||
1138 node->getOp() == glslang::EOpPostIncrement)
1139 op = glslang::EOpAdd;
1140 else
1141 op = glslang::EOpSub;
1142
qining25262b32016-05-06 17:25:16 -04001143 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1144 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001145 convertGlslangToSpvType(node->getType()), operand, one,
1146 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001147 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001148
1149 // The result of operation is always stored, but conditionally the
1150 // consumed result. The consumed result is always an r-value.
1151 builder.accessChainStore(result);
1152 builder.clearAccessChain();
1153 if (node->getOp() == glslang::EOpPreIncrement ||
1154 node->getOp() == glslang::EOpPreDecrement)
1155 builder.setAccessChainRValue(result);
1156 else
1157 builder.setAccessChainRValue(operand);
1158 }
1159
1160 return false;
1161
1162 case glslang::EOpEmitStreamVertex:
1163 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1164 return false;
1165 case glslang::EOpEndStreamPrimitive:
1166 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1167 return false;
1168
1169 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001170 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001171 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001172 }
John Kessenich140f3df2015-06-26 16:58:36 -06001173}
1174
1175bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1176{
qining27e04a02016-04-14 16:40:20 -04001177 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1178 if (node->getType().getQualifier().isSpecConstant())
1179 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1180
John Kessenichfc51d282015-08-19 13:34:18 -06001181 spv::Id result = spv::NoResult;
1182
1183 // try texturing
1184 result = createImageTextureFunctionCall(node);
1185 if (result != spv::NoResult) {
1186 builder.clearAccessChain();
1187 builder.setAccessChainRValue(result);
1188
1189 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001190 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001191 // "imageStore" is a special case, which has no result
1192 return false;
1193 }
John Kessenichfc51d282015-08-19 13:34:18 -06001194
John Kessenich140f3df2015-06-26 16:58:36 -06001195 glslang::TOperator binOp = glslang::EOpNull;
1196 bool reduceComparison = true;
1197 bool isMatrix = false;
1198 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001199 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001200
1201 assert(node->getOp());
1202
1203 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1204
1205 switch (node->getOp()) {
1206 case glslang::EOpSequence:
1207 {
1208 if (preVisit)
1209 ++sequenceDepth;
1210 else
1211 --sequenceDepth;
1212
1213 if (sequenceDepth == 1) {
1214 // If this is the parent node of all the functions, we want to see them
1215 // early, so all call points have actual SPIR-V functions to reference.
1216 // In all cases, still let the traverser visit the children for us.
1217 makeFunctions(node->getAsAggregate()->getSequence());
1218
1219 // Also, we want all globals initializers to go into the entry of main(), before
1220 // anything else gets there, so visit out of order, doing them all now.
1221 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1222
1223 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1224 // so do them manually.
1225 visitFunctions(node->getAsAggregate()->getSequence());
1226
1227 return false;
1228 }
1229
1230 return true;
1231 }
1232 case glslang::EOpLinkerObjects:
1233 {
1234 if (visit == glslang::EvPreVisit)
1235 linkageOnly = true;
1236 else
1237 linkageOnly = false;
1238
1239 return true;
1240 }
1241 case glslang::EOpComma:
1242 {
1243 // processing from left to right naturally leaves the right-most
1244 // lying around in the access chain
1245 glslang::TIntermSequence& glslangOperands = node->getSequence();
1246 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1247 glslangOperands[i]->traverse(this);
1248
1249 return false;
1250 }
1251 case glslang::EOpFunction:
1252 if (visit == glslang::EvPreVisit) {
1253 if (isShaderEntrypoint(node)) {
1254 inMain = true;
1255 builder.setBuildPoint(shaderEntry->getLastBlock());
1256 } else {
1257 handleFunctionEntry(node);
1258 }
1259 } else {
1260 if (inMain)
1261 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001262 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001263 inMain = false;
1264 }
1265
1266 return true;
1267 case glslang::EOpParameters:
1268 // Parameters will have been consumed by EOpFunction processing, but not
1269 // the body, so we still visited the function node's children, making this
1270 // child redundant.
1271 return false;
1272 case glslang::EOpFunctionCall:
1273 {
1274 if (node->isUserDefined())
1275 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001276 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1277 if (result) {
1278 builder.clearAccessChain();
1279 builder.setAccessChainRValue(result);
1280 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001281 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001282
1283 return false;
1284 }
1285 case glslang::EOpConstructMat2x2:
1286 case glslang::EOpConstructMat2x3:
1287 case glslang::EOpConstructMat2x4:
1288 case glslang::EOpConstructMat3x2:
1289 case glslang::EOpConstructMat3x3:
1290 case glslang::EOpConstructMat3x4:
1291 case glslang::EOpConstructMat4x2:
1292 case glslang::EOpConstructMat4x3:
1293 case glslang::EOpConstructMat4x4:
1294 case glslang::EOpConstructDMat2x2:
1295 case glslang::EOpConstructDMat2x3:
1296 case glslang::EOpConstructDMat2x4:
1297 case glslang::EOpConstructDMat3x2:
1298 case glslang::EOpConstructDMat3x3:
1299 case glslang::EOpConstructDMat3x4:
1300 case glslang::EOpConstructDMat4x2:
1301 case glslang::EOpConstructDMat4x3:
1302 case glslang::EOpConstructDMat4x4:
1303 isMatrix = true;
1304 // fall through
1305 case glslang::EOpConstructFloat:
1306 case glslang::EOpConstructVec2:
1307 case glslang::EOpConstructVec3:
1308 case glslang::EOpConstructVec4:
1309 case glslang::EOpConstructDouble:
1310 case glslang::EOpConstructDVec2:
1311 case glslang::EOpConstructDVec3:
1312 case glslang::EOpConstructDVec4:
1313 case glslang::EOpConstructBool:
1314 case glslang::EOpConstructBVec2:
1315 case glslang::EOpConstructBVec3:
1316 case glslang::EOpConstructBVec4:
1317 case glslang::EOpConstructInt:
1318 case glslang::EOpConstructIVec2:
1319 case glslang::EOpConstructIVec3:
1320 case glslang::EOpConstructIVec4:
1321 case glslang::EOpConstructUint:
1322 case glslang::EOpConstructUVec2:
1323 case glslang::EOpConstructUVec3:
1324 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001325 case glslang::EOpConstructInt64:
1326 case glslang::EOpConstructI64Vec2:
1327 case glslang::EOpConstructI64Vec3:
1328 case glslang::EOpConstructI64Vec4:
1329 case glslang::EOpConstructUint64:
1330 case glslang::EOpConstructU64Vec2:
1331 case glslang::EOpConstructU64Vec3:
1332 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001333 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001334 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001335 {
1336 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001337 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001338 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1339 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001340 if (node->getOp() == glslang::EOpConstructTextureSampler)
1341 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1342 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001343 std::vector<spv::Id> constituents;
1344 for (int c = 0; c < (int)arguments.size(); ++c)
1345 constituents.push_back(arguments[c]);
1346 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001347 } else if (isMatrix)
1348 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1349 else
1350 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 builder.clearAccessChain();
1353 builder.setAccessChainRValue(constructed);
1354
1355 return false;
1356 }
1357
1358 // These six are component-wise compares with component-wise results.
1359 // Forward on to createBinaryOperation(), requesting a vector result.
1360 case glslang::EOpLessThan:
1361 case glslang::EOpGreaterThan:
1362 case glslang::EOpLessThanEqual:
1363 case glslang::EOpGreaterThanEqual:
1364 case glslang::EOpVectorEqual:
1365 case glslang::EOpVectorNotEqual:
1366 {
1367 // Map the operation to a binary
1368 binOp = node->getOp();
1369 reduceComparison = false;
1370 switch (node->getOp()) {
1371 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1372 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1373 default: binOp = node->getOp(); break;
1374 }
1375
1376 break;
1377 }
1378 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001379 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001380 binOp = glslang::EOpMul;
1381 break;
1382 case glslang::EOpOuterProduct:
1383 // two vectors multiplied to make a matrix
1384 binOp = glslang::EOpOuterProduct;
1385 break;
1386 case glslang::EOpDot:
1387 {
qining25262b32016-05-06 17:25:16 -04001388 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001389 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001390 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001391 binOp = glslang::EOpMul;
1392 break;
1393 }
1394 case glslang::EOpMod:
1395 // when an aggregate, this is the floating-point mod built-in function,
1396 // which can be emitted by the one in createBinaryOperation()
1397 binOp = glslang::EOpMod;
1398 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001399 case glslang::EOpEmitVertex:
1400 case glslang::EOpEndPrimitive:
1401 case glslang::EOpBarrier:
1402 case glslang::EOpMemoryBarrier:
1403 case glslang::EOpMemoryBarrierAtomicCounter:
1404 case glslang::EOpMemoryBarrierBuffer:
1405 case glslang::EOpMemoryBarrierImage:
1406 case glslang::EOpMemoryBarrierShared:
1407 case glslang::EOpGroupMemoryBarrier:
1408 noReturnValue = true;
1409 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1410 break;
1411
John Kessenich426394d2015-07-23 10:22:48 -06001412 case glslang::EOpAtomicAdd:
1413 case glslang::EOpAtomicMin:
1414 case glslang::EOpAtomicMax:
1415 case glslang::EOpAtomicAnd:
1416 case glslang::EOpAtomicOr:
1417 case glslang::EOpAtomicXor:
1418 case glslang::EOpAtomicExchange:
1419 case glslang::EOpAtomicCompSwap:
1420 atomic = true;
1421 break;
1422
John Kessenich140f3df2015-06-26 16:58:36 -06001423 default:
1424 break;
1425 }
1426
1427 //
1428 // See if it maps to a regular operation.
1429 //
John Kessenich140f3df2015-06-26 16:58:36 -06001430 if (binOp != glslang::EOpNull) {
1431 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1432 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1433 assert(left && right);
1434
1435 builder.clearAccessChain();
1436 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001437 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 builder.clearAccessChain();
1440 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001441 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001442
qining25262b32016-05-06 17:25:16 -04001443 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1444 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001445 left->getType().getBasicType(), reduceComparison);
1446
1447 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001448 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001449 builder.clearAccessChain();
1450 builder.setAccessChainRValue(result);
1451
1452 return false;
1453 }
1454
John Kessenich426394d2015-07-23 10:22:48 -06001455 //
1456 // Create the list of operands.
1457 //
John Kessenich140f3df2015-06-26 16:58:36 -06001458 glslang::TIntermSequence& glslangOperands = node->getSequence();
1459 std::vector<spv::Id> operands;
1460 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1461 builder.clearAccessChain();
1462 glslangOperands[arg]->traverse(this);
1463
1464 // special case l-value operands; there are just a few
1465 bool lvalue = false;
1466 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001467 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001468 case glslang::EOpModf:
1469 if (arg == 1)
1470 lvalue = true;
1471 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001472 case glslang::EOpInterpolateAtSample:
1473 case glslang::EOpInterpolateAtOffset:
1474 if (arg == 0)
1475 lvalue = true;
1476 break;
Rex Xud4782c12015-09-06 16:30:11 +08001477 case glslang::EOpAtomicAdd:
1478 case glslang::EOpAtomicMin:
1479 case glslang::EOpAtomicMax:
1480 case glslang::EOpAtomicAnd:
1481 case glslang::EOpAtomicOr:
1482 case glslang::EOpAtomicXor:
1483 case glslang::EOpAtomicExchange:
1484 case glslang::EOpAtomicCompSwap:
1485 if (arg == 0)
1486 lvalue = true;
1487 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001488 case glslang::EOpAddCarry:
1489 case glslang::EOpSubBorrow:
1490 if (arg == 2)
1491 lvalue = true;
1492 break;
1493 case glslang::EOpUMulExtended:
1494 case glslang::EOpIMulExtended:
1495 if (arg >= 2)
1496 lvalue = true;
1497 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001498 default:
1499 break;
1500 }
1501 if (lvalue)
1502 operands.push_back(builder.accessChainGetLValue());
1503 else
John Kessenich32cfd492016-02-02 12:37:46 -07001504 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001505 }
John Kessenich426394d2015-07-23 10:22:48 -06001506
1507 if (atomic) {
1508 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001509 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001510 } else {
1511 // Pass through to generic operations.
1512 switch (glslangOperands.size()) {
1513 case 0:
1514 result = createNoArgOperation(node->getOp());
1515 break;
1516 case 1:
qining25262b32016-05-06 17:25:16 -04001517 result = createUnaryOperation(
1518 node->getOp(), precision,
1519 TranslateNoContractionDecoration(node->getType().getQualifier()),
1520 convertGlslangToSpvType(node->getType()), operands.front(),
1521 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001522 break;
1523 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001524 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001525 break;
1526 }
John Kessenich140f3df2015-06-26 16:58:36 -06001527 }
1528
1529 if (noReturnValue)
1530 return false;
1531
1532 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001533 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001534 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001535 } else {
1536 builder.clearAccessChain();
1537 builder.setAccessChainRValue(result);
1538 return false;
1539 }
1540}
1541
1542bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1543{
1544 // This path handles both if-then-else and ?:
1545 // The if-then-else has a node type of void, while
1546 // ?: has a non-void node type
1547 spv::Id result = 0;
1548 if (node->getBasicType() != glslang::EbtVoid) {
1549 // don't handle this as just on-the-fly temporaries, because there will be two names
1550 // and better to leave SSA to later passes
1551 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1552 }
1553
1554 // emit the condition before doing anything with selection
1555 node->getCondition()->traverse(this);
1556
1557 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001558 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001559
1560 if (node->getTrueBlock()) {
1561 // emit the "then" statement
1562 node->getTrueBlock()->traverse(this);
1563 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001564 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001565 }
1566
1567 if (node->getFalseBlock()) {
1568 ifBuilder.makeBeginElse();
1569 // emit the "else" statement
1570 node->getFalseBlock()->traverse(this);
1571 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001572 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001573 }
1574
1575 ifBuilder.makeEndIf();
1576
1577 if (result) {
1578 // GLSL only has r-values as the result of a :?, but
1579 // if we have an l-value, that can be more efficient if it will
1580 // become the base of a complex r-value expression, because the
1581 // next layer copies r-values into memory to use the access-chain mechanism
1582 builder.clearAccessChain();
1583 builder.setAccessChainLValue(result);
1584 }
1585
1586 return false;
1587}
1588
1589bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1590{
1591 // emit and get the condition before doing anything with switch
1592 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001593 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001594
1595 // browse the children to sort out code segments
1596 int defaultSegment = -1;
1597 std::vector<TIntermNode*> codeSegments;
1598 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1599 std::vector<int> caseValues;
1600 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1601 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1602 TIntermNode* child = *c;
1603 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001604 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001605 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001606 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001607 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1608 } else
1609 codeSegments.push_back(child);
1610 }
1611
qining25262b32016-05-06 17:25:16 -04001612 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001613 // statements between the last case and the end of the switch statement
1614 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1615 (int)codeSegments.size() == defaultSegment)
1616 codeSegments.push_back(nullptr);
1617
1618 // make the switch statement
1619 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001620 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001621
1622 // emit all the code in the segments
1623 breakForLoop.push(false);
1624 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1625 builder.nextSwitchSegment(segmentBlocks, s);
1626 if (codeSegments[s])
1627 codeSegments[s]->traverse(this);
1628 else
1629 builder.addSwitchBreak();
1630 }
1631 breakForLoop.pop();
1632
1633 builder.endSwitch(segmentBlocks);
1634
1635 return false;
1636}
1637
1638void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1639{
1640 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001641 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001642
1643 builder.clearAccessChain();
1644 builder.setAccessChainRValue(constant);
1645}
1646
1647bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1648{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001649 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001650 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001651 // Spec requires back edges to target header blocks, and every header block
1652 // must dominate its merge block. Make a header block first to ensure these
1653 // conditions are met. By definition, it will contain OpLoopMerge, followed
1654 // by a block-ending branch. But we don't want to put any other body/test
1655 // instructions in it, since the body/test may have arbitrary instructions,
1656 // including merges of its own.
1657 builder.setBuildPoint(&blocks.head);
1658 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001659 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001660 spv::Block& test = builder.makeNewBlock();
1661 builder.createBranch(&test);
1662
1663 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001664 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001665 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001666 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001667 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1668
1669 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001670 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001671 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001672 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001673 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001674 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001675
1676 builder.setBuildPoint(&blocks.continue_target);
1677 if (node->getTerminal())
1678 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001679 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001680 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001681 builder.createBranch(&blocks.body);
1682
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001683 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001684 builder.setBuildPoint(&blocks.body);
1685 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001686 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001687 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001688 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001689
1690 builder.setBuildPoint(&blocks.continue_target);
1691 if (node->getTerminal())
1692 node->getTerminal()->traverse(this);
1693 if (node->getTest()) {
1694 node->getTest()->traverse(this);
1695 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001696 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001697 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001698 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001699 // TODO: unless there was a break/return/discard instruction
1700 // somewhere in the body, this is an infinite loop, so we should
1701 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001702 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001703 }
John Kessenich140f3df2015-06-26 16:58:36 -06001704 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001705 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001706 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001707 return false;
1708}
1709
1710bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1711{
1712 if (node->getExpression())
1713 node->getExpression()->traverse(this);
1714
1715 switch (node->getFlowOp()) {
1716 case glslang::EOpKill:
1717 builder.makeDiscard();
1718 break;
1719 case glslang::EOpBreak:
1720 if (breakForLoop.top())
1721 builder.createLoopExit();
1722 else
1723 builder.addSwitchBreak();
1724 break;
1725 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001726 builder.createLoopContinue();
1727 break;
1728 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001729 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001730 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001731 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001732 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001733
1734 builder.clearAccessChain();
1735 break;
1736
1737 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001738 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 break;
1740 }
1741
1742 return false;
1743}
1744
1745spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1746{
qining25262b32016-05-06 17:25:16 -04001747 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001748 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001749 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001750 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001751 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001752 }
1753
1754 // Now, handle actual variables
1755 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1756 spv::Id spvType = convertGlslangToSpvType(node->getType());
1757
1758 const char* name = node->getName().c_str();
1759 if (glslang::IsAnonymous(name))
1760 name = "";
1761
1762 return builder.createVariable(storageClass, spvType, name);
1763}
1764
1765// Return type Id of the sampled type.
1766spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1767{
1768 switch (sampler.type) {
1769 case glslang::EbtFloat: return builder.makeFloatType(32);
1770 case glslang::EbtInt: return builder.makeIntType(32);
1771 case glslang::EbtUint: return builder.makeUintType(32);
1772 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001773 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001774 return builder.makeFloatType(32);
1775 }
1776}
1777
John Kessenich3ac051e2015-12-20 11:29:16 -07001778// Convert from a glslang type to an SPV type, by calling into a
1779// recursive version of this function. This establishes the inherited
1780// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001781spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1782{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001783 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001784}
1785
1786// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001787// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001788spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001789{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001790 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001791
1792 switch (type.getBasicType()) {
1793 case glslang::EbtVoid:
1794 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001795 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001796 break;
1797 case glslang::EbtFloat:
1798 spvType = builder.makeFloatType(32);
1799 break;
1800 case glslang::EbtDouble:
1801 spvType = builder.makeFloatType(64);
1802 break;
1803 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001804 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1805 // a 32-bit int where non-0 means true.
1806 if (explicitLayout != glslang::ElpNone)
1807 spvType = builder.makeUintType(32);
1808 else
1809 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001810 break;
1811 case glslang::EbtInt:
1812 spvType = builder.makeIntType(32);
1813 break;
1814 case glslang::EbtUint:
1815 spvType = builder.makeUintType(32);
1816 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001817 case glslang::EbtInt64:
1818 builder.addCapability(spv::CapabilityInt64);
1819 spvType = builder.makeIntType(64);
1820 break;
1821 case glslang::EbtUint64:
1822 builder.addCapability(spv::CapabilityInt64);
1823 spvType = builder.makeUintType(64);
1824 break;
John Kessenich426394d2015-07-23 10:22:48 -06001825 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001826 logger->tbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
John Kessenich426394d2015-07-23 10:22:48 -06001827 spvType = builder.makeUintType(32);
1828 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001829 case glslang::EbtSampler:
1830 {
1831 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001832 if (sampler.sampler) {
1833 // pure sampler
1834 spvType = builder.makeSamplerType();
1835 } else {
1836 // an image is present, make its type
1837 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1838 sampler.image ? 2 : 1, TranslateImageFormat(type));
1839 if (sampler.combined) {
1840 // already has both image and sampler, make the combined type
1841 spvType = builder.makeSampledImageType(spvType);
1842 }
John Kessenich55e7d112015-11-15 21:33:39 -07001843 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001844 }
John Kessenich140f3df2015-06-26 16:58:36 -06001845 break;
1846 case glslang::EbtStruct:
1847 case glslang::EbtBlock:
1848 {
1849 // If we've seen this struct type, return it
1850 const glslang::TTypeList* glslangStruct = type.getStruct();
1851 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001852
1853 // Try to share structs for different layouts, but not yet for other
1854 // kinds of qualification (primarily not yet including interpolant qualification).
1855 if (! HasNonLayoutQualifiers(qualifier))
1856 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1857 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001858 break;
1859
1860 // else, we haven't seen it...
1861
1862 // Create a vector of struct types for SPIR-V to consume
1863 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1864 if (type.getBasicType() == glslang::EbtBlock)
1865 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001866 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001867 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1868 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1869 if (glslangType.hiddenMember()) {
1870 ++memberDelta;
1871 if (type.getBasicType() == glslang::EbtBlock)
1872 memberRemapper[glslangStruct][i] = -1;
1873 } else {
1874 if (type.getBasicType() == glslang::EbtBlock)
1875 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001876 // modify just this child's view of the qualifier
1877 glslang::TQualifier subQualifier = glslangType.getQualifier();
1878 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001879
1880 // manually inherit location; it's more complex
1881 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1882 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1883 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001884 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001885
1886 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001887 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001888 }
1889 }
1890
1891 // Make the SPIR-V type
1892 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 if (! HasNonLayoutQualifiers(qualifier))
1894 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001895
1896 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001897 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001898 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001899 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1900 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1901 int member = i;
1902 if (type.getBasicType() == glslang::EbtBlock)
1903 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001904
John Kesseniche0b6cad2015-12-24 10:30:13 -07001905 // modify just this child's view of the qualifier
1906 glslang::TQualifier subQualifier = glslangType.getQualifier();
1907 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001908
John Kessenich140f3df2015-06-26 16:58:36 -06001909 // using -1 above to indicate a hidden member
1910 if (member >= 0) {
1911 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001912 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001913 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
Rex Xubbceed72016-05-21 09:40:44 +08001914 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001915 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06001916 if (type.getBasicType() == glslang::EbtBlock) {
1917 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1918 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(subQualifier));
1919 }
scygan8add1512016-05-06 16:54:54 +02001920 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001921 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001922
Rex Xu1da878f2016-02-21 20:59:01 +08001923 if (qualifier.storage == glslang::EvqBuffer) {
1924 std::vector<spv::Decoration> memory;
1925 TranslateMemoryDecoration(subQualifier, memory);
1926 for (unsigned int i = 0; i < memory.size(); ++i)
1927 addMemberDecoration(spvType, member, memory[i]);
1928 }
1929
John Kessenich09677482016-02-19 12:21:50 -07001930 // compute location decoration; tricky based on whether inheritance is at play
1931 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1932 // probably move to the linker stage of the front end proper, and just have the
1933 // answer sitting already distributed throughout the individual member locations.
1934 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001935 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001936 // struct members should not have explicit locations
1937 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001938 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001939 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001940 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1941 // The members, and their nested types, must not themselves have Location decorations.
1942 }
John Kessenich09677482016-02-19 12:21:50 -07001943 else if (qualifier.hasLocation()) // inheritance
1944 location = qualifier.layoutLocation + locationOffset;
1945 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001946 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001947 if (location >= 0)
1948 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1949
1950 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001951 if (glslangType.getQualifier().hasComponent())
1952 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1953 if (glslangType.getQualifier().hasXfbOffset())
1954 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001955 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001956 // figure out what to do with offset, which is accumulating
1957 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001958 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001959 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001960 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001961 offset = nextOffset;
1962 }
John Kessenich140f3df2015-06-26 16:58:36 -06001963
John Kessenichf85e8062015-12-19 13:57:10 -07001964 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001965 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001966
John Kessenich140f3df2015-06-26 16:58:36 -06001967 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001968 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001969 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001970 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001971 }
1972 }
1973
1974 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001975 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001976 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001977 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001978 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001979 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001980 }
John Kessenich140f3df2015-06-26 16:58:36 -06001981 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001982 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001983 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001984 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001985 if (type.getQualifier().hasXfbBuffer())
1986 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1987 }
1988 }
1989 break;
1990 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001991 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001992 break;
1993 }
1994
1995 if (type.isMatrix())
1996 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1997 else {
1998 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1999 if (type.getVectorSize() > 1)
2000 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2001 }
2002
2003 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002004 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2005
John Kessenichc9a80832015-09-12 12:17:44 -06002006 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002007 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002008 // We need to decorate array strides for types needing explicit layout, except blocks.
2009 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002010 // Use a dummy glslang type for querying internal strides of
2011 // arrays of arrays, but using just a one-dimensional array.
2012 glslang::TType simpleArrayType(type, 0); // deference type of the array
2013 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2014 simpleArrayType.getArraySizes().dereference();
2015
2016 // Will compute the higher-order strides here, rather than making a whole
2017 // pile of types and doing repetitive recursion on their contents.
2018 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2019 }
John Kessenichf8842e52016-01-04 19:22:56 -07002020
2021 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002022 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002023 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002024 if (stride > 0)
2025 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002026 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002027 }
2028 } else {
2029 // single-dimensional array, and don't yet have stride
2030
John Kessenichf8842e52016-01-04 19:22:56 -07002031 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002032 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2033 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002034 }
John Kessenich31ed4832015-09-09 17:51:38 -06002035
John Kessenichc9a80832015-09-12 12:17:44 -06002036 // Do the outer dimension, which might not be known for a runtime-sized array
2037 if (type.isRuntimeSizedArray()) {
2038 spvType = builder.makeRuntimeArray(spvType);
2039 } else {
2040 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002041 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002042 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002043 if (stride > 0)
2044 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002045 }
2046
2047 return spvType;
2048}
2049
John Kessenich6c292d32016-02-15 20:58:50 -07002050// Turn the expression forming the array size into an id.
2051// This is not quite trivial, because of specialization constants.
2052// Sometimes, a raw constant is turned into an Id, and sometimes
2053// a specialization constant expression is.
2054spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2055{
2056 // First, see if this is sized with a node, meaning a specialization constant:
2057 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2058 if (specNode != nullptr) {
2059 builder.clearAccessChain();
2060 specNode->traverse(this);
2061 return accessChainLoad(specNode->getAsTyped()->getType());
2062 }
qining25262b32016-05-06 17:25:16 -04002063
John Kessenich6c292d32016-02-15 20:58:50 -07002064 // Otherwise, need a compile-time (front end) size, get it:
2065 int size = arraySizes.getDimSize(dim);
2066 assert(size > 0);
2067 return builder.makeUintConstant(size);
2068}
2069
John Kessenich103bef92016-02-08 21:38:15 -07002070// Wrap the builder's accessChainLoad to:
2071// - localize handling of RelaxedPrecision
2072// - use the SPIR-V inferred type instead of another conversion of the glslang type
2073// (avoids unnecessary work and possible type punning for structures)
2074// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002075spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2076{
John Kessenich103bef92016-02-08 21:38:15 -07002077 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2078 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2079
2080 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002081 if (type.getBasicType() == glslang::EbtBool) {
2082 if (builder.isScalarType(nominalTypeId)) {
2083 // Conversion for bool
2084 spv::Id boolType = builder.makeBoolType();
2085 if (nominalTypeId != boolType)
2086 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2087 } else if (builder.isVectorType(nominalTypeId)) {
2088 // Conversion for bvec
2089 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2090 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2091 if (nominalTypeId != bvecType)
2092 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2093 }
2094 }
John Kessenich103bef92016-02-08 21:38:15 -07002095
2096 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002097}
2098
Rex Xu27253232016-02-23 17:51:09 +08002099// Wrap the builder's accessChainStore to:
2100// - do conversion of concrete to abstract type
2101void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2102{
2103 // Need to convert to abstract types when necessary
2104 if (type.getBasicType() == glslang::EbtBool) {
2105 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2106
2107 if (builder.isScalarType(nominalTypeId)) {
2108 // Conversion for bool
2109 spv::Id boolType = builder.makeBoolType();
2110 if (nominalTypeId != boolType) {
2111 spv::Id zero = builder.makeUintConstant(0);
2112 spv::Id one = builder.makeUintConstant(1);
2113 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2114 }
2115 } else if (builder.isVectorType(nominalTypeId)) {
2116 // Conversion for bvec
2117 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2118 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2119 if (nominalTypeId != bvecType) {
2120 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2121 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2122 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2123 }
2124 }
2125 }
2126
2127 builder.accessChainStore(rvalue);
2128}
2129
John Kessenichf85e8062015-12-19 13:57:10 -07002130// Decide whether or not this type should be
2131// decorated with offsets and strides, and if so
2132// whether std140 or std430 rules should be applied.
2133glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002134{
John Kessenichf85e8062015-12-19 13:57:10 -07002135 // has to be a block
2136 if (type.getBasicType() != glslang::EbtBlock)
2137 return glslang::ElpNone;
2138
2139 // has to be a uniform or buffer block
2140 if (type.getQualifier().storage != glslang::EvqUniform &&
2141 type.getQualifier().storage != glslang::EvqBuffer)
2142 return glslang::ElpNone;
2143
2144 // return the layout to use
2145 switch (type.getQualifier().layoutPacking) {
2146 case glslang::ElpStd140:
2147 case glslang::ElpStd430:
2148 return type.getQualifier().layoutPacking;
2149 default:
2150 return glslang::ElpNone;
2151 }
John Kessenich31ed4832015-09-09 17:51:38 -06002152}
2153
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002154// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002155int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002156{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002157 int size;
John Kessenich49987892015-12-29 17:11:44 -07002158 int stride;
2159 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002160
2161 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002162}
2163
John Kessenich49987892015-12-29 17:11:44 -07002164// 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 -07002165// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002166int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002167{
John Kessenich49987892015-12-29 17:11:44 -07002168 glslang::TType elementType;
2169 elementType.shallowCopy(matrixType);
2170 elementType.clearArraySizes();
2171
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002172 int size;
John Kessenich49987892015-12-29 17:11:44 -07002173 int stride;
2174 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2175
2176 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002177}
2178
John Kessenich5e4b1242015-08-06 22:53:06 -06002179// Given a member type of a struct, realign the current offset for it, and compute
2180// the next (not yet aligned) offset for the next member, which will get aligned
2181// on the next call.
2182// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2183// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2184// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002185void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002186 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002187{
2188 // this will get a positive value when deemed necessary
2189 nextOffset = -1;
2190
John Kessenich5e4b1242015-08-06 22:53:06 -06002191 // override anything in currentOffset with user-set offset
2192 if (memberType.getQualifier().hasOffset())
2193 currentOffset = memberType.getQualifier().layoutOffset;
2194
2195 // It could be that current linker usage in glslang updated all the layoutOffset,
2196 // in which case the following code does not matter. But, that's not quite right
2197 // once cross-compilation unit GLSL validation is done, as the original user
2198 // settings are needed in layoutOffset, and then the following will come into play.
2199
John Kessenichf85e8062015-12-19 13:57:10 -07002200 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002201 if (! memberType.getQualifier().hasOffset())
2202 currentOffset = -1;
2203
2204 return;
2205 }
2206
John Kessenichf85e8062015-12-19 13:57:10 -07002207 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002208 if (currentOffset < 0)
2209 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002210
John Kessenich5e4b1242015-08-06 22:53:06 -06002211 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2212 // but possibly not yet correctly aligned.
2213
2214 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002215 int dummyStride;
2216 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002217 glslang::RoundToPow2(currentOffset, memberAlignment);
2218 nextOffset = currentOffset + memberSize;
2219}
2220
David Netoa901ffe2016-06-08 14:11:40 +01002221void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002222{
David Netoa901ffe2016-06-08 14:11:40 +01002223 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2224 switch (glslangBuiltIn)
2225 {
2226 case glslang::EbvClipDistance:
2227 case glslang::EbvCullDistance:
2228 case glslang::EbvPointSize:
2229 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2230 // Alternately, we could just call this for any glslang built-in, since the
2231 // capability already guards against duplicates.
2232 TranslateBuiltInDecoration(glslangBuiltIn, false);
2233 break;
2234 default:
2235 // Capabilities were already generated when the struct was declared.
2236 break;
2237 }
John Kessenichebb50532016-05-16 19:22:05 -06002238}
2239
John Kessenich140f3df2015-06-26 16:58:36 -06002240bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2241{
John Kessenich4d65ee32016-03-12 18:17:47 -07002242 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002243 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002244 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002245}
2246
2247// Make all the functions, skeletally, without actually visiting their bodies.
2248void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2249{
2250 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2251 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2252 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2253 continue;
2254
2255 // We're on a user function. Set up the basic interface for the function now,
2256 // so that it's available to call.
2257 // Translating the body will happen later.
2258 //
qining25262b32016-05-06 17:25:16 -04002259 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002260 // function. What it is an address of varies:
2261 //
2262 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2263 // so that write needs to be to a copy, hence the address of a copy works.
2264 //
2265 // - "const in" parameters can just be the r-value, as no writes need occur.
2266 //
2267 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2268 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2269
2270 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002271 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002272 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2273
2274 for (int p = 0; p < (int)parameters.size(); ++p) {
2275 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2276 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002277 if (paramType.isOpaque())
2278 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2279 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002280 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2281 else
2282 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002283 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002284 paramTypes.push_back(typeId);
2285 }
2286
2287 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002288 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2289 convertGlslangToSpvType(glslFunction->getType()),
2290 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002291
2292 // Track function to emit/call later
2293 functionMap[glslFunction->getName().c_str()] = function;
2294
2295 // Set the parameter id's
2296 for (int p = 0; p < (int)parameters.size(); ++p) {
2297 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2298 // give a name too
2299 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2300 }
2301 }
2302}
2303
2304// Process all the initializers, while skipping the functions and link objects
2305void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2306{
2307 builder.setBuildPoint(shaderEntry->getLastBlock());
2308 for (int i = 0; i < (int)initializers.size(); ++i) {
2309 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2310 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2311
2312 // We're on a top-level node that's not a function. Treat as an initializer, whose
2313 // code goes into the beginning of main.
2314 initializer->traverse(this);
2315 }
2316 }
2317}
2318
2319// Process all the functions, while skipping initializers.
2320void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2321{
2322 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2323 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2324 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2325 node->traverse(this);
2326 }
2327}
2328
2329void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2330{
qining25262b32016-05-06 17:25:16 -04002331 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002332 // that called makeFunctions().
2333 spv::Function* function = functionMap[node->getName().c_str()];
2334 spv::Block* functionBlock = function->getEntryBlock();
2335 builder.setBuildPoint(functionBlock);
2336}
2337
Rex Xu04db3f52015-09-16 11:44:02 +08002338void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002339{
Rex Xufc618912015-09-09 16:42:49 +08002340 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002341
2342 glslang::TSampler sampler = {};
2343 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002344 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002345 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2346 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2347 }
2348
John Kessenich140f3df2015-06-26 16:58:36 -06002349 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2350 builder.clearAccessChain();
2351 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002352
2353 // Special case l-value operands
2354 bool lvalue = false;
2355 switch (node.getOp()) {
2356 case glslang::EOpImageAtomicAdd:
2357 case glslang::EOpImageAtomicMin:
2358 case glslang::EOpImageAtomicMax:
2359 case glslang::EOpImageAtomicAnd:
2360 case glslang::EOpImageAtomicOr:
2361 case glslang::EOpImageAtomicXor:
2362 case glslang::EOpImageAtomicExchange:
2363 case glslang::EOpImageAtomicCompSwap:
2364 if (i == 0)
2365 lvalue = true;
2366 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002367 case glslang::EOpSparseImageLoad:
2368 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2369 lvalue = true;
2370 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002371 case glslang::EOpSparseTexture:
2372 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2373 lvalue = true;
2374 break;
2375 case glslang::EOpSparseTextureClamp:
2376 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2377 lvalue = true;
2378 break;
2379 case glslang::EOpSparseTextureLod:
2380 case glslang::EOpSparseTextureOffset:
2381 if (i == 3)
2382 lvalue = true;
2383 break;
2384 case glslang::EOpSparseTextureFetch:
2385 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2386 lvalue = true;
2387 break;
2388 case glslang::EOpSparseTextureFetchOffset:
2389 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2390 lvalue = true;
2391 break;
2392 case glslang::EOpSparseTextureLodOffset:
2393 case glslang::EOpSparseTextureGrad:
2394 case glslang::EOpSparseTextureOffsetClamp:
2395 if (i == 4)
2396 lvalue = true;
2397 break;
2398 case glslang::EOpSparseTextureGradOffset:
2399 case glslang::EOpSparseTextureGradClamp:
2400 if (i == 5)
2401 lvalue = true;
2402 break;
2403 case glslang::EOpSparseTextureGradOffsetClamp:
2404 if (i == 6)
2405 lvalue = true;
2406 break;
2407 case glslang::EOpSparseTextureGather:
2408 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2409 lvalue = true;
2410 break;
2411 case glslang::EOpSparseTextureGatherOffset:
2412 case glslang::EOpSparseTextureGatherOffsets:
2413 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2414 lvalue = true;
2415 break;
Rex Xufc618912015-09-09 16:42:49 +08002416 default:
2417 break;
2418 }
2419
Rex Xu6b86d492015-09-16 17:48:22 +08002420 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002421 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002422 else
John Kessenich32cfd492016-02-02 12:37:46 -07002423 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002424 }
2425}
2426
John Kessenichfc51d282015-08-19 13:34:18 -06002427void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002428{
John Kessenichfc51d282015-08-19 13:34:18 -06002429 builder.clearAccessChain();
2430 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002431 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002432}
John Kessenich140f3df2015-06-26 16:58:36 -06002433
John Kessenichfc51d282015-08-19 13:34:18 -06002434spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2435{
Rex Xufc618912015-09-09 16:42:49 +08002436 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002437 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002438 }
2439
John Kessenichfc51d282015-08-19 13:34:18 -06002440 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002441 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2442 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2443 std::vector<spv::Id> arguments;
2444 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002445 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002446 else
2447 translateArguments(*node->getAsUnaryNode(), arguments);
2448 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2449
2450 spv::Builder::TextureParameters params = { };
2451 params.sampler = arguments[0];
2452
Rex Xu04db3f52015-09-16 11:44:02 +08002453 glslang::TCrackedTextureOp cracked;
2454 node->crackTexture(sampler, cracked);
2455
John Kessenichfc51d282015-08-19 13:34:18 -06002456 // Check for queries
2457 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002458 // a sampled image needs to have the image extracted first
2459 if (builder.isSampledImage(params.sampler))
2460 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002461 switch (node->getOp()) {
2462 case glslang::EOpImageQuerySize:
2463 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002464 if (arguments.size() > 1) {
2465 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002466 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002467 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002468 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002469 case glslang::EOpImageQuerySamples:
2470 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002471 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002472 case glslang::EOpTextureQueryLod:
2473 params.coords = arguments[1];
2474 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2475 case glslang::EOpTextureQueryLevels:
2476 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002477 case glslang::EOpSparseTexelsResident:
2478 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002479 default:
2480 assert(0);
2481 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002482 }
John Kessenich140f3df2015-06-26 16:58:36 -06002483 }
2484
Rex Xufc618912015-09-09 16:42:49 +08002485 // Check for image functions other than queries
2486 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002487 std::vector<spv::Id> operands;
2488 auto opIt = arguments.begin();
2489 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002490
2491 // Handle subpass operations
2492 // TODO: GLSL should change to have the "MS" only on the type rather than the
2493 // built-in function.
2494 if (cracked.subpass) {
2495 // add on the (0,0) coordinate
2496 spv::Id zero = builder.makeIntConstant(0);
2497 std::vector<spv::Id> comps;
2498 comps.push_back(zero);
2499 comps.push_back(zero);
2500 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2501 if (sampler.ms) {
2502 operands.push_back(spv::ImageOperandsSampleMask);
2503 operands.push_back(*(opIt++));
2504 }
2505 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2506 }
2507
John Kessenich56bab042015-09-16 10:54:31 -06002508 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002509 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002510 if (sampler.ms) {
2511 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002512 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002513 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002514 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2515 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002516 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002517 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002518 if (sampler.ms) {
2519 operands.push_back(*(opIt + 1));
2520 operands.push_back(spv::ImageOperandsSampleMask);
2521 operands.push_back(*opIt);
2522 } else
2523 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002524 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002525 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2526 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002527 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002528 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2529 builder.addCapability(spv::CapabilitySparseResidency);
2530 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2531 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2532
2533 if (sampler.ms) {
2534 operands.push_back(spv::ImageOperandsSampleMask);
2535 operands.push_back(*opIt++);
2536 }
2537
2538 // Create the return type that was a special structure
2539 spv::Id texelOut = *opIt;
2540 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2541 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2542 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2543
2544 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2545
2546 // Decode the return type
2547 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2548 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002549 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002550 // Process image atomic operations
2551
2552 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2553 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002554 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002555
Rex Xufc618912015-09-09 16:42:49 +08002556 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002557 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002558
2559 std::vector<spv::Id> operands;
2560 operands.push_back(pointer);
2561 for (; opIt != arguments.end(); ++opIt)
2562 operands.push_back(*opIt);
2563
Rex Xu04db3f52015-09-16 11:44:02 +08002564 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002565 }
2566 }
2567
2568 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002569 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002570 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2571
John Kessenichfc51d282015-08-19 13:34:18 -06002572 // check for bias argument
2573 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002574 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002575 int nonBiasArgCount = 2;
2576 if (cracked.offset)
2577 ++nonBiasArgCount;
2578 if (cracked.grad)
2579 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002580 if (cracked.lodClamp)
2581 ++nonBiasArgCount;
2582 if (sparse)
2583 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002584
2585 if ((int)arguments.size() > nonBiasArgCount)
2586 bias = true;
2587 }
2588
John Kessenicha5c33d62016-06-02 23:45:21 -06002589 // See if the sampler param should really be just the SPV image part
2590 if (cracked.fetch) {
2591 // a fetch needs to have the image extracted first
2592 if (builder.isSampledImage(params.sampler))
2593 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2594 }
2595
John Kessenichfc51d282015-08-19 13:34:18 -06002596 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002597
John Kessenichfc51d282015-08-19 13:34:18 -06002598 params.coords = arguments[1];
2599 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002600 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002601
2602 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002603 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002604 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002605 ++extraArgs;
2606 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002607 params.Dref = arguments[2];
2608 ++extraArgs;
2609 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002610 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002611 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002612 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002613 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002614 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002615 dRefComp = builder.getNumComponents(params.coords) - 1;
2616 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002617 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2618 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002619
2620 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002621 if (cracked.lod) {
2622 params.lod = arguments[2];
2623 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002624 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2625 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2626 noImplicitLod = true;
2627 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002628
2629 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002630 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002631 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002632 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002633 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002634
2635 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002636 if (cracked.grad) {
2637 params.gradX = arguments[2 + extraArgs];
2638 params.gradY = arguments[3 + extraArgs];
2639 extraArgs += 2;
2640 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002641
2642 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002643 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002644 params.offset = arguments[2 + extraArgs];
2645 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002646 } else if (cracked.offsets) {
2647 params.offsets = arguments[2 + extraArgs];
2648 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002649 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002650
2651 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002652 if (cracked.lodClamp) {
2653 params.lodClamp = arguments[2 + extraArgs];
2654 ++extraArgs;
2655 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002656
2657 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002658 if (sparse) {
2659 params.texelOut = arguments[2 + extraArgs];
2660 ++extraArgs;
2661 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002662
2663 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002664 if (bias) {
2665 params.bias = arguments[2 + extraArgs];
2666 ++extraArgs;
2667 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002668
2669 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002670 if (cracked.gather && ! sampler.shadow) {
2671 // default component is 0, if missing, otherwise an argument
2672 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002673 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002674 ++extraArgs;
2675 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002676 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002677 }
2678 }
John Kessenichfc51d282015-08-19 13:34:18 -06002679
John Kessenich019f08f2016-02-15 15:40:42 -07002680 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002681}
2682
2683spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2684{
2685 // Grab the function's pointer from the previously created function
2686 spv::Function* function = functionMap[node->getName().c_str()];
2687 if (! function)
2688 return 0;
2689
2690 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2691 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2692
2693 // See comments in makeFunctions() for details about the semantics for parameter passing.
2694 //
2695 // These imply we need a four step process:
2696 // 1. Evaluate the arguments
2697 // 2. Allocate and make copies of in, out, and inout arguments
2698 // 3. Make the call
2699 // 4. Copy back the results
2700
2701 // 1. Evaluate the arguments
2702 std::vector<spv::Builder::AccessChain> lValues;
2703 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002704 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002705 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002706 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002707 // build l-value
2708 builder.clearAccessChain();
2709 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002710 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002711 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2712 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002713 // save l-value
2714 lValues.push_back(builder.getAccessChain());
2715 } else {
2716 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002717 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002718 }
2719 }
2720
2721 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2722 // copy the original into that space.
2723 //
2724 // Also, build up the list of actual arguments to pass in for the call
2725 int lValueCount = 0;
2726 int rValueCount = 0;
2727 std::vector<spv::Id> spvArgs;
2728 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002729 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002730 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002731 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002732 builder.setAccessChain(lValues[lValueCount]);
2733 arg = builder.accessChainGetLValue();
2734 ++lValueCount;
2735 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002736 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002737 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2738 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2739 // need to copy the input into output space
2740 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002741 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002742 builder.createStore(copy, arg);
2743 }
2744 ++lValueCount;
2745 } else {
2746 arg = rValues[rValueCount];
2747 ++rValueCount;
2748 }
2749 spvArgs.push_back(arg);
2750 }
2751
2752 // 3. Make the call.
2753 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002754 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002755
2756 // 4. Copy back out an "out" arguments.
2757 lValueCount = 0;
2758 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2759 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2760 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2761 spv::Id copy = builder.createLoad(spvArgs[a]);
2762 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002763 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002764 }
2765 ++lValueCount;
2766 }
2767 }
2768
2769 return result;
2770}
2771
2772// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002773spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2774 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002775 spv::Id typeId, spv::Id left, spv::Id right,
2776 glslang::TBasicType typeProxy, bool reduceComparison)
2777{
Rex Xu8ff43de2016-04-22 16:51:45 +08002778 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002779 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002780 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002781
2782 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002783 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002784 bool comparison = false;
2785
2786 switch (op) {
2787 case glslang::EOpAdd:
2788 case glslang::EOpAddAssign:
2789 if (isFloat)
2790 binOp = spv::OpFAdd;
2791 else
2792 binOp = spv::OpIAdd;
2793 break;
2794 case glslang::EOpSub:
2795 case glslang::EOpSubAssign:
2796 if (isFloat)
2797 binOp = spv::OpFSub;
2798 else
2799 binOp = spv::OpISub;
2800 break;
2801 case glslang::EOpMul:
2802 case glslang::EOpMulAssign:
2803 if (isFloat)
2804 binOp = spv::OpFMul;
2805 else
2806 binOp = spv::OpIMul;
2807 break;
2808 case glslang::EOpVectorTimesScalar:
2809 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002810 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002811 if (builder.isVector(right))
2812 std::swap(left, right);
2813 assert(builder.isScalar(right));
2814 needMatchingVectors = false;
2815 binOp = spv::OpVectorTimesScalar;
2816 } else
2817 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002818 break;
2819 case glslang::EOpVectorTimesMatrix:
2820 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002821 binOp = spv::OpVectorTimesMatrix;
2822 break;
2823 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002824 binOp = spv::OpMatrixTimesVector;
2825 break;
2826 case glslang::EOpMatrixTimesScalar:
2827 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002828 binOp = spv::OpMatrixTimesScalar;
2829 break;
2830 case glslang::EOpMatrixTimesMatrix:
2831 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002832 binOp = spv::OpMatrixTimesMatrix;
2833 break;
2834 case glslang::EOpOuterProduct:
2835 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002836 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002837 break;
2838
2839 case glslang::EOpDiv:
2840 case glslang::EOpDivAssign:
2841 if (isFloat)
2842 binOp = spv::OpFDiv;
2843 else if (isUnsigned)
2844 binOp = spv::OpUDiv;
2845 else
2846 binOp = spv::OpSDiv;
2847 break;
2848 case glslang::EOpMod:
2849 case glslang::EOpModAssign:
2850 if (isFloat)
2851 binOp = spv::OpFMod;
2852 else if (isUnsigned)
2853 binOp = spv::OpUMod;
2854 else
2855 binOp = spv::OpSMod;
2856 break;
2857 case glslang::EOpRightShift:
2858 case glslang::EOpRightShiftAssign:
2859 if (isUnsigned)
2860 binOp = spv::OpShiftRightLogical;
2861 else
2862 binOp = spv::OpShiftRightArithmetic;
2863 break;
2864 case glslang::EOpLeftShift:
2865 case glslang::EOpLeftShiftAssign:
2866 binOp = spv::OpShiftLeftLogical;
2867 break;
2868 case glslang::EOpAnd:
2869 case glslang::EOpAndAssign:
2870 binOp = spv::OpBitwiseAnd;
2871 break;
2872 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002873 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002874 binOp = spv::OpLogicalAnd;
2875 break;
2876 case glslang::EOpInclusiveOr:
2877 case glslang::EOpInclusiveOrAssign:
2878 binOp = spv::OpBitwiseOr;
2879 break;
2880 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002881 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002882 binOp = spv::OpLogicalOr;
2883 break;
2884 case glslang::EOpExclusiveOr:
2885 case glslang::EOpExclusiveOrAssign:
2886 binOp = spv::OpBitwiseXor;
2887 break;
2888 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002889 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002890 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002891 break;
2892
2893 case glslang::EOpLessThan:
2894 case glslang::EOpGreaterThan:
2895 case glslang::EOpLessThanEqual:
2896 case glslang::EOpGreaterThanEqual:
2897 case glslang::EOpEqual:
2898 case glslang::EOpNotEqual:
2899 case glslang::EOpVectorEqual:
2900 case glslang::EOpVectorNotEqual:
2901 comparison = true;
2902 break;
2903 default:
2904 break;
2905 }
2906
John Kessenich7c1aa102015-10-15 13:29:11 -06002907 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002908 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002909 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002910 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002911 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002912
2913 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002914 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002915 builder.promoteScalar(precision, left, right);
2916
qining25262b32016-05-06 17:25:16 -04002917 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2918 addDecoration(result, noContraction);
2919 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002920 }
2921
2922 if (! comparison)
2923 return 0;
2924
John Kessenich7c1aa102015-10-15 13:29:11 -06002925 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002926
2927 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2928 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2929
John Kessenich22118352015-12-21 20:54:09 -07002930 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002931 }
2932
2933 switch (op) {
2934 case glslang::EOpLessThan:
2935 if (isFloat)
2936 binOp = spv::OpFOrdLessThan;
2937 else if (isUnsigned)
2938 binOp = spv::OpULessThan;
2939 else
2940 binOp = spv::OpSLessThan;
2941 break;
2942 case glslang::EOpGreaterThan:
2943 if (isFloat)
2944 binOp = spv::OpFOrdGreaterThan;
2945 else if (isUnsigned)
2946 binOp = spv::OpUGreaterThan;
2947 else
2948 binOp = spv::OpSGreaterThan;
2949 break;
2950 case glslang::EOpLessThanEqual:
2951 if (isFloat)
2952 binOp = spv::OpFOrdLessThanEqual;
2953 else if (isUnsigned)
2954 binOp = spv::OpULessThanEqual;
2955 else
2956 binOp = spv::OpSLessThanEqual;
2957 break;
2958 case glslang::EOpGreaterThanEqual:
2959 if (isFloat)
2960 binOp = spv::OpFOrdGreaterThanEqual;
2961 else if (isUnsigned)
2962 binOp = spv::OpUGreaterThanEqual;
2963 else
2964 binOp = spv::OpSGreaterThanEqual;
2965 break;
2966 case glslang::EOpEqual:
2967 case glslang::EOpVectorEqual:
2968 if (isFloat)
2969 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002970 else if (isBool)
2971 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 else
2973 binOp = spv::OpIEqual;
2974 break;
2975 case glslang::EOpNotEqual:
2976 case glslang::EOpVectorNotEqual:
2977 if (isFloat)
2978 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002979 else if (isBool)
2980 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002981 else
2982 binOp = spv::OpINotEqual;
2983 break;
2984 default:
2985 break;
2986 }
2987
qining25262b32016-05-06 17:25:16 -04002988 if (binOp != spv::OpNop) {
2989 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2990 addDecoration(result, noContraction);
2991 return builder.setPrecision(result, precision);
2992 }
John Kessenich140f3df2015-06-26 16:58:36 -06002993
2994 return 0;
2995}
2996
John Kessenich04bb8a02015-12-12 12:28:14 -07002997//
2998// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2999// These can be any of:
3000//
3001// matrix * scalar
3002// scalar * matrix
3003// matrix * matrix linear algebraic
3004// matrix * vector
3005// vector * matrix
3006// matrix * matrix componentwise
3007// matrix op matrix op in {+, -, /}
3008// matrix op scalar op in {+, -, /}
3009// scalar op matrix op in {+, -, /}
3010//
qining25262b32016-05-06 17:25:16 -04003011spv::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 -07003012{
3013 bool firstClass = true;
3014
3015 // First, handle first-class matrix operations (* and matrix/scalar)
3016 switch (op) {
3017 case spv::OpFDiv:
3018 if (builder.isMatrix(left) && builder.isScalar(right)) {
3019 // turn matrix / scalar into a multiply...
3020 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3021 op = spv::OpMatrixTimesScalar;
3022 } else
3023 firstClass = false;
3024 break;
3025 case spv::OpMatrixTimesScalar:
3026 if (builder.isMatrix(right))
3027 std::swap(left, right);
3028 assert(builder.isScalar(right));
3029 break;
3030 case spv::OpVectorTimesMatrix:
3031 assert(builder.isVector(left));
3032 assert(builder.isMatrix(right));
3033 break;
3034 case spv::OpMatrixTimesVector:
3035 assert(builder.isMatrix(left));
3036 assert(builder.isVector(right));
3037 break;
3038 case spv::OpMatrixTimesMatrix:
3039 assert(builder.isMatrix(left));
3040 assert(builder.isMatrix(right));
3041 break;
3042 default:
3043 firstClass = false;
3044 break;
3045 }
3046
qining25262b32016-05-06 17:25:16 -04003047 if (firstClass) {
3048 spv::Id result = builder.createBinOp(op, typeId, left, right);
3049 addDecoration(result, noContraction);
3050 return builder.setPrecision(result, precision);
3051 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003052
LoopDawg592860c2016-06-09 08:57:35 -06003053 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003054 // The result type of all of them is the same type as the (a) matrix operand.
3055 // The algorithm is to:
3056 // - break the matrix(es) into vectors
3057 // - smear any scalar to a vector
3058 // - do vector operations
3059 // - make a matrix out the vector results
3060 switch (op) {
3061 case spv::OpFAdd:
3062 case spv::OpFSub:
3063 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003064 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003065 case spv::OpFMul:
3066 {
3067 // one time set up...
3068 bool leftMat = builder.isMatrix(left);
3069 bool rightMat = builder.isMatrix(right);
3070 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3071 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3072 spv::Id scalarType = builder.getScalarTypeId(typeId);
3073 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3074 std::vector<spv::Id> results;
3075 spv::Id smearVec = spv::NoResult;
3076 if (builder.isScalar(left))
3077 smearVec = builder.smearScalar(precision, left, vecType);
3078 else if (builder.isScalar(right))
3079 smearVec = builder.smearScalar(precision, right, vecType);
3080
3081 // do each vector op
3082 for (unsigned int c = 0; c < numCols; ++c) {
3083 std::vector<unsigned int> indexes;
3084 indexes.push_back(c);
3085 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3086 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003087 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3088 addDecoration(result, noContraction);
3089 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003090 }
3091
3092 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003093 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003094 }
3095 default:
3096 assert(0);
3097 return spv::NoResult;
3098 }
3099}
3100
qining25262b32016-05-06 17:25:16 -04003101spv::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 -06003102{
3103 spv::Op unaryOp = spv::OpNop;
3104 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003105 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003106 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003107
3108 switch (op) {
3109 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003110 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003111 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003112 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003113 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003114 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003115 unaryOp = spv::OpSNegate;
3116 break;
3117
3118 case glslang::EOpLogicalNot:
3119 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 unaryOp = spv::OpLogicalNot;
3121 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003122 case glslang::EOpBitwiseNot:
3123 unaryOp = spv::OpNot;
3124 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003125
John Kessenich140f3df2015-06-26 16:58:36 -06003126 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003127 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003128 break;
3129 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003130 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003131 break;
3132 case glslang::EOpTranspose:
3133 unaryOp = spv::OpTranspose;
3134 break;
3135
3136 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003137 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 break;
3139 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003140 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003141 break;
3142 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003143 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003144 break;
3145 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003146 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003147 break;
3148 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003149 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003152 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003153 break;
3154 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003155 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160
3161 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003162 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003168 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003171 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003172 break;
3173 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003174 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003175 break;
3176 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003177 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003178 break;
3179
3180 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003181 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003182 break;
3183 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003184 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 break;
3186
3187 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003188 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003189 break;
3190 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003191 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003192 break;
3193 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003194 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003195 break;
3196 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003197 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003198 break;
3199 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003200 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003201 break;
3202 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003203 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003204 break;
3205
3206 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003208 break;
3209 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003210 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003211 break;
3212 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003213 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003214 break;
3215 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003216 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003217 break;
3218 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003219 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003220 break;
3221 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003222 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003223 break;
3224
3225 case glslang::EOpIsNan:
3226 unaryOp = spv::OpIsNan;
3227 break;
3228 case glslang::EOpIsInf:
3229 unaryOp = spv::OpIsInf;
3230 break;
LoopDawg592860c2016-06-09 08:57:35 -06003231 case glslang::EOpIsFinite:
3232 unaryOp = spv::OpIsFinite;
3233 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003234
Rex Xucbc426e2015-12-15 16:03:10 +08003235 case glslang::EOpFloatBitsToInt:
3236 case glslang::EOpFloatBitsToUint:
3237 case glslang::EOpIntBitsToFloat:
3238 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003239 case glslang::EOpDoubleBitsToInt64:
3240 case glslang::EOpDoubleBitsToUint64:
3241 case glslang::EOpInt64BitsToDouble:
3242 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003243 unaryOp = spv::OpBitcast;
3244 break;
3245
John Kessenich140f3df2015-06-26 16:58:36 -06003246 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003247 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003248 break;
3249 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003250 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003251 break;
3252 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003253 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003254 break;
3255 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003256 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003257 break;
3258 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003259 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003260 break;
3261 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003262 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003263 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003264 case glslang::EOpPackSnorm4x8:
3265 libCall = spv::GLSLstd450PackSnorm4x8;
3266 break;
3267 case glslang::EOpUnpackSnorm4x8:
3268 libCall = spv::GLSLstd450UnpackSnorm4x8;
3269 break;
3270 case glslang::EOpPackUnorm4x8:
3271 libCall = spv::GLSLstd450PackUnorm4x8;
3272 break;
3273 case glslang::EOpUnpackUnorm4x8:
3274 libCall = spv::GLSLstd450UnpackUnorm4x8;
3275 break;
3276 case glslang::EOpPackDouble2x32:
3277 libCall = spv::GLSLstd450PackDouble2x32;
3278 break;
3279 case glslang::EOpUnpackDouble2x32:
3280 libCall = spv::GLSLstd450UnpackDouble2x32;
3281 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003282
Rex Xu8ff43de2016-04-22 16:51:45 +08003283 case glslang::EOpPackInt2x32:
3284 case glslang::EOpUnpackInt2x32:
3285 case glslang::EOpPackUint2x32:
3286 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003287 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003288 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3289 break;
3290
John Kessenich140f3df2015-06-26 16:58:36 -06003291 case glslang::EOpDPdx:
3292 unaryOp = spv::OpDPdx;
3293 break;
3294 case glslang::EOpDPdy:
3295 unaryOp = spv::OpDPdy;
3296 break;
3297 case glslang::EOpFwidth:
3298 unaryOp = spv::OpFwidth;
3299 break;
3300 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003301 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003302 unaryOp = spv::OpDPdxFine;
3303 break;
3304 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003305 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003306 unaryOp = spv::OpDPdyFine;
3307 break;
3308 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003309 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003310 unaryOp = spv::OpFwidthFine;
3311 break;
3312 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003313 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003314 unaryOp = spv::OpDPdxCoarse;
3315 break;
3316 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003317 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003318 unaryOp = spv::OpDPdyCoarse;
3319 break;
3320 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003321 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003322 unaryOp = spv::OpFwidthCoarse;
3323 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003324 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003325 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003326 libCall = spv::GLSLstd450InterpolateAtCentroid;
3327 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003328 case glslang::EOpAny:
3329 unaryOp = spv::OpAny;
3330 break;
3331 case glslang::EOpAll:
3332 unaryOp = spv::OpAll;
3333 break;
3334
3335 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003336 if (isFloat)
3337 libCall = spv::GLSLstd450FAbs;
3338 else
3339 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003340 break;
3341 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003342 if (isFloat)
3343 libCall = spv::GLSLstd450FSign;
3344 else
3345 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003346 break;
3347
John Kessenichfc51d282015-08-19 13:34:18 -06003348 case glslang::EOpAtomicCounterIncrement:
3349 case glslang::EOpAtomicCounterDecrement:
3350 case glslang::EOpAtomicCounter:
3351 {
3352 // Handle all of the atomics in one place, in createAtomicOperation()
3353 std::vector<spv::Id> operands;
3354 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003355 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003356 }
3357
John Kessenichfc51d282015-08-19 13:34:18 -06003358 case glslang::EOpBitFieldReverse:
3359 unaryOp = spv::OpBitReverse;
3360 break;
3361 case glslang::EOpBitCount:
3362 unaryOp = spv::OpBitCount;
3363 break;
3364 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003365 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003366 break;
3367 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003368 if (isUnsigned)
3369 libCall = spv::GLSLstd450FindUMsb;
3370 else
3371 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003372 break;
3373
Rex Xu574ab042016-04-14 16:53:07 +08003374 case glslang::EOpBallot:
3375 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003376 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003377 libCall = spv::GLSLstd450Bad;
3378 break;
3379
Rex Xu338b1852016-05-05 20:38:33 +08003380 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003381 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003382 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003383 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003384
John Kessenich140f3df2015-06-26 16:58:36 -06003385 default:
3386 return 0;
3387 }
3388
3389 spv::Id id;
3390 if (libCall >= 0) {
3391 std::vector<spv::Id> args;
3392 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003393 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003394 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003395 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003396 }
John Kessenich140f3df2015-06-26 16:58:36 -06003397
qining25262b32016-05-06 17:25:16 -04003398 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003399 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003400}
3401
John Kessenich7a53f762016-01-20 11:19:27 -07003402// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003403spv::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 -07003404{
3405 // Handle unary operations vector by vector.
3406 // The result type is the same type as the original type.
3407 // The algorithm is to:
3408 // - break the matrix into vectors
3409 // - apply the operation to each vector
3410 // - make a matrix out the vector results
3411
3412 // get the types sorted out
3413 int numCols = builder.getNumColumns(operand);
3414 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003415 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3416 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003417 std::vector<spv::Id> results;
3418
3419 // do each vector op
3420 for (int c = 0; c < numCols; ++c) {
3421 std::vector<unsigned int> indexes;
3422 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003423 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3424 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3425 addDecoration(destVec, noContraction);
3426 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003427 }
3428
3429 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003430 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003431}
3432
Rex Xu73e3ce72016-04-27 18:48:17 +08003433spv::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 -06003434{
3435 spv::Op convOp = spv::OpNop;
3436 spv::Id zero = 0;
3437 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003438 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003439
3440 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3441
3442 switch (op) {
3443 case glslang::EOpConvIntToBool:
3444 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003445 case glslang::EOpConvInt64ToBool:
3446 case glslang::EOpConvUint64ToBool:
3447 zero = (op == glslang::EOpConvInt64ToBool ||
3448 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003449 zero = makeSmearedConstant(zero, vectorSize);
3450 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3451
3452 case glslang::EOpConvFloatToBool:
3453 zero = builder.makeFloatConstant(0.0F);
3454 zero = makeSmearedConstant(zero, vectorSize);
3455 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3456
3457 case glslang::EOpConvDoubleToBool:
3458 zero = builder.makeDoubleConstant(0.0);
3459 zero = makeSmearedConstant(zero, vectorSize);
3460 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3461
3462 case glslang::EOpConvBoolToFloat:
3463 convOp = spv::OpSelect;
3464 zero = builder.makeFloatConstant(0.0);
3465 one = builder.makeFloatConstant(1.0);
3466 break;
3467 case glslang::EOpConvBoolToDouble:
3468 convOp = spv::OpSelect;
3469 zero = builder.makeDoubleConstant(0.0);
3470 one = builder.makeDoubleConstant(1.0);
3471 break;
3472 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003473 case glslang::EOpConvBoolToInt64:
3474 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3475 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003476 convOp = spv::OpSelect;
3477 break;
3478 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003479 case glslang::EOpConvBoolToUint64:
3480 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3481 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003482 convOp = spv::OpSelect;
3483 break;
3484
3485 case glslang::EOpConvIntToFloat:
3486 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003487 case glslang::EOpConvInt64ToFloat:
3488 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003489 convOp = spv::OpConvertSToF;
3490 break;
3491
3492 case glslang::EOpConvUintToFloat:
3493 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003494 case glslang::EOpConvUint64ToFloat:
3495 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003496 convOp = spv::OpConvertUToF;
3497 break;
3498
3499 case glslang::EOpConvDoubleToFloat:
3500 case glslang::EOpConvFloatToDouble:
3501 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003502 if (builder.isMatrixType(destType))
3503 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003504 break;
3505
3506 case glslang::EOpConvFloatToInt:
3507 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003508 case glslang::EOpConvFloatToInt64:
3509 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003510 convOp = spv::OpConvertFToS;
3511 break;
3512
3513 case glslang::EOpConvUintToInt:
3514 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003515 case glslang::EOpConvUint64ToInt64:
3516 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003517 if (builder.isInSpecConstCodeGenMode()) {
3518 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003519 zero = (op == glslang::EOpConvUintToInt64 ||
3520 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003521 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003522 // Use OpIAdd, instead of OpBitcast to do the conversion when
3523 // generating for OpSpecConstantOp instruction.
3524 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3525 }
3526 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003527 convOp = spv::OpBitcast;
3528 break;
3529
3530 case glslang::EOpConvFloatToUint:
3531 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003532 case glslang::EOpConvFloatToUint64:
3533 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003534 convOp = spv::OpConvertFToU;
3535 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003536
3537 case glslang::EOpConvIntToInt64:
3538 case glslang::EOpConvInt64ToInt:
3539 convOp = spv::OpSConvert;
3540 break;
3541
3542 case glslang::EOpConvUintToUint64:
3543 case glslang::EOpConvUint64ToUint:
3544 convOp = spv::OpUConvert;
3545 break;
3546
3547 case glslang::EOpConvIntToUint64:
3548 case glslang::EOpConvInt64ToUint:
3549 case glslang::EOpConvUint64ToInt:
3550 case glslang::EOpConvUintToInt64:
3551 // OpSConvert/OpUConvert + OpBitCast
3552 switch (op) {
3553 case glslang::EOpConvIntToUint64:
3554 convOp = spv::OpSConvert;
3555 type = builder.makeIntType(64);
3556 break;
3557 case glslang::EOpConvInt64ToUint:
3558 convOp = spv::OpSConvert;
3559 type = builder.makeIntType(32);
3560 break;
3561 case glslang::EOpConvUint64ToInt:
3562 convOp = spv::OpUConvert;
3563 type = builder.makeUintType(32);
3564 break;
3565 case glslang::EOpConvUintToInt64:
3566 convOp = spv::OpUConvert;
3567 type = builder.makeUintType(64);
3568 break;
3569 default:
3570 assert(0);
3571 break;
3572 }
3573
3574 if (vectorSize > 0)
3575 type = builder.makeVectorType(type, vectorSize);
3576
3577 operand = builder.createUnaryOp(convOp, type, operand);
3578
3579 if (builder.isInSpecConstCodeGenMode()) {
3580 // Build zero scalar or vector for OpIAdd.
3581 zero = (op == glslang::EOpConvIntToUint64 ||
3582 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3583 zero = makeSmearedConstant(zero, vectorSize);
3584 // Use OpIAdd, instead of OpBitcast to do the conversion when
3585 // generating for OpSpecConstantOp instruction.
3586 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3587 }
3588 // For normal run-time conversion instruction, use OpBitcast.
3589 convOp = spv::OpBitcast;
3590 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003591 default:
3592 break;
3593 }
3594
3595 spv::Id result = 0;
3596 if (convOp == spv::OpNop)
3597 return result;
3598
3599 if (convOp == spv::OpSelect) {
3600 zero = makeSmearedConstant(zero, vectorSize);
3601 one = makeSmearedConstant(one, vectorSize);
3602 result = builder.createTriOp(convOp, destType, operand, one, zero);
3603 } else
3604 result = builder.createUnaryOp(convOp, destType, operand);
3605
John Kessenich32cfd492016-02-02 12:37:46 -07003606 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003607}
3608
3609spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3610{
3611 if (vectorSize == 0)
3612 return constant;
3613
3614 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3615 std::vector<spv::Id> components;
3616 for (int c = 0; c < vectorSize; ++c)
3617 components.push_back(constant);
3618 return builder.makeCompositeConstant(vectorTypeId, components);
3619}
3620
John Kessenich426394d2015-07-23 10:22:48 -06003621// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003622spv::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 -06003623{
3624 spv::Op opCode = spv::OpNop;
3625
3626 switch (op) {
3627 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003628 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003629 opCode = spv::OpAtomicIAdd;
3630 break;
3631 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003632 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003633 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003634 break;
3635 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003636 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003637 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003638 break;
3639 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003640 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003641 opCode = spv::OpAtomicAnd;
3642 break;
3643 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003644 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003645 opCode = spv::OpAtomicOr;
3646 break;
3647 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003648 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003649 opCode = spv::OpAtomicXor;
3650 break;
3651 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003652 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003653 opCode = spv::OpAtomicExchange;
3654 break;
3655 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003656 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003657 opCode = spv::OpAtomicCompareExchange;
3658 break;
3659 case glslang::EOpAtomicCounterIncrement:
3660 opCode = spv::OpAtomicIIncrement;
3661 break;
3662 case glslang::EOpAtomicCounterDecrement:
3663 opCode = spv::OpAtomicIDecrement;
3664 break;
3665 case glslang::EOpAtomicCounter:
3666 opCode = spv::OpAtomicLoad;
3667 break;
3668 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003669 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003670 break;
3671 }
3672
3673 // Sort out the operands
3674 // - mapping from glslang -> SPV
3675 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003676 // - compare-exchange swaps the value and comparator
3677 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003678 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3679 auto opIt = operands.begin(); // walk the glslang operands
3680 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003681 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3682 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3683 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003684 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3685 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003686 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003687 spvAtomicOperands.push_back(*(opIt + 1));
3688 spvAtomicOperands.push_back(*opIt);
3689 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003690 }
John Kessenich426394d2015-07-23 10:22:48 -06003691
John Kessenich3e60a6f2015-09-14 22:45:16 -06003692 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003693 for (; opIt != operands.end(); ++opIt)
3694 spvAtomicOperands.push_back(*opIt);
3695
3696 return builder.createOp(opCode, typeId, spvAtomicOperands);
3697}
3698
John Kessenich91cef522016-05-05 16:45:40 -06003699// Create group invocation operations.
3700spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3701{
3702 builder.addCapability(spv::CapabilityGroups);
3703
3704 std::vector<spv::Id> operands;
3705 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3706 operands.push_back(operand);
3707
3708 switch (op) {
3709 case glslang::EOpAnyInvocation:
3710 case glslang::EOpAllInvocations:
3711 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3712
3713 case glslang::EOpAllInvocationsEqual:
3714 {
3715 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3716 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3717
3718 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3719 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3720 }
3721 default:
3722 logger->missingFunctionality("invocation operation");
3723 return spv::NoResult;
3724 }
3725}
3726
John Kessenich5e4b1242015-08-06 22:53:06 -06003727spv::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 -06003728{
Rex Xu8ff43de2016-04-22 16:51:45 +08003729 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003730 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3731
John Kessenich140f3df2015-06-26 16:58:36 -06003732 spv::Op opCode = spv::OpNop;
3733 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003734 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003735 spv::Id typeId0 = 0;
3736 if (consumedOperands > 0)
3737 typeId0 = builder.getTypeId(operands[0]);
3738 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003739
3740 switch (op) {
3741 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003742 if (isFloat)
3743 libCall = spv::GLSLstd450FMin;
3744 else if (isUnsigned)
3745 libCall = spv::GLSLstd450UMin;
3746 else
3747 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003748 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 if (isFloat)
3755 libCall = spv::GLSLstd450FMax;
3756 else if (isUnsigned)
3757 libCall = spv::GLSLstd450UMax;
3758 else
3759 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003760 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003761 break;
3762 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003763 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003764 break;
3765 case glslang::EOpDot:
3766 opCode = spv::OpDot;
3767 break;
3768 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003769 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003770 break;
3771
3772 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 if (isFloat)
3774 libCall = spv::GLSLstd450FClamp;
3775 else if (isUnsigned)
3776 libCall = spv::GLSLstd450UClamp;
3777 else
3778 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003779 builder.promoteScalar(precision, operands.front(), operands[1]);
3780 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003783 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3784 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003785 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003786 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003787 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003788 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003789 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003790 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003791 break;
3792 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003794 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003795 break;
3796 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003798 builder.promoteScalar(precision, operands[0], operands[2]);
3799 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003800 break;
3801
3802 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003803 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003804 break;
3805 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003806 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003807 break;
3808 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003810 break;
3811 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003812 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003813 break;
3814 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003815 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003817 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003818 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003819 libCall = spv::GLSLstd450InterpolateAtSample;
3820 break;
3821 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003822 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003823 libCall = spv::GLSLstd450InterpolateAtOffset;
3824 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003825 case glslang::EOpAddCarry:
3826 opCode = spv::OpIAddCarry;
3827 typeId = builder.makeStructResultType(typeId0, typeId0);
3828 consumedOperands = 2;
3829 break;
3830 case glslang::EOpSubBorrow:
3831 opCode = spv::OpISubBorrow;
3832 typeId = builder.makeStructResultType(typeId0, typeId0);
3833 consumedOperands = 2;
3834 break;
3835 case glslang::EOpUMulExtended:
3836 opCode = spv::OpUMulExtended;
3837 typeId = builder.makeStructResultType(typeId0, typeId0);
3838 consumedOperands = 2;
3839 break;
3840 case glslang::EOpIMulExtended:
3841 opCode = spv::OpSMulExtended;
3842 typeId = builder.makeStructResultType(typeId0, typeId0);
3843 consumedOperands = 2;
3844 break;
3845 case glslang::EOpBitfieldExtract:
3846 if (isUnsigned)
3847 opCode = spv::OpBitFieldUExtract;
3848 else
3849 opCode = spv::OpBitFieldSExtract;
3850 break;
3851 case glslang::EOpBitfieldInsert:
3852 opCode = spv::OpBitFieldInsert;
3853 break;
3854
3855 case glslang::EOpFma:
3856 libCall = spv::GLSLstd450Fma;
3857 break;
3858 case glslang::EOpFrexp:
3859 libCall = spv::GLSLstd450FrexpStruct;
3860 if (builder.getNumComponents(operands[0]) == 1)
3861 frexpIntType = builder.makeIntegerType(32, true);
3862 else
3863 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3864 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3865 consumedOperands = 1;
3866 break;
3867 case glslang::EOpLdexp:
3868 libCall = spv::GLSLstd450Ldexp;
3869 break;
3870
Rex Xu574ab042016-04-14 16:53:07 +08003871 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003872 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003873 libCall = spv::GLSLstd450Bad;
3874 break;
3875
John Kessenich140f3df2015-06-26 16:58:36 -06003876 default:
3877 return 0;
3878 }
3879
3880 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003881 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003882 // Use an extended instruction from the standard library.
3883 // Construct the call arguments, without modifying the original operands vector.
3884 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3885 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003886 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003887 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003888 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003889 case 0:
3890 // should all be handled by visitAggregate and createNoArgOperation
3891 assert(0);
3892 return 0;
3893 case 1:
3894 // should all be handled by createUnaryOperation
3895 assert(0);
3896 return 0;
3897 case 2:
3898 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3899 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003900 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003901 // anything 3 or over doesn't have l-value operands, so all should be consumed
3902 assert(consumedOperands == operands.size());
3903 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003904 break;
3905 }
3906 }
3907
John Kessenich55e7d112015-11-15 21:33:39 -07003908 // Decode the return types that were structures
3909 switch (op) {
3910 case glslang::EOpAddCarry:
3911 case glslang::EOpSubBorrow:
3912 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3913 id = builder.createCompositeExtract(id, typeId0, 0);
3914 break;
3915 case glslang::EOpUMulExtended:
3916 case glslang::EOpIMulExtended:
3917 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3918 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3919 break;
3920 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003921 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003922 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3923 id = builder.createCompositeExtract(id, typeId0, 0);
3924 break;
3925 default:
3926 break;
3927 }
3928
John Kessenich32cfd492016-02-02 12:37:46 -07003929 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003930}
3931
3932// Intrinsics with no arguments, no return value, and no precision.
3933spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3934{
3935 // TODO: get the barrier operands correct
3936
3937 switch (op) {
3938 case glslang::EOpEmitVertex:
3939 builder.createNoResultOp(spv::OpEmitVertex);
3940 return 0;
3941 case glslang::EOpEndPrimitive:
3942 builder.createNoResultOp(spv::OpEndPrimitive);
3943 return 0;
3944 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003945 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003946 return 0;
3947 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003948 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003949 return 0;
3950 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003951 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003952 return 0;
3953 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003954 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003955 return 0;
3956 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003957 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003958 return 0;
3959 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003960 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003961 return 0;
3962 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003963 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003964 return 0;
3965 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003966 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003967 return 0;
3968 }
3969}
3970
3971spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3972{
John Kessenich2f273362015-07-18 22:34:27 -06003973 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003974 spv::Id id;
3975 if (symbolValues.end() != iter) {
3976 id = iter->second;
3977 return id;
3978 }
3979
3980 // it was not found, create it
3981 id = createSpvVariable(symbol);
3982 symbolValues[symbol->getId()] = id;
3983
3984 if (! symbol->getType().isStruct()) {
3985 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003986 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08003987 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003988 if (symbol->getType().getQualifier().hasSpecConstantId())
3989 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003990 if (symbol->getQualifier().hasIndex())
3991 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3992 if (symbol->getQualifier().hasComponent())
3993 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3994 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003995 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003996 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003997 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003998 if (symbol->getQualifier().hasXfbBuffer())
3999 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4000 if (symbol->getQualifier().hasXfbOffset())
4001 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4002 }
4003 }
4004
scygan2c864272016-05-18 18:09:17 +02004005 if (symbol->getQualifier().hasLocation())
4006 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004007 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004008 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004009 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004010 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004011 }
John Kessenich140f3df2015-06-26 16:58:36 -06004012 if (symbol->getQualifier().hasSet())
4013 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004014 else if (IsDescriptorResource(symbol->getType())) {
4015 // default to 0
4016 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4017 }
John Kessenich140f3df2015-06-26 16:58:36 -06004018 if (symbol->getQualifier().hasBinding())
4019 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004020 if (symbol->getQualifier().hasAttachment())
4021 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004022 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004023 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004024 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004025 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004026 if (symbol->getQualifier().hasXfbBuffer())
4027 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4028 }
4029
Rex Xu1da878f2016-02-21 20:59:01 +08004030 if (symbol->getType().isImage()) {
4031 std::vector<spv::Decoration> memory;
4032 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4033 for (unsigned int i = 0; i < memory.size(); ++i)
4034 addDecoration(id, memory[i]);
4035 }
4036
John Kessenich140f3df2015-06-26 16:58:36 -06004037 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004038 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06004039 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07004040 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004041
John Kessenich140f3df2015-06-26 16:58:36 -06004042 return id;
4043}
4044
John Kessenich55e7d112015-11-15 21:33:39 -07004045// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004046void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4047{
4048 if (dec != spv::BadValue)
4049 builder.addDecoration(id, dec);
4050}
4051
John Kessenich55e7d112015-11-15 21:33:39 -07004052// If 'dec' is valid, add a one-operand decoration to an object
4053void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4054{
4055 if (dec != spv::BadValue)
4056 builder.addDecoration(id, dec, value);
4057}
4058
4059// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004060void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4061{
4062 if (dec != spv::BadValue)
4063 builder.addMemberDecoration(id, (unsigned)member, dec);
4064}
4065
John Kessenich92187592016-02-01 13:45:25 -07004066// If 'dec' is valid, add a one-operand decoration to a struct member
4067void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4068{
4069 if (dec != spv::BadValue)
4070 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4071}
4072
John Kessenich55e7d112015-11-15 21:33:39 -07004073// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004074// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004075//
4076// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4077//
4078// Recursively walk the nodes. The nodes form a tree whose leaves are
4079// regular constants, which themselves are trees that createSpvConstant()
4080// recursively walks. So, this function walks the "top" of the tree:
4081// - emit specialization constant-building instructions for specConstant
4082// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004083spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004084{
John Kessenich7cc0e282016-03-20 00:46:02 -06004085 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004086
qining4f4bb812016-04-03 23:55:17 -04004087 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004088 if (! node.getQualifier().specConstant) {
4089 // hand off to the non-spec-constant path
4090 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4091 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004092 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004093 nextConst, false);
4094 }
4095
4096 // We now know we have a specialization constant to build
4097
John Kessenichd94c0032016-05-30 19:29:40 -06004098 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004099 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4100 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4101 std::vector<spv::Id> dimConstId;
4102 for (int dim = 0; dim < 3; ++dim) {
4103 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4104 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4105 if (specConst)
4106 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4107 }
4108 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4109 }
4110
4111 // An AST node labelled as specialization constant should be a symbol node.
4112 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4113 if (auto* sn = node.getAsSymbolNode()) {
4114 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004115 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4116 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4117 // will set the builder into spec constant op instruction generating mode.
4118 sub_tree->traverse(this);
4119 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004120 } else if (auto* const_union_array = &sn->getConstArray()){
4121 int nextConst = 0;
4122 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004123 }
4124 }
qining4f4bb812016-04-03 23:55:17 -04004125
4126 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4127 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004128 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004129 exit(1);
4130 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004131}
4132
John Kessenich140f3df2015-06-26 16:58:36 -06004133// Use 'consts' as the flattened glslang source of scalar constants to recursively
4134// build the aggregate SPIR-V constant.
4135//
4136// If there are not enough elements present in 'consts', 0 will be substituted;
4137// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4138//
qining08408382016-03-21 09:51:37 -04004139spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004140{
4141 // vector of constants for SPIR-V
4142 std::vector<spv::Id> spvConsts;
4143
4144 // Type is used for struct and array constants
4145 spv::Id typeId = convertGlslangToSpvType(glslangType);
4146
4147 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004148 glslang::TType elementType(glslangType, 0);
4149 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004150 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004151 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004152 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004153 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004154 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004155 } else if (glslangType.getStruct()) {
4156 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4157 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004158 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004159 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004160 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4161 bool zero = nextConst >= consts.size();
4162 switch (glslangType.getBasicType()) {
4163 case glslang::EbtInt:
4164 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4165 break;
4166 case glslang::EbtUint:
4167 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4168 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004169 case glslang::EbtInt64:
4170 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4171 break;
4172 case glslang::EbtUint64:
4173 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4174 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004175 case glslang::EbtFloat:
4176 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4177 break;
4178 case glslang::EbtDouble:
4179 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4180 break;
4181 case glslang::EbtBool:
4182 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4183 break;
4184 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004185 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004186 break;
4187 }
4188 ++nextConst;
4189 }
4190 } else {
4191 // we have a non-aggregate (scalar) constant
4192 bool zero = nextConst >= consts.size();
4193 spv::Id scalar = 0;
4194 switch (glslangType.getBasicType()) {
4195 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004196 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004197 break;
4198 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004199 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004200 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004201 case glslang::EbtInt64:
4202 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4203 break;
4204 case glslang::EbtUint64:
4205 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4206 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004207 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004208 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004209 break;
4210 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004211 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004212 break;
4213 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004214 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004215 break;
4216 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004218 break;
4219 }
4220 ++nextConst;
4221 return scalar;
4222 }
4223
4224 return builder.makeCompositeConstant(typeId, spvConsts);
4225}
4226
John Kessenich7c1aa102015-10-15 13:29:11 -06004227// Return true if the node is a constant or symbol whose reading has no
4228// non-trivial observable cost or effect.
4229bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4230{
4231 // don't know what this is
4232 if (node == nullptr)
4233 return false;
4234
4235 // a constant is safe
4236 if (node->getAsConstantUnion() != nullptr)
4237 return true;
4238
4239 // not a symbol means non-trivial
4240 if (node->getAsSymbolNode() == nullptr)
4241 return false;
4242
4243 // a symbol, depends on what's being read
4244 switch (node->getType().getQualifier().storage) {
4245 case glslang::EvqTemporary:
4246 case glslang::EvqGlobal:
4247 case glslang::EvqIn:
4248 case glslang::EvqInOut:
4249 case glslang::EvqConst:
4250 case glslang::EvqConstReadOnly:
4251 case glslang::EvqUniform:
4252 return true;
4253 default:
4254 return false;
4255 }
qining25262b32016-05-06 17:25:16 -04004256}
John Kessenich7c1aa102015-10-15 13:29:11 -06004257
4258// A node is trivial if it is a single operation with no side effects.
4259// Error on the side of saying non-trivial.
4260// Return true if trivial.
4261bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4262{
4263 if (node == nullptr)
4264 return false;
4265
4266 // symbols and constants are trivial
4267 if (isTrivialLeaf(node))
4268 return true;
4269
4270 // otherwise, it needs to be a simple operation or one or two leaf nodes
4271
4272 // not a simple operation
4273 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4274 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4275 if (binaryNode == nullptr && unaryNode == nullptr)
4276 return false;
4277
4278 // not on leaf nodes
4279 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4280 return false;
4281
4282 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4283 return false;
4284 }
4285
4286 switch (node->getAsOperator()->getOp()) {
4287 case glslang::EOpLogicalNot:
4288 case glslang::EOpConvIntToBool:
4289 case glslang::EOpConvUintToBool:
4290 case glslang::EOpConvFloatToBool:
4291 case glslang::EOpConvDoubleToBool:
4292 case glslang::EOpEqual:
4293 case glslang::EOpNotEqual:
4294 case glslang::EOpLessThan:
4295 case glslang::EOpGreaterThan:
4296 case glslang::EOpLessThanEqual:
4297 case glslang::EOpGreaterThanEqual:
4298 case glslang::EOpIndexDirect:
4299 case glslang::EOpIndexDirectStruct:
4300 case glslang::EOpLogicalXor:
4301 case glslang::EOpAny:
4302 case glslang::EOpAll:
4303 return true;
4304 default:
4305 return false;
4306 }
4307}
4308
4309// Emit short-circuiting code, where 'right' is never evaluated unless
4310// the left side is true (for &&) or false (for ||).
4311spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4312{
4313 spv::Id boolTypeId = builder.makeBoolType();
4314
4315 // emit left operand
4316 builder.clearAccessChain();
4317 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004318 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004319
4320 // Operands to accumulate OpPhi operands
4321 std::vector<spv::Id> phiOperands;
4322 // accumulate left operand's phi information
4323 phiOperands.push_back(leftId);
4324 phiOperands.push_back(builder.getBuildPoint()->getId());
4325
4326 // Make the two kinds of operation symmetric with a "!"
4327 // || => emit "if (! left) result = right"
4328 // && => emit "if ( left) result = right"
4329 //
4330 // TODO: this runtime "not" for || could be avoided by adding functionality
4331 // to 'builder' to have an "else" without an "then"
4332 if (op == glslang::EOpLogicalOr)
4333 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4334
4335 // make an "if" based on the left value
4336 spv::Builder::If ifBuilder(leftId, builder);
4337
4338 // emit right operand as the "then" part of the "if"
4339 builder.clearAccessChain();
4340 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004341 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004342
4343 // accumulate left operand's phi information
4344 phiOperands.push_back(rightId);
4345 phiOperands.push_back(builder.getBuildPoint()->getId());
4346
4347 // finish the "if"
4348 ifBuilder.makeEndIf();
4349
4350 // phi together the two results
4351 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4352}
4353
John Kessenich140f3df2015-06-26 16:58:36 -06004354}; // end anonymous namespace
4355
4356namespace glslang {
4357
John Kessenich68d78fd2015-07-12 19:28:10 -06004358void GetSpirvVersion(std::string& version)
4359{
John Kessenich9e55f632015-07-15 10:03:39 -06004360 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004361 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004362 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004363 version = buf;
4364}
4365
John Kessenich140f3df2015-06-26 16:58:36 -06004366// Write SPIR-V out to a binary file
4367void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4368{
4369 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004370 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004371 for (int i = 0; i < (int)spirv.size(); ++i) {
4372 unsigned int word = spirv[i];
4373 out.write((const char*)&word, 4);
4374 }
4375 out.close();
4376}
4377
4378//
4379// Set up the glslang traversal
4380//
4381void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4382{
Lei Zhang17535f72016-05-04 15:55:59 -04004383 spv::SpvBuildLogger logger;
4384 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004385}
4386
Lei Zhang17535f72016-05-04 15:55:59 -04004387void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004388{
John Kessenich140f3df2015-06-26 16:58:36 -06004389 TIntermNode* root = intermediate.getTreeRoot();
4390
4391 if (root == 0)
4392 return;
4393
4394 glslang::GetThreadPoolAllocator().push();
4395
Lei Zhang17535f72016-05-04 15:55:59 -04004396 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004397
4398 root->traverse(&it);
4399
4400 it.dumpSpv(spirv);
4401
4402 glslang::GetThreadPoolAllocator().pop();
4403}
4404
4405}; // end namespace glslang