blob: 22575b5a53d4af8939e81103b182aee4cc0be7b4 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//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:
John Kessenich5e801132016-02-15 11:09:46 -0700111 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -0700112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
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);
John Kessenich140f3df2015-06-26 16:58:36 -0600125
126 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
127 void makeFunctions(const glslang::TIntermSequence&);
128 void makeGlobalInitializers(const glslang::TIntermSequence&);
129 void visitFunctions(const glslang::TIntermSequence&);
130 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800131 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600132 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
133 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600134 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
135
qining25262b32016-05-06 17:25:16 -0400136 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);
137 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
138 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
139 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600140 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
141 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800142 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 -0600143 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600144 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 -0600145 spv::Id createNoArgOperation(glslang::TOperator op);
146 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
147 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700148 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600149 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400151 spv::Id createSpvConstant(const glslang::TIntermTyped&);
152 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600153 bool isTrivialLeaf(const glslang::TIntermTyped* node);
154 bool isTrivial(const glslang::TIntermTyped* node);
155 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600156
157 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700158 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600159 int sequenceDepth;
160
Lei Zhang17535f72016-05-04 15:55:59 -0400161 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400162
John Kessenich140f3df2015-06-26 16:58:36 -0600163 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
164 spv::Builder builder;
165 bool inMain;
166 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700167 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 -0700168 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600169 const glslang::TIntermediate* glslangIntermediate;
170 spv::Id stdBuiltins;
171
John Kessenich2f273362015-07-18 22:34:27 -0600172 std::unordered_map<int, spv::Id> symbolValues;
173 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
174 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700175 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600176 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 -0600177 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600178};
179
180//
181// Helper functions for translating glslang representations to SPIR-V enumerants.
182//
183
184// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700185spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600186{
John Kessenich66e2faf2016-03-12 18:34:36 -0700187 switch (source) {
188 case glslang::EShSourceGlsl:
189 switch (profile) {
190 case ENoProfile:
191 case ECoreProfile:
192 case ECompatibilityProfile:
193 return spv::SourceLanguageGLSL;
194 case EEsProfile:
195 return spv::SourceLanguageESSL;
196 default:
197 return spv::SourceLanguageUnknown;
198 }
199 case glslang::EShSourceHlsl:
200 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600201 default:
202 return spv::SourceLanguageUnknown;
203 }
204}
205
206// Translate glslang language (stage) to SPIR-V execution model.
207spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
208{
209 switch (stage) {
210 case EShLangVertex: return spv::ExecutionModelVertex;
211 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
212 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
213 case EShLangGeometry: return spv::ExecutionModelGeometry;
214 case EShLangFragment: return spv::ExecutionModelFragment;
215 case EShLangCompute: return spv::ExecutionModelGLCompute;
216 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600218 return spv::ExecutionModelFragment;
219 }
220}
221
222// Translate glslang type to SPIR-V storage class.
223spv::StorageClass TranslateStorageClass(const glslang::TType& type)
224{
225 if (type.getQualifier().isPipeInput())
226 return spv::StorageClassInput;
227 else if (type.getQualifier().isPipeOutput())
228 return spv::StorageClassOutput;
229 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700230 if (type.getQualifier().layoutPushConstant)
231 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600232 if (type.getBasicType() == glslang::EbtBlock)
233 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800234 else if (type.getBasicType() == glslang::EbtAtomicUint)
235 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 else
237 return spv::StorageClassUniformConstant;
238 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
239 } else {
240 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700241 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
242 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600243 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
244 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::StorageClassFunction;
248 }
249 }
250}
251
252// Translate glslang sampler type to SPIR-V dimensionality.
253spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
254{
255 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700256 case glslang::Esd1D: return spv::Dim1D;
257 case glslang::Esd2D: return spv::Dim2D;
258 case glslang::Esd3D: return spv::Dim3D;
259 case glslang::EsdCube: return spv::DimCube;
260 case glslang::EsdRect: return spv::DimRect;
261 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700262 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700264 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600265 return spv::Dim2D;
266 }
267}
268
269// Translate glslang type to SPIR-V precision decorations.
270spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
271{
272 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700273 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600274 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600275 default:
276 return spv::NoPrecision;
277 }
278}
279
280// Translate glslang type to SPIR-V block decorations.
281spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
282{
283 if (type.getBasicType() == glslang::EbtBlock) {
284 switch (type.getQualifier().storage) {
285 case glslang::EvqUniform: return spv::DecorationBlock;
286 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
287 case glslang::EvqVaryingIn: return spv::DecorationBlock;
288 case glslang::EvqVaryingOut: return spv::DecorationBlock;
289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 break;
292 }
293 }
294
295 return (spv::Decoration)spv::BadValue;
296}
297
Rex Xu1da878f2016-02-21 20:59:01 +0800298// Translate glslang type to SPIR-V memory decorations.
299void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
300{
301 if (qualifier.coherent)
302 memory.push_back(spv::DecorationCoherent);
303 if (qualifier.volatil)
304 memory.push_back(spv::DecorationVolatile);
305 if (qualifier.restrict)
306 memory.push_back(spv::DecorationRestrict);
307 if (qualifier.readonly)
308 memory.push_back(spv::DecorationNonWritable);
309 if (qualifier.writeonly)
310 memory.push_back(spv::DecorationNonReadable);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700314spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600315{
316 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700317 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600318 case glslang::ElmRowMajor:
319 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600321 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 default:
323 // opaque layouts don't need a majorness
324 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600325 }
326 } else {
327 switch (type.getBasicType()) {
328 default:
329 return (spv::Decoration)spv::BadValue;
330 break;
331 case glslang::EbtBlock:
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform:
334 case glslang::EvqBuffer:
335 switch (type.getQualifier().layoutPacking) {
336 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
338 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600339 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 }
341 case glslang::EvqVaryingIn:
342 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700343 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return (spv::Decoration)spv::BadValue;
345 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600347 return (spv::Decoration)spv::BadValue;
348 }
349 }
350 }
351}
352
353// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700354// Returns spv::Decoration(spv::BadValue) when no decoration
355// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700356spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600357{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700358 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700359 // Smooth decoration doesn't exist in SPIR-V 1.0
360 return (spv::Decoration)spv::BadValue;
361 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700362 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700363 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700364 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600365 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700370 else if (qualifier.sample) {
371 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600372 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700373 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600374 return (spv::Decoration)spv::BadValue;
375}
376
John Kessenich92187592016-02-01 13:45:25 -0700377// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700378spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600379{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationInvariant;
382 else
383 return (spv::Decoration)spv::BadValue;
384}
385
qining9220dbb2016-05-04 17:34:38 -0400386// If glslang type is noContraction, return SPIR-V NoContraction decoration.
387spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
388{
389 if (qualifier.noContraction)
390 return spv::DecorationNoContraction;
391 else
392 return (spv::Decoration)spv::BadValue;
393}
394
John Kessenich140f3df2015-06-26 16:58:36 -0600395// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700396spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
398 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700399 case glslang::EbvPointSize:
400 switch (glslangIntermediate->getStage()) {
401 case EShLangGeometry:
402 builder.addCapability(spv::CapabilityGeometryPointSize);
403 break;
404 case EShLangTessControl:
405 case EShLangTessEvaluation:
406 builder.addCapability(spv::CapabilityTessellationPointSize);
407 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100408 default:
409 break;
John Kessenich92187592016-02-01 13:45:25 -0700410 }
411 return spv::BuiltInPointSize;
412
413 case glslang::EbvClipDistance:
414 builder.addCapability(spv::CapabilityClipDistance);
415 return spv::BuiltInClipDistance;
416
417 case glslang::EbvCullDistance:
418 builder.addCapability(spv::CapabilityCullDistance);
419 return spv::BuiltInCullDistance;
420
421 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500422 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700423 return spv::BuiltInViewportIndex;
424
John Kessenich5e801132016-02-15 11:09:46 -0700425 case glslang::EbvSampleId:
426 builder.addCapability(spv::CapabilitySampleRateShading);
427 return spv::BuiltInSampleId;
428
429 case glslang::EbvSamplePosition:
430 builder.addCapability(spv::CapabilitySampleRateShading);
431 return spv::BuiltInSamplePosition;
432
433 case glslang::EbvSampleMask:
434 builder.addCapability(spv::CapabilitySampleRateShading);
435 return spv::BuiltInSampleMask;
436
John Kessenich140f3df2015-06-26 16:58:36 -0600437 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600438 case glslang::EbvVertexId: return spv::BuiltInVertexId;
439 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700440 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
441 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600442 case glslang::EbvBaseVertex:
443 case glslang::EbvBaseInstance:
444 case glslang::EbvDrawId:
445 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600446 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600447 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600448 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
449 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
450 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600451 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
452 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
453 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
454 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
455 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
456 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
457 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600458 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
459 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
460 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
461 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
462 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
463 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
464 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
465 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800466 case glslang::EbvSubGroupSize:
467 case glslang::EbvSubGroupInvocation:
468 case glslang::EbvSubGroupEqMask:
469 case glslang::EbvSubGroupGeMask:
470 case glslang::EbvSubGroupGtMask:
471 case glslang::EbvSubGroupLeMask:
472 case glslang::EbvSubGroupLtMask:
473 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600474 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800475 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600476 default: return (spv::BuiltIn)spv::BadValue;
477 }
478}
479
Rex Xufc618912015-09-09 16:42:49 +0800480// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700481spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800482{
483 assert(type.getBasicType() == glslang::EbtSampler);
484
John Kessenich5d0fa972016-02-15 11:57:00 -0700485 // Check for capabilities
486 switch (type.getQualifier().layoutFormat) {
487 case glslang::ElfRg32f:
488 case glslang::ElfRg16f:
489 case glslang::ElfR11fG11fB10f:
490 case glslang::ElfR16f:
491 case glslang::ElfRgba16:
492 case glslang::ElfRgb10A2:
493 case glslang::ElfRg16:
494 case glslang::ElfRg8:
495 case glslang::ElfR16:
496 case glslang::ElfR8:
497 case glslang::ElfRgba16Snorm:
498 case glslang::ElfRg16Snorm:
499 case glslang::ElfRg8Snorm:
500 case glslang::ElfR16Snorm:
501 case glslang::ElfR8Snorm:
502
503 case glslang::ElfRg32i:
504 case glslang::ElfRg16i:
505 case glslang::ElfRg8i:
506 case glslang::ElfR16i:
507 case glslang::ElfR8i:
508
509 case glslang::ElfRgb10a2ui:
510 case glslang::ElfRg32ui:
511 case glslang::ElfRg16ui:
512 case glslang::ElfRg8ui:
513 case glslang::ElfR16ui:
514 case glslang::ElfR8ui:
515 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
516 break;
517
518 default:
519 break;
520 }
521
522 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800523 switch (type.getQualifier().layoutFormat) {
524 case glslang::ElfNone: return spv::ImageFormatUnknown;
525 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
526 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
527 case glslang::ElfR32f: return spv::ImageFormatR32f;
528 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
529 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
530 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
531 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
532 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
533 case glslang::ElfR16f: return spv::ImageFormatR16f;
534 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
535 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
536 case glslang::ElfRg16: return spv::ImageFormatRg16;
537 case glslang::ElfRg8: return spv::ImageFormatRg8;
538 case glslang::ElfR16: return spv::ImageFormatR16;
539 case glslang::ElfR8: return spv::ImageFormatR8;
540 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
541 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
542 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
543 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
544 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
545 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
546 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
547 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
548 case glslang::ElfR32i: return spv::ImageFormatR32i;
549 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
550 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
551 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
552 case glslang::ElfR16i: return spv::ImageFormatR16i;
553 case glslang::ElfR8i: return spv::ImageFormatR8i;
554 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
555 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
556 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
557 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
558 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
559 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
560 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
561 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
562 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
563 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
564 default: return (spv::ImageFormat)spv::BadValue;
565 }
566}
567
qining25262b32016-05-06 17:25:16 -0400568// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700569// descriptor set.
570bool IsDescriptorResource(const glslang::TType& type)
571{
John Kessenichf7497e22016-03-08 21:36:22 -0700572 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700573 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700574 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700575
576 // non block...
577 // basically samplerXXX/subpass/sampler/texture are all included
578 // if they are the global-scope-class, not the function parameter
579 // (or local, if they ever exist) class.
580 if (type.getBasicType() == glslang::EbtSampler)
581 return type.getQualifier().isUniformOrBuffer();
582
583 // None of the above.
584 return false;
585}
586
John Kesseniche0b6cad2015-12-24 10:30:13 -0700587void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
588{
589 if (child.layoutMatrix == glslang::ElmNone)
590 child.layoutMatrix = parent.layoutMatrix;
591
592 if (parent.invariant)
593 child.invariant = true;
594 if (parent.nopersp)
595 child.nopersp = true;
596 if (parent.flat)
597 child.flat = true;
598 if (parent.centroid)
599 child.centroid = true;
600 if (parent.patch)
601 child.patch = true;
602 if (parent.sample)
603 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800604 if (parent.coherent)
605 child.coherent = true;
606 if (parent.volatil)
607 child.volatil = true;
608 if (parent.restrict)
609 child.restrict = true;
610 if (parent.readonly)
611 child.readonly = true;
612 if (parent.writeonly)
613 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700614}
615
616bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
617{
John Kessenich7b9fa252016-01-21 18:56:57 -0700618 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700619 // - struct members can inherit from a struct declaration
620 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
621 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400622 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700623}
624
John Kessenich140f3df2015-06-26 16:58:36 -0600625//
626// Implement the TGlslangToSpvTraverser class.
627//
628
Lei Zhang17535f72016-05-04 15:55:59 -0400629TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
630 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
631 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600632 inMain(false), mainTerminated(false), linkageOnly(false),
633 glslangIntermediate(glslangIntermediate)
634{
635 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
636
637 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700638 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600639 stdBuiltins = builder.import("GLSL.std.450");
640 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700641 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
642 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600643
644 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600645 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
646 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600647 builder.addSourceExtension(it->c_str());
648
649 // Add the top-level modes for this shader.
650
John Kessenich92187592016-02-01 13:45:25 -0700651 if (glslangIntermediate->getXfbMode()) {
652 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700654 }
John Kessenich140f3df2015-06-26 16:58:36 -0600655
656 unsigned int mode;
657 switch (glslangIntermediate->getStage()) {
658 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600659 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600660 break;
661
662 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600663 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600664 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
665 break;
666
667 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600668 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600669 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700670 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
671 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
672 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600673 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600674 }
675 if (mode != spv::BadValue)
676 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
677
John Kesseniche6903322015-10-13 16:29:02 -0600678 switch (glslangIntermediate->getVertexSpacing()) {
679 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
680 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
681 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
682 default: mode = spv::BadValue; break;
683 }
684 if (mode != spv::BadValue)
685 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
686
687 switch (glslangIntermediate->getVertexOrder()) {
688 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
689 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
690 default: mode = spv::BadValue; break;
691 }
692 if (mode != spv::BadValue)
693 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
694
695 if (glslangIntermediate->getPointMode())
696 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600697 break;
698
699 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600700 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600701 switch (glslangIntermediate->getInputPrimitive()) {
702 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
703 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
704 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700705 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
707 default: mode = spv::BadValue; break;
708 }
709 if (mode != spv::BadValue)
710 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600711
John Kessenich140f3df2015-06-26 16:58:36 -0600712 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
713
714 switch (glslangIntermediate->getOutputPrimitive()) {
715 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
716 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
717 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
718 default: mode = spv::BadValue; break;
719 }
720 if (mode != spv::BadValue)
721 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
722 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
723 break;
724
725 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600726 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 if (glslangIntermediate->getPixelCenterInteger())
728 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600729
John Kessenich140f3df2015-06-26 16:58:36 -0600730 if (glslangIntermediate->getOriginUpperLeft())
731 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600732 else
733 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600734
735 if (glslangIntermediate->getEarlyFragmentTests())
736 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
737
738 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600739 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
740 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
741 default: mode = spv::BadValue; break;
742 }
743 if (mode != spv::BadValue)
744 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
745
746 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
747 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600748 break;
749
750 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600751 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600752 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
753 glslangIntermediate->getLocalSize(1),
754 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600755 break;
756
757 default:
758 break;
759 }
760
761}
762
John Kessenich7ba63412015-12-20 17:37:07 -0700763// Finish everything and dump
764void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
765{
766 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100767 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
768 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700769
qiningda397332016-03-09 19:54:03 -0500770 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700771 builder.dump(out);
772}
773
John Kessenich140f3df2015-06-26 16:58:36 -0600774TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
775{
776 if (! mainTerminated) {
777 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
778 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600779 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600780 }
781}
782
783//
784// Implement the traversal functions.
785//
786// Return true from interior nodes to have the external traversal
787// continue on to children. Return false if children were
788// already processed.
789//
790
791//
qining25262b32016-05-06 17:25:16 -0400792// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600793// - uniform/input reads
794// - output writes
795// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
796// - something simple that degenerates into the last bullet
797//
798void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
799{
qining75d1d802016-04-06 14:42:01 -0400800 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
801 if (symbol->getType().getQualifier().isSpecConstant())
802 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
803
John Kessenich140f3df2015-06-26 16:58:36 -0600804 // getSymbolId() will set up all the IO decorations on the first call.
805 // Formal function parameters were mapped during makeFunctions().
806 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700807
808 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
809 if (builder.isPointer(id)) {
810 spv::StorageClass sc = builder.getStorageClass(id);
811 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
812 iOSet.insert(id);
813 }
814
815 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700816 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600817 // Prepare to generate code for the access
818
819 // L-value chains will be computed left to right. We're on the symbol now,
820 // which is the left-most part of the access chain, so now is "clear" time,
821 // followed by setting the base.
822 builder.clearAccessChain();
823
824 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700825 // except for
826 // A) "const in" arguments to a function, which are an intermediate object.
827 // See comments in handleUserFunctionCall().
828 // B) Specialization constants (normal constant don't even come in as a variable),
829 // These are also pure R-values.
830 glslang::TQualifier qualifier = symbol->getQualifier();
831 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
832 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600833 builder.setAccessChainRValue(id);
834 else
835 builder.setAccessChainLValue(id);
836 }
837}
838
839bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
840{
qining40887662016-04-03 22:20:42 -0400841 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
842 if (node->getType().getQualifier().isSpecConstant())
843 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
844
John Kessenich140f3df2015-06-26 16:58:36 -0600845 // First, handle special cases
846 switch (node->getOp()) {
847 case glslang::EOpAssign:
848 case glslang::EOpAddAssign:
849 case glslang::EOpSubAssign:
850 case glslang::EOpMulAssign:
851 case glslang::EOpVectorTimesMatrixAssign:
852 case glslang::EOpVectorTimesScalarAssign:
853 case glslang::EOpMatrixTimesScalarAssign:
854 case glslang::EOpMatrixTimesMatrixAssign:
855 case glslang::EOpDivAssign:
856 case glslang::EOpModAssign:
857 case glslang::EOpAndAssign:
858 case glslang::EOpInclusiveOrAssign:
859 case glslang::EOpExclusiveOrAssign:
860 case glslang::EOpLeftShiftAssign:
861 case glslang::EOpRightShiftAssign:
862 // A bin-op assign "a += b" means the same thing as "a = a + b"
863 // where a is evaluated before b. For a simple assignment, GLSL
864 // says to evaluate the left before the right. So, always, left
865 // node then right node.
866 {
867 // get the left l-value, save it away
868 builder.clearAccessChain();
869 node->getLeft()->traverse(this);
870 spv::Builder::AccessChain lValue = builder.getAccessChain();
871
872 // evaluate the right
873 builder.clearAccessChain();
874 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700875 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600876
877 if (node->getOp() != glslang::EOpAssign) {
878 // the left is also an r-value
879 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700880 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600881
882 // do the operation
qining25262b32016-05-06 17:25:16 -0400883 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
884 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600885 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
886 node->getType().getBasicType());
887
888 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700889 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600890 }
891
892 // store the result
893 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800894 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600895
896 // assignments are expressions having an rValue after they are evaluated...
897 builder.clearAccessChain();
898 builder.setAccessChainRValue(rValue);
899 }
900 return false;
901 case glslang::EOpIndexDirect:
902 case glslang::EOpIndexDirectStruct:
903 {
904 // Get the left part of the access chain.
905 node->getLeft()->traverse(this);
906
907 // Add the next element in the chain
908
John Kessenich55e7d112015-11-15 21:33:39 -0700909 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600910 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
911 // This may be, e.g., an anonymous block-member selection, which generally need
912 // index remapping due to hidden members in anonymous blocks.
913 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700914 assert(remapper.size() > 0);
915 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600916 }
917
918 if (! node->getLeft()->getType().isArray() &&
919 node->getLeft()->getType().isVector() &&
920 node->getOp() == glslang::EOpIndexDirect) {
921 // This is essentially a hard-coded vector swizzle of size 1,
922 // so short circuit the access-chain stuff with a swizzle.
923 std::vector<unsigned> swizzle;
924 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600925 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600926 } else {
927 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600928 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600929 }
930 }
931 return false;
932 case glslang::EOpIndexIndirect:
933 {
934 // Structure or array or vector indirection.
935 // Will use native SPIR-V access-chain for struct and array indirection;
936 // matrices are arrays of vectors, so will also work for a matrix.
937 // Will use the access chain's 'component' for variable index into a vector.
938
939 // This adapter is building access chains left to right.
940 // Set up the access chain to the left.
941 node->getLeft()->traverse(this);
942
943 // save it so that computing the right side doesn't trash it
944 spv::Builder::AccessChain partial = builder.getAccessChain();
945
946 // compute the next index in the chain
947 builder.clearAccessChain();
948 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700949 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600950
951 // restore the saved access chain
952 builder.setAccessChain(partial);
953
954 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600955 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600956 else
John Kessenichfa668da2015-09-13 14:46:30 -0600957 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600958 }
959 return false;
960 case glslang::EOpVectorSwizzle:
961 {
962 node->getLeft()->traverse(this);
963 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
964 std::vector<unsigned> swizzle;
965 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
966 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600967 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600968 }
969 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600970 case glslang::EOpLogicalOr:
971 case glslang::EOpLogicalAnd:
972 {
973
974 // These may require short circuiting, but can sometimes be done as straight
975 // binary operations. The right operand must be short circuited if it has
976 // side effects, and should probably be if it is complex.
977 if (isTrivial(node->getRight()->getAsTyped()))
978 break; // handle below as a normal binary operation
979 // otherwise, we need to do dynamic short circuiting on the right operand
980 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
981 builder.clearAccessChain();
982 builder.setAccessChainRValue(result);
983 }
984 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600985 default:
986 break;
987 }
988
989 // Assume generic binary op...
990
John Kessenich32cfd492016-02-02 12:37:46 -0700991 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600992 builder.clearAccessChain();
993 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700994 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600995
John Kessenich32cfd492016-02-02 12:37:46 -0700996 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600997 builder.clearAccessChain();
998 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700999 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001000
John Kessenich32cfd492016-02-02 12:37:46 -07001001 // get result
1002 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001003 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001004 convertGlslangToSpvType(node->getType()), left, right,
1005 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001006
John Kessenich50e57562015-12-21 21:21:11 -07001007 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001008 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001009 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001010 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001011 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001012 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001013 return false;
1014 }
John Kessenich140f3df2015-06-26 16:58:36 -06001015}
1016
1017bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1018{
qining40887662016-04-03 22:20:42 -04001019 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1020 if (node->getType().getQualifier().isSpecConstant())
1021 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1022
John Kessenichfc51d282015-08-19 13:34:18 -06001023 spv::Id result = spv::NoResult;
1024
1025 // try texturing first
1026 result = createImageTextureFunctionCall(node);
1027 if (result != spv::NoResult) {
1028 builder.clearAccessChain();
1029 builder.setAccessChainRValue(result);
1030
1031 return false; // done with this node
1032 }
1033
1034 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001035
1036 if (node->getOp() == glslang::EOpArrayLength) {
1037 // Quite special; won't want to evaluate the operand.
1038
1039 // Normal .length() would have been constant folded by the front-end.
1040 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001041 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001042 assert(node->getOperand()->getType().isRuntimeSizedArray());
1043 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1044 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001045 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1046 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001047
1048 builder.clearAccessChain();
1049 builder.setAccessChainRValue(length);
1050
1051 return false;
1052 }
1053
John Kessenichfc51d282015-08-19 13:34:18 -06001054 // Start by evaluating the operand
1055
John Kessenich140f3df2015-06-26 16:58:36 -06001056 builder.clearAccessChain();
1057 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001058
Rex Xufc618912015-09-09 16:42:49 +08001059 spv::Id operand = spv::NoResult;
1060
1061 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1062 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001063 node->getOp() == glslang::EOpAtomicCounter ||
1064 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001065 operand = builder.accessChainGetLValue(); // Special case l-value operands
1066 else
John Kessenich32cfd492016-02-02 12:37:46 -07001067 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001068
1069 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001070 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001071
1072 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001073 if (! result)
1074 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001075
1076 // if not, then possibly an operation
1077 if (! result)
qining25262b32016-05-06 17:25:16 -04001078 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001079
1080 if (result) {
1081 builder.clearAccessChain();
1082 builder.setAccessChainRValue(result);
1083
1084 return false; // done with this node
1085 }
1086
1087 // it must be a special case, check...
1088 switch (node->getOp()) {
1089 case glslang::EOpPostIncrement:
1090 case glslang::EOpPostDecrement:
1091 case glslang::EOpPreIncrement:
1092 case glslang::EOpPreDecrement:
1093 {
1094 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001095 spv::Id one = 0;
1096 if (node->getBasicType() == glslang::EbtFloat)
1097 one = builder.makeFloatConstant(1.0F);
1098 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1099 one = builder.makeInt64Constant(1);
1100 else
1101 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001102 glslang::TOperator op;
1103 if (node->getOp() == glslang::EOpPreIncrement ||
1104 node->getOp() == glslang::EOpPostIncrement)
1105 op = glslang::EOpAdd;
1106 else
1107 op = glslang::EOpSub;
1108
qining25262b32016-05-06 17:25:16 -04001109 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1110 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001111 convertGlslangToSpvType(node->getType()), operand, one,
1112 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001113 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001114
1115 // The result of operation is always stored, but conditionally the
1116 // consumed result. The consumed result is always an r-value.
1117 builder.accessChainStore(result);
1118 builder.clearAccessChain();
1119 if (node->getOp() == glslang::EOpPreIncrement ||
1120 node->getOp() == glslang::EOpPreDecrement)
1121 builder.setAccessChainRValue(result);
1122 else
1123 builder.setAccessChainRValue(operand);
1124 }
1125
1126 return false;
1127
1128 case glslang::EOpEmitStreamVertex:
1129 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1130 return false;
1131 case glslang::EOpEndStreamPrimitive:
1132 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1133 return false;
1134
1135 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001136 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001137 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001138 }
John Kessenich140f3df2015-06-26 16:58:36 -06001139}
1140
1141bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1142{
qining27e04a02016-04-14 16:40:20 -04001143 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1144 if (node->getType().getQualifier().isSpecConstant())
1145 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1146
John Kessenichfc51d282015-08-19 13:34:18 -06001147 spv::Id result = spv::NoResult;
1148
1149 // try texturing
1150 result = createImageTextureFunctionCall(node);
1151 if (result != spv::NoResult) {
1152 builder.clearAccessChain();
1153 builder.setAccessChainRValue(result);
1154
1155 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001156 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001157 // "imageStore" is a special case, which has no result
1158 return false;
1159 }
John Kessenichfc51d282015-08-19 13:34:18 -06001160
John Kessenich140f3df2015-06-26 16:58:36 -06001161 glslang::TOperator binOp = glslang::EOpNull;
1162 bool reduceComparison = true;
1163 bool isMatrix = false;
1164 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001165 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001166
1167 assert(node->getOp());
1168
1169 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1170
1171 switch (node->getOp()) {
1172 case glslang::EOpSequence:
1173 {
1174 if (preVisit)
1175 ++sequenceDepth;
1176 else
1177 --sequenceDepth;
1178
1179 if (sequenceDepth == 1) {
1180 // If this is the parent node of all the functions, we want to see them
1181 // early, so all call points have actual SPIR-V functions to reference.
1182 // In all cases, still let the traverser visit the children for us.
1183 makeFunctions(node->getAsAggregate()->getSequence());
1184
1185 // Also, we want all globals initializers to go into the entry of main(), before
1186 // anything else gets there, so visit out of order, doing them all now.
1187 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1188
1189 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1190 // so do them manually.
1191 visitFunctions(node->getAsAggregate()->getSequence());
1192
1193 return false;
1194 }
1195
1196 return true;
1197 }
1198 case glslang::EOpLinkerObjects:
1199 {
1200 if (visit == glslang::EvPreVisit)
1201 linkageOnly = true;
1202 else
1203 linkageOnly = false;
1204
1205 return true;
1206 }
1207 case glslang::EOpComma:
1208 {
1209 // processing from left to right naturally leaves the right-most
1210 // lying around in the access chain
1211 glslang::TIntermSequence& glslangOperands = node->getSequence();
1212 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1213 glslangOperands[i]->traverse(this);
1214
1215 return false;
1216 }
1217 case glslang::EOpFunction:
1218 if (visit == glslang::EvPreVisit) {
1219 if (isShaderEntrypoint(node)) {
1220 inMain = true;
1221 builder.setBuildPoint(shaderEntry->getLastBlock());
1222 } else {
1223 handleFunctionEntry(node);
1224 }
1225 } else {
1226 if (inMain)
1227 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001228 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001229 inMain = false;
1230 }
1231
1232 return true;
1233 case glslang::EOpParameters:
1234 // Parameters will have been consumed by EOpFunction processing, but not
1235 // the body, so we still visited the function node's children, making this
1236 // child redundant.
1237 return false;
1238 case glslang::EOpFunctionCall:
1239 {
1240 if (node->isUserDefined())
1241 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001242 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1243 if (result) {
1244 builder.clearAccessChain();
1245 builder.setAccessChainRValue(result);
1246 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001247 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001248
1249 return false;
1250 }
1251 case glslang::EOpConstructMat2x2:
1252 case glslang::EOpConstructMat2x3:
1253 case glslang::EOpConstructMat2x4:
1254 case glslang::EOpConstructMat3x2:
1255 case glslang::EOpConstructMat3x3:
1256 case glslang::EOpConstructMat3x4:
1257 case glslang::EOpConstructMat4x2:
1258 case glslang::EOpConstructMat4x3:
1259 case glslang::EOpConstructMat4x4:
1260 case glslang::EOpConstructDMat2x2:
1261 case glslang::EOpConstructDMat2x3:
1262 case glslang::EOpConstructDMat2x4:
1263 case glslang::EOpConstructDMat3x2:
1264 case glslang::EOpConstructDMat3x3:
1265 case glslang::EOpConstructDMat3x4:
1266 case glslang::EOpConstructDMat4x2:
1267 case glslang::EOpConstructDMat4x3:
1268 case glslang::EOpConstructDMat4x4:
1269 isMatrix = true;
1270 // fall through
1271 case glslang::EOpConstructFloat:
1272 case glslang::EOpConstructVec2:
1273 case glslang::EOpConstructVec3:
1274 case glslang::EOpConstructVec4:
1275 case glslang::EOpConstructDouble:
1276 case glslang::EOpConstructDVec2:
1277 case glslang::EOpConstructDVec3:
1278 case glslang::EOpConstructDVec4:
1279 case glslang::EOpConstructBool:
1280 case glslang::EOpConstructBVec2:
1281 case glslang::EOpConstructBVec3:
1282 case glslang::EOpConstructBVec4:
1283 case glslang::EOpConstructInt:
1284 case glslang::EOpConstructIVec2:
1285 case glslang::EOpConstructIVec3:
1286 case glslang::EOpConstructIVec4:
1287 case glslang::EOpConstructUint:
1288 case glslang::EOpConstructUVec2:
1289 case glslang::EOpConstructUVec3:
1290 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001291 case glslang::EOpConstructInt64:
1292 case glslang::EOpConstructI64Vec2:
1293 case glslang::EOpConstructI64Vec3:
1294 case glslang::EOpConstructI64Vec4:
1295 case glslang::EOpConstructUint64:
1296 case glslang::EOpConstructU64Vec2:
1297 case glslang::EOpConstructU64Vec3:
1298 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001299 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001300 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001301 {
1302 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001303 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001304 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1305 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001306 if (node->getOp() == glslang::EOpConstructTextureSampler)
1307 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1308 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001309 std::vector<spv::Id> constituents;
1310 for (int c = 0; c < (int)arguments.size(); ++c)
1311 constituents.push_back(arguments[c]);
1312 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001313 } else if (isMatrix)
1314 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1315 else
1316 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001317
1318 builder.clearAccessChain();
1319 builder.setAccessChainRValue(constructed);
1320
1321 return false;
1322 }
1323
1324 // These six are component-wise compares with component-wise results.
1325 // Forward on to createBinaryOperation(), requesting a vector result.
1326 case glslang::EOpLessThan:
1327 case glslang::EOpGreaterThan:
1328 case glslang::EOpLessThanEqual:
1329 case glslang::EOpGreaterThanEqual:
1330 case glslang::EOpVectorEqual:
1331 case glslang::EOpVectorNotEqual:
1332 {
1333 // Map the operation to a binary
1334 binOp = node->getOp();
1335 reduceComparison = false;
1336 switch (node->getOp()) {
1337 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1338 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1339 default: binOp = node->getOp(); break;
1340 }
1341
1342 break;
1343 }
1344 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001345 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001346 binOp = glslang::EOpMul;
1347 break;
1348 case glslang::EOpOuterProduct:
1349 // two vectors multiplied to make a matrix
1350 binOp = glslang::EOpOuterProduct;
1351 break;
1352 case glslang::EOpDot:
1353 {
qining25262b32016-05-06 17:25:16 -04001354 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001355 glslang::TIntermSequence& glslangOperands = node->getSequence();
1356 if (! glslangOperands[0]->getAsTyped()->isVector())
1357 binOp = glslang::EOpMul;
1358 break;
1359 }
1360 case glslang::EOpMod:
1361 // when an aggregate, this is the floating-point mod built-in function,
1362 // which can be emitted by the one in createBinaryOperation()
1363 binOp = glslang::EOpMod;
1364 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001365 case glslang::EOpEmitVertex:
1366 case glslang::EOpEndPrimitive:
1367 case glslang::EOpBarrier:
1368 case glslang::EOpMemoryBarrier:
1369 case glslang::EOpMemoryBarrierAtomicCounter:
1370 case glslang::EOpMemoryBarrierBuffer:
1371 case glslang::EOpMemoryBarrierImage:
1372 case glslang::EOpMemoryBarrierShared:
1373 case glslang::EOpGroupMemoryBarrier:
1374 noReturnValue = true;
1375 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1376 break;
1377
John Kessenich426394d2015-07-23 10:22:48 -06001378 case glslang::EOpAtomicAdd:
1379 case glslang::EOpAtomicMin:
1380 case glslang::EOpAtomicMax:
1381 case glslang::EOpAtomicAnd:
1382 case glslang::EOpAtomicOr:
1383 case glslang::EOpAtomicXor:
1384 case glslang::EOpAtomicExchange:
1385 case glslang::EOpAtomicCompSwap:
1386 atomic = true;
1387 break;
1388
John Kessenich140f3df2015-06-26 16:58:36 -06001389 default:
1390 break;
1391 }
1392
1393 //
1394 // See if it maps to a regular operation.
1395 //
John Kessenich140f3df2015-06-26 16:58:36 -06001396 if (binOp != glslang::EOpNull) {
1397 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1398 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1399 assert(left && right);
1400
1401 builder.clearAccessChain();
1402 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001403 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
1405 builder.clearAccessChain();
1406 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001407 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001408
qining25262b32016-05-06 17:25:16 -04001409 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1410 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001411 left->getType().getBasicType(), reduceComparison);
1412
1413 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001414 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 builder.clearAccessChain();
1416 builder.setAccessChainRValue(result);
1417
1418 return false;
1419 }
1420
John Kessenich426394d2015-07-23 10:22:48 -06001421 //
1422 // Create the list of operands.
1423 //
John Kessenich140f3df2015-06-26 16:58:36 -06001424 glslang::TIntermSequence& glslangOperands = node->getSequence();
1425 std::vector<spv::Id> operands;
1426 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1427 builder.clearAccessChain();
1428 glslangOperands[arg]->traverse(this);
1429
1430 // special case l-value operands; there are just a few
1431 bool lvalue = false;
1432 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001433 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001434 case glslang::EOpModf:
1435 if (arg == 1)
1436 lvalue = true;
1437 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001438 case glslang::EOpInterpolateAtSample:
1439 case glslang::EOpInterpolateAtOffset:
1440 if (arg == 0)
1441 lvalue = true;
1442 break;
Rex Xud4782c12015-09-06 16:30:11 +08001443 case glslang::EOpAtomicAdd:
1444 case glslang::EOpAtomicMin:
1445 case glslang::EOpAtomicMax:
1446 case glslang::EOpAtomicAnd:
1447 case glslang::EOpAtomicOr:
1448 case glslang::EOpAtomicXor:
1449 case glslang::EOpAtomicExchange:
1450 case glslang::EOpAtomicCompSwap:
1451 if (arg == 0)
1452 lvalue = true;
1453 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001454 case glslang::EOpAddCarry:
1455 case glslang::EOpSubBorrow:
1456 if (arg == 2)
1457 lvalue = true;
1458 break;
1459 case glslang::EOpUMulExtended:
1460 case glslang::EOpIMulExtended:
1461 if (arg >= 2)
1462 lvalue = true;
1463 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001464 default:
1465 break;
1466 }
1467 if (lvalue)
1468 operands.push_back(builder.accessChainGetLValue());
1469 else
John Kessenich32cfd492016-02-02 12:37:46 -07001470 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001471 }
John Kessenich426394d2015-07-23 10:22:48 -06001472
1473 if (atomic) {
1474 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001475 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001476 } else {
1477 // Pass through to generic operations.
1478 switch (glslangOperands.size()) {
1479 case 0:
1480 result = createNoArgOperation(node->getOp());
1481 break;
1482 case 1:
qining25262b32016-05-06 17:25:16 -04001483 result = createUnaryOperation(
1484 node->getOp(), precision,
1485 TranslateNoContractionDecoration(node->getType().getQualifier()),
1486 convertGlslangToSpvType(node->getType()), operands.front(),
1487 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001488 break;
1489 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001490 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001491 break;
1492 }
John Kessenich140f3df2015-06-26 16:58:36 -06001493 }
1494
1495 if (noReturnValue)
1496 return false;
1497
1498 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001499 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001500 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001501 } else {
1502 builder.clearAccessChain();
1503 builder.setAccessChainRValue(result);
1504 return false;
1505 }
1506}
1507
1508bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1509{
1510 // This path handles both if-then-else and ?:
1511 // The if-then-else has a node type of void, while
1512 // ?: has a non-void node type
1513 spv::Id result = 0;
1514 if (node->getBasicType() != glslang::EbtVoid) {
1515 // don't handle this as just on-the-fly temporaries, because there will be two names
1516 // and better to leave SSA to later passes
1517 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1518 }
1519
1520 // emit the condition before doing anything with selection
1521 node->getCondition()->traverse(this);
1522
1523 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001524 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001525
1526 if (node->getTrueBlock()) {
1527 // emit the "then" statement
1528 node->getTrueBlock()->traverse(this);
1529 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001530 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001531 }
1532
1533 if (node->getFalseBlock()) {
1534 ifBuilder.makeBeginElse();
1535 // emit the "else" statement
1536 node->getFalseBlock()->traverse(this);
1537 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001538 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001539 }
1540
1541 ifBuilder.makeEndIf();
1542
1543 if (result) {
1544 // GLSL only has r-values as the result of a :?, but
1545 // if we have an l-value, that can be more efficient if it will
1546 // become the base of a complex r-value expression, because the
1547 // next layer copies r-values into memory to use the access-chain mechanism
1548 builder.clearAccessChain();
1549 builder.setAccessChainLValue(result);
1550 }
1551
1552 return false;
1553}
1554
1555bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1556{
1557 // emit and get the condition before doing anything with switch
1558 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001559 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001560
1561 // browse the children to sort out code segments
1562 int defaultSegment = -1;
1563 std::vector<TIntermNode*> codeSegments;
1564 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1565 std::vector<int> caseValues;
1566 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1567 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1568 TIntermNode* child = *c;
1569 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001570 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001571 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001572 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001573 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1574 } else
1575 codeSegments.push_back(child);
1576 }
1577
qining25262b32016-05-06 17:25:16 -04001578 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001579 // statements between the last case and the end of the switch statement
1580 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1581 (int)codeSegments.size() == defaultSegment)
1582 codeSegments.push_back(nullptr);
1583
1584 // make the switch statement
1585 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001586 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001587
1588 // emit all the code in the segments
1589 breakForLoop.push(false);
1590 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1591 builder.nextSwitchSegment(segmentBlocks, s);
1592 if (codeSegments[s])
1593 codeSegments[s]->traverse(this);
1594 else
1595 builder.addSwitchBreak();
1596 }
1597 breakForLoop.pop();
1598
1599 builder.endSwitch(segmentBlocks);
1600
1601 return false;
1602}
1603
1604void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1605{
1606 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001607 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001608
1609 builder.clearAccessChain();
1610 builder.setAccessChainRValue(constant);
1611}
1612
1613bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1614{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001615 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001616 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001617 // Spec requires back edges to target header blocks, and every header block
1618 // must dominate its merge block. Make a header block first to ensure these
1619 // conditions are met. By definition, it will contain OpLoopMerge, followed
1620 // by a block-ending branch. But we don't want to put any other body/test
1621 // instructions in it, since the body/test may have arbitrary instructions,
1622 // including merges of its own.
1623 builder.setBuildPoint(&blocks.head);
1624 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001625 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001626 spv::Block& test = builder.makeNewBlock();
1627 builder.createBranch(&test);
1628
1629 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001630 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001631 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001632 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001633 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1634
1635 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001636 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001637 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001638 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001639 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001640 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001641
1642 builder.setBuildPoint(&blocks.continue_target);
1643 if (node->getTerminal())
1644 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001645 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001646 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001647 builder.createBranch(&blocks.body);
1648
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001649 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001650 builder.setBuildPoint(&blocks.body);
1651 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001652 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001653 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001654 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001655
1656 builder.setBuildPoint(&blocks.continue_target);
1657 if (node->getTerminal())
1658 node->getTerminal()->traverse(this);
1659 if (node->getTest()) {
1660 node->getTest()->traverse(this);
1661 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001662 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001663 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001664 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001665 // TODO: unless there was a break/return/discard instruction
1666 // somewhere in the body, this is an infinite loop, so we should
1667 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001668 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001669 }
John Kessenich140f3df2015-06-26 16:58:36 -06001670 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001671 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001672 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001673 return false;
1674}
1675
1676bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1677{
1678 if (node->getExpression())
1679 node->getExpression()->traverse(this);
1680
1681 switch (node->getFlowOp()) {
1682 case glslang::EOpKill:
1683 builder.makeDiscard();
1684 break;
1685 case glslang::EOpBreak:
1686 if (breakForLoop.top())
1687 builder.createLoopExit();
1688 else
1689 builder.addSwitchBreak();
1690 break;
1691 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001692 builder.createLoopContinue();
1693 break;
1694 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001695 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001696 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001697 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001698 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001699
1700 builder.clearAccessChain();
1701 break;
1702
1703 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001704 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001705 break;
1706 }
1707
1708 return false;
1709}
1710
1711spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1712{
qining25262b32016-05-06 17:25:16 -04001713 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001714 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001715 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001716 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001717 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001718 }
1719
1720 // Now, handle actual variables
1721 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1722 spv::Id spvType = convertGlslangToSpvType(node->getType());
1723
1724 const char* name = node->getName().c_str();
1725 if (glslang::IsAnonymous(name))
1726 name = "";
1727
1728 return builder.createVariable(storageClass, spvType, name);
1729}
1730
1731// Return type Id of the sampled type.
1732spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1733{
1734 switch (sampler.type) {
1735 case glslang::EbtFloat: return builder.makeFloatType(32);
1736 case glslang::EbtInt: return builder.makeIntType(32);
1737 case glslang::EbtUint: return builder.makeUintType(32);
1738 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001739 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001740 return builder.makeFloatType(32);
1741 }
1742}
1743
John Kessenich3ac051e2015-12-20 11:29:16 -07001744// Convert from a glslang type to an SPV type, by calling into a
1745// recursive version of this function. This establishes the inherited
1746// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001747spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1748{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001749 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001750}
1751
1752// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001753// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001754spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001755{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001756 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001757
1758 switch (type.getBasicType()) {
1759 case glslang::EbtVoid:
1760 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001761 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001762 break;
1763 case glslang::EbtFloat:
1764 spvType = builder.makeFloatType(32);
1765 break;
1766 case glslang::EbtDouble:
1767 spvType = builder.makeFloatType(64);
1768 break;
1769 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001770 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1771 // a 32-bit int where non-0 means true.
1772 if (explicitLayout != glslang::ElpNone)
1773 spvType = builder.makeUintType(32);
1774 else
1775 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001776 break;
1777 case glslang::EbtInt:
1778 spvType = builder.makeIntType(32);
1779 break;
1780 case glslang::EbtUint:
1781 spvType = builder.makeUintType(32);
1782 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001783 case glslang::EbtInt64:
1784 builder.addCapability(spv::CapabilityInt64);
1785 spvType = builder.makeIntType(64);
1786 break;
1787 case glslang::EbtUint64:
1788 builder.addCapability(spv::CapabilityInt64);
1789 spvType = builder.makeUintType(64);
1790 break;
John Kessenich426394d2015-07-23 10:22:48 -06001791 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001792 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 -06001793 spvType = builder.makeUintType(32);
1794 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001795 case glslang::EbtSampler:
1796 {
1797 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001798 if (sampler.sampler) {
1799 // pure sampler
1800 spvType = builder.makeSamplerType();
1801 } else {
1802 // an image is present, make its type
1803 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1804 sampler.image ? 2 : 1, TranslateImageFormat(type));
1805 if (sampler.combined) {
1806 // already has both image and sampler, make the combined type
1807 spvType = builder.makeSampledImageType(spvType);
1808 }
John Kessenich55e7d112015-11-15 21:33:39 -07001809 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001810 }
John Kessenich140f3df2015-06-26 16:58:36 -06001811 break;
1812 case glslang::EbtStruct:
1813 case glslang::EbtBlock:
1814 {
1815 // If we've seen this struct type, return it
1816 const glslang::TTypeList* glslangStruct = type.getStruct();
1817 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001818
1819 // Try to share structs for different layouts, but not yet for other
1820 // kinds of qualification (primarily not yet including interpolant qualification).
1821 if (! HasNonLayoutQualifiers(qualifier))
1822 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1823 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001824 break;
1825
1826 // else, we haven't seen it...
1827
1828 // Create a vector of struct types for SPIR-V to consume
1829 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1830 if (type.getBasicType() == glslang::EbtBlock)
1831 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001832 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001833 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1834 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1835 if (glslangType.hiddenMember()) {
1836 ++memberDelta;
1837 if (type.getBasicType() == glslang::EbtBlock)
1838 memberRemapper[glslangStruct][i] = -1;
1839 } else {
1840 if (type.getBasicType() == glslang::EbtBlock)
1841 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001842 // modify just this child's view of the qualifier
1843 glslang::TQualifier subQualifier = glslangType.getQualifier();
1844 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001845
1846 // manually inherit location; it's more complex
1847 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1848 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1849 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001850 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001851
1852 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001853 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001854 }
1855 }
1856
1857 // Make the SPIR-V type
1858 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001859 if (! HasNonLayoutQualifiers(qualifier))
1860 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001861
1862 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001863 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001864 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001865 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1866 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1867 int member = i;
1868 if (type.getBasicType() == glslang::EbtBlock)
1869 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001870
John Kesseniche0b6cad2015-12-24 10:30:13 -07001871 // modify just this child's view of the qualifier
1872 glslang::TQualifier subQualifier = glslangType.getQualifier();
1873 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001874
John Kessenich140f3df2015-06-26 16:58:36 -06001875 // using -1 above to indicate a hidden member
1876 if (member >= 0) {
1877 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001878 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001879 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001880 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1881 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001882
Rex Xu1da878f2016-02-21 20:59:01 +08001883 if (qualifier.storage == glslang::EvqBuffer) {
1884 std::vector<spv::Decoration> memory;
1885 TranslateMemoryDecoration(subQualifier, memory);
1886 for (unsigned int i = 0; i < memory.size(); ++i)
1887 addMemberDecoration(spvType, member, memory[i]);
1888 }
1889
John Kessenich09677482016-02-19 12:21:50 -07001890 // compute location decoration; tricky based on whether inheritance is at play
1891 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1892 // probably move to the linker stage of the front end proper, and just have the
1893 // answer sitting already distributed throughout the individual member locations.
1894 int location = -1; // will only decorate if present or inherited
1895 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1896 location = subQualifier.layoutLocation;
1897 else if (qualifier.hasLocation()) // inheritance
1898 location = qualifier.layoutLocation + locationOffset;
1899 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001900 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001901 if (location >= 0)
1902 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1903
1904 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001905 if (glslangType.getQualifier().hasComponent())
1906 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1907 if (glslangType.getQualifier().hasXfbOffset())
1908 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001909 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001910 // figure out what to do with offset, which is accumulating
1911 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001912 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001913 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001914 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001915 offset = nextOffset;
1916 }
John Kessenich140f3df2015-06-26 16:58:36 -06001917
John Kessenichf85e8062015-12-19 13:57:10 -07001918 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001919 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001920
John Kessenich140f3df2015-06-26 16:58:36 -06001921 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001922 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1923 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001924 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001925 }
1926 }
1927
1928 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001929 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001930 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001931 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001932 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001933 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001934 }
John Kessenich140f3df2015-06-26 16:58:36 -06001935 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001936 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001937 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001938 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001939 if (type.getQualifier().hasXfbBuffer())
1940 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1941 }
1942 }
1943 break;
1944 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001945 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001946 break;
1947 }
1948
1949 if (type.isMatrix())
1950 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1951 else {
1952 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1953 if (type.getVectorSize() > 1)
1954 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1955 }
1956
1957 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001958 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1959
John Kessenichc9a80832015-09-12 12:17:44 -06001960 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001961 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001962 // We need to decorate array strides for types needing explicit layout, except blocks.
1963 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001964 // Use a dummy glslang type for querying internal strides of
1965 // arrays of arrays, but using just a one-dimensional array.
1966 glslang::TType simpleArrayType(type, 0); // deference type of the array
1967 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1968 simpleArrayType.getArraySizes().dereference();
1969
1970 // Will compute the higher-order strides here, rather than making a whole
1971 // pile of types and doing repetitive recursion on their contents.
1972 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1973 }
John Kessenichf8842e52016-01-04 19:22:56 -07001974
1975 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001976 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001977 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001978 if (stride > 0)
1979 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001980 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001981 }
1982 } else {
1983 // single-dimensional array, and don't yet have stride
1984
John Kessenichf8842e52016-01-04 19:22:56 -07001985 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001986 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1987 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001988 }
John Kessenich31ed4832015-09-09 17:51:38 -06001989
John Kessenichc9a80832015-09-12 12:17:44 -06001990 // Do the outer dimension, which might not be known for a runtime-sized array
1991 if (type.isRuntimeSizedArray()) {
1992 spvType = builder.makeRuntimeArray(spvType);
1993 } else {
1994 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001995 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001996 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001997 if (stride > 0)
1998 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001999 }
2000
2001 return spvType;
2002}
2003
John Kessenich6c292d32016-02-15 20:58:50 -07002004// Turn the expression forming the array size into an id.
2005// This is not quite trivial, because of specialization constants.
2006// Sometimes, a raw constant is turned into an Id, and sometimes
2007// a specialization constant expression is.
2008spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2009{
2010 // First, see if this is sized with a node, meaning a specialization constant:
2011 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2012 if (specNode != nullptr) {
2013 builder.clearAccessChain();
2014 specNode->traverse(this);
2015 return accessChainLoad(specNode->getAsTyped()->getType());
2016 }
qining25262b32016-05-06 17:25:16 -04002017
John Kessenich6c292d32016-02-15 20:58:50 -07002018 // Otherwise, need a compile-time (front end) size, get it:
2019 int size = arraySizes.getDimSize(dim);
2020 assert(size > 0);
2021 return builder.makeUintConstant(size);
2022}
2023
John Kessenich103bef92016-02-08 21:38:15 -07002024// Wrap the builder's accessChainLoad to:
2025// - localize handling of RelaxedPrecision
2026// - use the SPIR-V inferred type instead of another conversion of the glslang type
2027// (avoids unnecessary work and possible type punning for structures)
2028// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002029spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2030{
John Kessenich103bef92016-02-08 21:38:15 -07002031 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2032 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2033
2034 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002035 if (type.getBasicType() == glslang::EbtBool) {
2036 if (builder.isScalarType(nominalTypeId)) {
2037 // Conversion for bool
2038 spv::Id boolType = builder.makeBoolType();
2039 if (nominalTypeId != boolType)
2040 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2041 } else if (builder.isVectorType(nominalTypeId)) {
2042 // Conversion for bvec
2043 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2044 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2045 if (nominalTypeId != bvecType)
2046 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2047 }
2048 }
John Kessenich103bef92016-02-08 21:38:15 -07002049
2050 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002051}
2052
Rex Xu27253232016-02-23 17:51:09 +08002053// Wrap the builder's accessChainStore to:
2054// - do conversion of concrete to abstract type
2055void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2056{
2057 // Need to convert to abstract types when necessary
2058 if (type.getBasicType() == glslang::EbtBool) {
2059 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2060
2061 if (builder.isScalarType(nominalTypeId)) {
2062 // Conversion for bool
2063 spv::Id boolType = builder.makeBoolType();
2064 if (nominalTypeId != boolType) {
2065 spv::Id zero = builder.makeUintConstant(0);
2066 spv::Id one = builder.makeUintConstant(1);
2067 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2068 }
2069 } else if (builder.isVectorType(nominalTypeId)) {
2070 // Conversion for bvec
2071 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2072 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2073 if (nominalTypeId != bvecType) {
2074 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2075 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2076 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2077 }
2078 }
2079 }
2080
2081 builder.accessChainStore(rvalue);
2082}
2083
John Kessenichf85e8062015-12-19 13:57:10 -07002084// Decide whether or not this type should be
2085// decorated with offsets and strides, and if so
2086// whether std140 or std430 rules should be applied.
2087glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002088{
John Kessenichf85e8062015-12-19 13:57:10 -07002089 // has to be a block
2090 if (type.getBasicType() != glslang::EbtBlock)
2091 return glslang::ElpNone;
2092
2093 // has to be a uniform or buffer block
2094 if (type.getQualifier().storage != glslang::EvqUniform &&
2095 type.getQualifier().storage != glslang::EvqBuffer)
2096 return glslang::ElpNone;
2097
2098 // return the layout to use
2099 switch (type.getQualifier().layoutPacking) {
2100 case glslang::ElpStd140:
2101 case glslang::ElpStd430:
2102 return type.getQualifier().layoutPacking;
2103 default:
2104 return glslang::ElpNone;
2105 }
John Kessenich31ed4832015-09-09 17:51:38 -06002106}
2107
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002108// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002109int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002110{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002111 int size;
John Kessenich49987892015-12-29 17:11:44 -07002112 int stride;
2113 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002114
2115 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002116}
2117
John Kessenich49987892015-12-29 17:11:44 -07002118// 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 -07002119// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002120int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002121{
John Kessenich49987892015-12-29 17:11:44 -07002122 glslang::TType elementType;
2123 elementType.shallowCopy(matrixType);
2124 elementType.clearArraySizes();
2125
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002126 int size;
John Kessenich49987892015-12-29 17:11:44 -07002127 int stride;
2128 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2129
2130 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002131}
2132
John Kessenich5e4b1242015-08-06 22:53:06 -06002133// Given a member type of a struct, realign the current offset for it, and compute
2134// the next (not yet aligned) offset for the next member, which will get aligned
2135// on the next call.
2136// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2137// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2138// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002139void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002140 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002141{
2142 // this will get a positive value when deemed necessary
2143 nextOffset = -1;
2144
John Kessenich5e4b1242015-08-06 22:53:06 -06002145 // override anything in currentOffset with user-set offset
2146 if (memberType.getQualifier().hasOffset())
2147 currentOffset = memberType.getQualifier().layoutOffset;
2148
2149 // It could be that current linker usage in glslang updated all the layoutOffset,
2150 // in which case the following code does not matter. But, that's not quite right
2151 // once cross-compilation unit GLSL validation is done, as the original user
2152 // settings are needed in layoutOffset, and then the following will come into play.
2153
John Kessenichf85e8062015-12-19 13:57:10 -07002154 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002155 if (! memberType.getQualifier().hasOffset())
2156 currentOffset = -1;
2157
2158 return;
2159 }
2160
John Kessenichf85e8062015-12-19 13:57:10 -07002161 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002162 if (currentOffset < 0)
2163 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002164
John Kessenich5e4b1242015-08-06 22:53:06 -06002165 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2166 // but possibly not yet correctly aligned.
2167
2168 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002169 int dummyStride;
2170 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002171 glslang::RoundToPow2(currentOffset, memberAlignment);
2172 nextOffset = currentOffset + memberSize;
2173}
2174
John Kessenich140f3df2015-06-26 16:58:36 -06002175bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2176{
John Kessenich4d65ee32016-03-12 18:17:47 -07002177 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002178 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002179 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002180}
2181
2182// Make all the functions, skeletally, without actually visiting their bodies.
2183void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2184{
2185 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2186 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2187 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2188 continue;
2189
2190 // We're on a user function. Set up the basic interface for the function now,
2191 // so that it's available to call.
2192 // Translating the body will happen later.
2193 //
qining25262b32016-05-06 17:25:16 -04002194 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002195 // function. What it is an address of varies:
2196 //
2197 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2198 // so that write needs to be to a copy, hence the address of a copy works.
2199 //
2200 // - "const in" parameters can just be the r-value, as no writes need occur.
2201 //
2202 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2203 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2204
2205 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002206 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002207 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2208
2209 for (int p = 0; p < (int)parameters.size(); ++p) {
2210 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2211 spv::Id typeId = convertGlslangToSpvType(paramType);
2212 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2213 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2214 else
2215 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002216 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002217 paramTypes.push_back(typeId);
2218 }
2219
2220 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002221 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2222 convertGlslangToSpvType(glslFunction->getType()),
2223 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002224
2225 // Track function to emit/call later
2226 functionMap[glslFunction->getName().c_str()] = function;
2227
2228 // Set the parameter id's
2229 for (int p = 0; p < (int)parameters.size(); ++p) {
2230 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2231 // give a name too
2232 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2233 }
2234 }
2235}
2236
2237// Process all the initializers, while skipping the functions and link objects
2238void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2239{
2240 builder.setBuildPoint(shaderEntry->getLastBlock());
2241 for (int i = 0; i < (int)initializers.size(); ++i) {
2242 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2243 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2244
2245 // We're on a top-level node that's not a function. Treat as an initializer, whose
2246 // code goes into the beginning of main.
2247 initializer->traverse(this);
2248 }
2249 }
2250}
2251
2252// Process all the functions, while skipping initializers.
2253void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2254{
2255 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2256 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2257 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2258 node->traverse(this);
2259 }
2260}
2261
2262void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2263{
qining25262b32016-05-06 17:25:16 -04002264 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002265 // that called makeFunctions().
2266 spv::Function* function = functionMap[node->getName().c_str()];
2267 spv::Block* functionBlock = function->getEntryBlock();
2268 builder.setBuildPoint(functionBlock);
2269}
2270
Rex Xu04db3f52015-09-16 11:44:02 +08002271void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002272{
Rex Xufc618912015-09-09 16:42:49 +08002273 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002274
2275 glslang::TSampler sampler = {};
2276 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002277 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002278 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2279 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2280 }
2281
John Kessenich140f3df2015-06-26 16:58:36 -06002282 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2283 builder.clearAccessChain();
2284 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002285
2286 // Special case l-value operands
2287 bool lvalue = false;
2288 switch (node.getOp()) {
2289 case glslang::EOpImageAtomicAdd:
2290 case glslang::EOpImageAtomicMin:
2291 case glslang::EOpImageAtomicMax:
2292 case glslang::EOpImageAtomicAnd:
2293 case glslang::EOpImageAtomicOr:
2294 case glslang::EOpImageAtomicXor:
2295 case glslang::EOpImageAtomicExchange:
2296 case glslang::EOpImageAtomicCompSwap:
2297 if (i == 0)
2298 lvalue = true;
2299 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002300 case glslang::EOpSparseImageLoad:
2301 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2302 lvalue = true;
2303 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002304 case glslang::EOpSparseTexture:
2305 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2306 lvalue = true;
2307 break;
2308 case glslang::EOpSparseTextureClamp:
2309 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2310 lvalue = true;
2311 break;
2312 case glslang::EOpSparseTextureLod:
2313 case glslang::EOpSparseTextureOffset:
2314 if (i == 3)
2315 lvalue = true;
2316 break;
2317 case glslang::EOpSparseTextureFetch:
2318 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2319 lvalue = true;
2320 break;
2321 case glslang::EOpSparseTextureFetchOffset:
2322 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2323 lvalue = true;
2324 break;
2325 case glslang::EOpSparseTextureLodOffset:
2326 case glslang::EOpSparseTextureGrad:
2327 case glslang::EOpSparseTextureOffsetClamp:
2328 if (i == 4)
2329 lvalue = true;
2330 break;
2331 case glslang::EOpSparseTextureGradOffset:
2332 case glslang::EOpSparseTextureGradClamp:
2333 if (i == 5)
2334 lvalue = true;
2335 break;
2336 case glslang::EOpSparseTextureGradOffsetClamp:
2337 if (i == 6)
2338 lvalue = true;
2339 break;
2340 case glslang::EOpSparseTextureGather:
2341 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2342 lvalue = true;
2343 break;
2344 case glslang::EOpSparseTextureGatherOffset:
2345 case glslang::EOpSparseTextureGatherOffsets:
2346 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2347 lvalue = true;
2348 break;
Rex Xufc618912015-09-09 16:42:49 +08002349 default:
2350 break;
2351 }
2352
Rex Xu6b86d492015-09-16 17:48:22 +08002353 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002354 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002355 else
John Kessenich32cfd492016-02-02 12:37:46 -07002356 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002357 }
2358}
2359
John Kessenichfc51d282015-08-19 13:34:18 -06002360void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002361{
John Kessenichfc51d282015-08-19 13:34:18 -06002362 builder.clearAccessChain();
2363 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002364 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002365}
John Kessenich140f3df2015-06-26 16:58:36 -06002366
John Kessenichfc51d282015-08-19 13:34:18 -06002367spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2368{
Rex Xufc618912015-09-09 16:42:49 +08002369 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002370 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002371 }
2372
John Kessenichfc51d282015-08-19 13:34:18 -06002373 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002374 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2375 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2376 std::vector<spv::Id> arguments;
2377 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002378 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002379 else
2380 translateArguments(*node->getAsUnaryNode(), arguments);
2381 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2382
2383 spv::Builder::TextureParameters params = { };
2384 params.sampler = arguments[0];
2385
Rex Xu04db3f52015-09-16 11:44:02 +08002386 glslang::TCrackedTextureOp cracked;
2387 node->crackTexture(sampler, cracked);
2388
John Kessenichfc51d282015-08-19 13:34:18 -06002389 // Check for queries
2390 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002391 // a sampled image needs to have the image extracted first
2392 if (builder.isSampledImage(params.sampler))
2393 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002394 switch (node->getOp()) {
2395 case glslang::EOpImageQuerySize:
2396 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002397 if (arguments.size() > 1) {
2398 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002399 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002400 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002401 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002402 case glslang::EOpImageQuerySamples:
2403 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002404 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002405 case glslang::EOpTextureQueryLod:
2406 params.coords = arguments[1];
2407 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2408 case glslang::EOpTextureQueryLevels:
2409 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002410 case glslang::EOpSparseTexelsResident:
2411 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002412 default:
2413 assert(0);
2414 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002415 }
John Kessenich140f3df2015-06-26 16:58:36 -06002416 }
2417
Rex Xufc618912015-09-09 16:42:49 +08002418 // Check for image functions other than queries
2419 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002420 std::vector<spv::Id> operands;
2421 auto opIt = arguments.begin();
2422 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002423
2424 // Handle subpass operations
2425 // TODO: GLSL should change to have the "MS" only on the type rather than the
2426 // built-in function.
2427 if (cracked.subpass) {
2428 // add on the (0,0) coordinate
2429 spv::Id zero = builder.makeIntConstant(0);
2430 std::vector<spv::Id> comps;
2431 comps.push_back(zero);
2432 comps.push_back(zero);
2433 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2434 if (sampler.ms) {
2435 operands.push_back(spv::ImageOperandsSampleMask);
2436 operands.push_back(*(opIt++));
2437 }
2438 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2439 }
2440
John Kessenich56bab042015-09-16 10:54:31 -06002441 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002442 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002443 if (sampler.ms) {
2444 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002445 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002446 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002447 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2448 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002449 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002450 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002451 if (sampler.ms) {
2452 operands.push_back(*(opIt + 1));
2453 operands.push_back(spv::ImageOperandsSampleMask);
2454 operands.push_back(*opIt);
2455 } else
2456 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002457 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002458 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2459 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002460 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002461 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2462 builder.addCapability(spv::CapabilitySparseResidency);
2463 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2464 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2465
2466 if (sampler.ms) {
2467 operands.push_back(spv::ImageOperandsSampleMask);
2468 operands.push_back(*opIt++);
2469 }
2470
2471 // Create the return type that was a special structure
2472 spv::Id texelOut = *opIt;
2473 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2474 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2475 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2476
2477 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2478
2479 // Decode the return type
2480 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2481 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002482 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002483 // Process image atomic operations
2484
2485 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2486 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002487 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002488
Rex Xufc618912015-09-09 16:42:49 +08002489 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002490 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002491
2492 std::vector<spv::Id> operands;
2493 operands.push_back(pointer);
2494 for (; opIt != arguments.end(); ++opIt)
2495 operands.push_back(*opIt);
2496
Rex Xu04db3f52015-09-16 11:44:02 +08002497 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002498 }
2499 }
2500
2501 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002502 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002503 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2504
John Kessenichfc51d282015-08-19 13:34:18 -06002505 // check for bias argument
2506 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002507 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002508 int nonBiasArgCount = 2;
2509 if (cracked.offset)
2510 ++nonBiasArgCount;
2511 if (cracked.grad)
2512 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002513 if (cracked.lodClamp)
2514 ++nonBiasArgCount;
2515 if (sparse)
2516 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002517
2518 if ((int)arguments.size() > nonBiasArgCount)
2519 bias = true;
2520 }
2521
John Kessenichfc51d282015-08-19 13:34:18 -06002522 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002523
John Kessenichfc51d282015-08-19 13:34:18 -06002524 params.coords = arguments[1];
2525 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002526 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002527
2528 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002529 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002530 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002531 ++extraArgs;
2532 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002533 params.Dref = arguments[2];
2534 ++extraArgs;
2535 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002536 std::vector<spv::Id> indexes;
2537 int comp;
2538 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002539 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002540 else
2541 comp = builder.getNumComponents(params.coords) - 1;
2542 indexes.push_back(comp);
2543 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2544 }
2545 if (cracked.lod) {
2546 params.lod = arguments[2];
2547 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002548 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2549 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2550 noImplicitLod = true;
2551 }
2552 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002553 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002554 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002555 }
2556 if (cracked.grad) {
2557 params.gradX = arguments[2 + extraArgs];
2558 params.gradY = arguments[3 + extraArgs];
2559 extraArgs += 2;
2560 }
John Kessenich55e7d112015-11-15 21:33:39 -07002561 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002562 params.offset = arguments[2 + extraArgs];
2563 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002564 } else if (cracked.offsets) {
2565 params.offsets = arguments[2 + extraArgs];
2566 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002567 }
Rex Xu48edadf2015-12-31 16:11:41 +08002568 if (cracked.lodClamp) {
2569 params.lodClamp = arguments[2 + extraArgs];
2570 ++extraArgs;
2571 }
2572 if (sparse) {
2573 params.texelOut = arguments[2 + extraArgs];
2574 ++extraArgs;
2575 }
John Kessenichfc51d282015-08-19 13:34:18 -06002576 if (bias) {
2577 params.bias = arguments[2 + extraArgs];
2578 ++extraArgs;
2579 }
John Kessenich55e7d112015-11-15 21:33:39 -07002580 if (cracked.gather && ! sampler.shadow) {
2581 // default component is 0, if missing, otherwise an argument
2582 if (2 + extraArgs < (int)arguments.size()) {
2583 params.comp = arguments[2 + extraArgs];
2584 ++extraArgs;
2585 } else {
2586 params.comp = builder.makeIntConstant(0);
2587 }
2588 }
John Kessenichfc51d282015-08-19 13:34:18 -06002589
John Kessenich019f08f2016-02-15 15:40:42 -07002590 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002591}
2592
2593spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2594{
2595 // Grab the function's pointer from the previously created function
2596 spv::Function* function = functionMap[node->getName().c_str()];
2597 if (! function)
2598 return 0;
2599
2600 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2601 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2602
2603 // See comments in makeFunctions() for details about the semantics for parameter passing.
2604 //
2605 // These imply we need a four step process:
2606 // 1. Evaluate the arguments
2607 // 2. Allocate and make copies of in, out, and inout arguments
2608 // 3. Make the call
2609 // 4. Copy back the results
2610
2611 // 1. Evaluate the arguments
2612 std::vector<spv::Builder::AccessChain> lValues;
2613 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002614 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002615 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2616 // build l-value
2617 builder.clearAccessChain();
2618 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002619 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002620 // keep outputs as l-values, evaluate input-only as r-values
2621 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2622 // save l-value
2623 lValues.push_back(builder.getAccessChain());
2624 } else {
2625 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002626 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002627 }
2628 }
2629
2630 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2631 // copy the original into that space.
2632 //
2633 // Also, build up the list of actual arguments to pass in for the call
2634 int lValueCount = 0;
2635 int rValueCount = 0;
2636 std::vector<spv::Id> spvArgs;
2637 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2638 spv::Id arg;
2639 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2640 // need space to hold the copy
2641 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2642 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2643 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2644 // need to copy the input into output space
2645 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002646 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002647 builder.createStore(copy, arg);
2648 }
2649 ++lValueCount;
2650 } else {
2651 arg = rValues[rValueCount];
2652 ++rValueCount;
2653 }
2654 spvArgs.push_back(arg);
2655 }
2656
2657 // 3. Make the call.
2658 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002659 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002660
2661 // 4. Copy back out an "out" arguments.
2662 lValueCount = 0;
2663 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2664 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2665 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2666 spv::Id copy = builder.createLoad(spvArgs[a]);
2667 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002668 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002669 }
2670 ++lValueCount;
2671 }
2672 }
2673
2674 return result;
2675}
2676
2677// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002678spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2679 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002680 spv::Id typeId, spv::Id left, spv::Id right,
2681 glslang::TBasicType typeProxy, bool reduceComparison)
2682{
Rex Xu8ff43de2016-04-22 16:51:45 +08002683 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002684 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002685 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002686
2687 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002688 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002689 bool comparison = false;
2690
2691 switch (op) {
2692 case glslang::EOpAdd:
2693 case glslang::EOpAddAssign:
2694 if (isFloat)
2695 binOp = spv::OpFAdd;
2696 else
2697 binOp = spv::OpIAdd;
2698 break;
2699 case glslang::EOpSub:
2700 case glslang::EOpSubAssign:
2701 if (isFloat)
2702 binOp = spv::OpFSub;
2703 else
2704 binOp = spv::OpISub;
2705 break;
2706 case glslang::EOpMul:
2707 case glslang::EOpMulAssign:
2708 if (isFloat)
2709 binOp = spv::OpFMul;
2710 else
2711 binOp = spv::OpIMul;
2712 break;
2713 case glslang::EOpVectorTimesScalar:
2714 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002715 if (isFloat) {
2716 if (builder.isVector(right))
2717 std::swap(left, right);
2718 assert(builder.isScalar(right));
2719 needMatchingVectors = false;
2720 binOp = spv::OpVectorTimesScalar;
2721 } else
2722 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002723 break;
2724 case glslang::EOpVectorTimesMatrix:
2725 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002726 binOp = spv::OpVectorTimesMatrix;
2727 break;
2728 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002729 binOp = spv::OpMatrixTimesVector;
2730 break;
2731 case glslang::EOpMatrixTimesScalar:
2732 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002733 binOp = spv::OpMatrixTimesScalar;
2734 break;
2735 case glslang::EOpMatrixTimesMatrix:
2736 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002737 binOp = spv::OpMatrixTimesMatrix;
2738 break;
2739 case glslang::EOpOuterProduct:
2740 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002741 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002742 break;
2743
2744 case glslang::EOpDiv:
2745 case glslang::EOpDivAssign:
2746 if (isFloat)
2747 binOp = spv::OpFDiv;
2748 else if (isUnsigned)
2749 binOp = spv::OpUDiv;
2750 else
2751 binOp = spv::OpSDiv;
2752 break;
2753 case glslang::EOpMod:
2754 case glslang::EOpModAssign:
2755 if (isFloat)
2756 binOp = spv::OpFMod;
2757 else if (isUnsigned)
2758 binOp = spv::OpUMod;
2759 else
2760 binOp = spv::OpSMod;
2761 break;
2762 case glslang::EOpRightShift:
2763 case glslang::EOpRightShiftAssign:
2764 if (isUnsigned)
2765 binOp = spv::OpShiftRightLogical;
2766 else
2767 binOp = spv::OpShiftRightArithmetic;
2768 break;
2769 case glslang::EOpLeftShift:
2770 case glslang::EOpLeftShiftAssign:
2771 binOp = spv::OpShiftLeftLogical;
2772 break;
2773 case glslang::EOpAnd:
2774 case glslang::EOpAndAssign:
2775 binOp = spv::OpBitwiseAnd;
2776 break;
2777 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002778 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002779 binOp = spv::OpLogicalAnd;
2780 break;
2781 case glslang::EOpInclusiveOr:
2782 case glslang::EOpInclusiveOrAssign:
2783 binOp = spv::OpBitwiseOr;
2784 break;
2785 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002786 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002787 binOp = spv::OpLogicalOr;
2788 break;
2789 case glslang::EOpExclusiveOr:
2790 case glslang::EOpExclusiveOrAssign:
2791 binOp = spv::OpBitwiseXor;
2792 break;
2793 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002794 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002795 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002796 break;
2797
2798 case glslang::EOpLessThan:
2799 case glslang::EOpGreaterThan:
2800 case glslang::EOpLessThanEqual:
2801 case glslang::EOpGreaterThanEqual:
2802 case glslang::EOpEqual:
2803 case glslang::EOpNotEqual:
2804 case glslang::EOpVectorEqual:
2805 case glslang::EOpVectorNotEqual:
2806 comparison = true;
2807 break;
2808 default:
2809 break;
2810 }
2811
John Kessenich7c1aa102015-10-15 13:29:11 -06002812 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002813 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002814 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002815 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002816 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002817
2818 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002819 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002820 builder.promoteScalar(precision, left, right);
2821
qining25262b32016-05-06 17:25:16 -04002822 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2823 addDecoration(result, noContraction);
2824 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002825 }
2826
2827 if (! comparison)
2828 return 0;
2829
John Kessenich7c1aa102015-10-15 13:29:11 -06002830 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002831
2832 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2833 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2834
John Kessenich22118352015-12-21 20:54:09 -07002835 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002836 }
2837
2838 switch (op) {
2839 case glslang::EOpLessThan:
2840 if (isFloat)
2841 binOp = spv::OpFOrdLessThan;
2842 else if (isUnsigned)
2843 binOp = spv::OpULessThan;
2844 else
2845 binOp = spv::OpSLessThan;
2846 break;
2847 case glslang::EOpGreaterThan:
2848 if (isFloat)
2849 binOp = spv::OpFOrdGreaterThan;
2850 else if (isUnsigned)
2851 binOp = spv::OpUGreaterThan;
2852 else
2853 binOp = spv::OpSGreaterThan;
2854 break;
2855 case glslang::EOpLessThanEqual:
2856 if (isFloat)
2857 binOp = spv::OpFOrdLessThanEqual;
2858 else if (isUnsigned)
2859 binOp = spv::OpULessThanEqual;
2860 else
2861 binOp = spv::OpSLessThanEqual;
2862 break;
2863 case glslang::EOpGreaterThanEqual:
2864 if (isFloat)
2865 binOp = spv::OpFOrdGreaterThanEqual;
2866 else if (isUnsigned)
2867 binOp = spv::OpUGreaterThanEqual;
2868 else
2869 binOp = spv::OpSGreaterThanEqual;
2870 break;
2871 case glslang::EOpEqual:
2872 case glslang::EOpVectorEqual:
2873 if (isFloat)
2874 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002875 else if (isBool)
2876 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002877 else
2878 binOp = spv::OpIEqual;
2879 break;
2880 case glslang::EOpNotEqual:
2881 case glslang::EOpVectorNotEqual:
2882 if (isFloat)
2883 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002884 else if (isBool)
2885 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002886 else
2887 binOp = spv::OpINotEqual;
2888 break;
2889 default:
2890 break;
2891 }
2892
qining25262b32016-05-06 17:25:16 -04002893 if (binOp != spv::OpNop) {
2894 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2895 addDecoration(result, noContraction);
2896 return builder.setPrecision(result, precision);
2897 }
John Kessenich140f3df2015-06-26 16:58:36 -06002898
2899 return 0;
2900}
2901
John Kessenich04bb8a02015-12-12 12:28:14 -07002902//
2903// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2904// These can be any of:
2905//
2906// matrix * scalar
2907// scalar * matrix
2908// matrix * matrix linear algebraic
2909// matrix * vector
2910// vector * matrix
2911// matrix * matrix componentwise
2912// matrix op matrix op in {+, -, /}
2913// matrix op scalar op in {+, -, /}
2914// scalar op matrix op in {+, -, /}
2915//
qining25262b32016-05-06 17:25:16 -04002916spv::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 -07002917{
2918 bool firstClass = true;
2919
2920 // First, handle first-class matrix operations (* and matrix/scalar)
2921 switch (op) {
2922 case spv::OpFDiv:
2923 if (builder.isMatrix(left) && builder.isScalar(right)) {
2924 // turn matrix / scalar into a multiply...
2925 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2926 op = spv::OpMatrixTimesScalar;
2927 } else
2928 firstClass = false;
2929 break;
2930 case spv::OpMatrixTimesScalar:
2931 if (builder.isMatrix(right))
2932 std::swap(left, right);
2933 assert(builder.isScalar(right));
2934 break;
2935 case spv::OpVectorTimesMatrix:
2936 assert(builder.isVector(left));
2937 assert(builder.isMatrix(right));
2938 break;
2939 case spv::OpMatrixTimesVector:
2940 assert(builder.isMatrix(left));
2941 assert(builder.isVector(right));
2942 break;
2943 case spv::OpMatrixTimesMatrix:
2944 assert(builder.isMatrix(left));
2945 assert(builder.isMatrix(right));
2946 break;
2947 default:
2948 firstClass = false;
2949 break;
2950 }
2951
qining25262b32016-05-06 17:25:16 -04002952 if (firstClass) {
2953 spv::Id result = builder.createBinOp(op, typeId, left, right);
2954 addDecoration(result, noContraction);
2955 return builder.setPrecision(result, precision);
2956 }
John Kessenich04bb8a02015-12-12 12:28:14 -07002957
2958 // Handle component-wise +, -, *, and / for all combinations of type.
2959 // The result type of all of them is the same type as the (a) matrix operand.
2960 // The algorithm is to:
2961 // - break the matrix(es) into vectors
2962 // - smear any scalar to a vector
2963 // - do vector operations
2964 // - make a matrix out the vector results
2965 switch (op) {
2966 case spv::OpFAdd:
2967 case spv::OpFSub:
2968 case spv::OpFDiv:
2969 case spv::OpFMul:
2970 {
2971 // one time set up...
2972 bool leftMat = builder.isMatrix(left);
2973 bool rightMat = builder.isMatrix(right);
2974 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2975 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2976 spv::Id scalarType = builder.getScalarTypeId(typeId);
2977 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2978 std::vector<spv::Id> results;
2979 spv::Id smearVec = spv::NoResult;
2980 if (builder.isScalar(left))
2981 smearVec = builder.smearScalar(precision, left, vecType);
2982 else if (builder.isScalar(right))
2983 smearVec = builder.smearScalar(precision, right, vecType);
2984
2985 // do each vector op
2986 for (unsigned int c = 0; c < numCols; ++c) {
2987 std::vector<unsigned int> indexes;
2988 indexes.push_back(c);
2989 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2990 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04002991 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
2992 addDecoration(result, noContraction);
2993 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07002994 }
2995
2996 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002997 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002998 }
2999 default:
3000 assert(0);
3001 return spv::NoResult;
3002 }
3003}
3004
qining25262b32016-05-06 17:25:16 -04003005spv::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 -06003006{
3007 spv::Op unaryOp = spv::OpNop;
3008 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003009 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003010 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003011
3012 switch (op) {
3013 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003014 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003015 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003016 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003017 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003018 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003019 unaryOp = spv::OpSNegate;
3020 break;
3021
3022 case glslang::EOpLogicalNot:
3023 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003024 unaryOp = spv::OpLogicalNot;
3025 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 case glslang::EOpBitwiseNot:
3027 unaryOp = spv::OpNot;
3028 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003029
John Kessenich140f3df2015-06-26 16:58:36 -06003030 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003031 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 break;
3033 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003034 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003035 break;
3036 case glslang::EOpTranspose:
3037 unaryOp = spv::OpTranspose;
3038 break;
3039
3040 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003050 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
3052 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003053 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003054 break;
3055 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003056 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 break;
3058 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003059 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003060 break;
3061 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003062 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003063 break;
3064
3065 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003066 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003067 break;
3068 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003069 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003070 break;
3071 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003072 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003073 break;
3074 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003075 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003076 break;
3077 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003078 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003079 break;
3080 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003081 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003082 break;
3083
3084 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003085 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003086 break;
3087 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003088 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003089 break;
3090
3091 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003095 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
3097 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003098 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003099 break;
3100 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003101 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003102 break;
3103 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003104 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003105 break;
3106 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003107 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003108 break;
3109
3110 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003111 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003112 break;
3113 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003114 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003115 break;
3116 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003118 break;
3119 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128
3129 case glslang::EOpIsNan:
3130 unaryOp = spv::OpIsNan;
3131 break;
3132 case glslang::EOpIsInf:
3133 unaryOp = spv::OpIsInf;
3134 break;
3135
Rex Xucbc426e2015-12-15 16:03:10 +08003136 case glslang::EOpFloatBitsToInt:
3137 case glslang::EOpFloatBitsToUint:
3138 case glslang::EOpIntBitsToFloat:
3139 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003140 case glslang::EOpDoubleBitsToInt64:
3141 case glslang::EOpDoubleBitsToUint64:
3142 case glslang::EOpInt64BitsToDouble:
3143 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003144 unaryOp = spv::OpBitcast;
3145 break;
3146
John Kessenich140f3df2015-06-26 16:58:36 -06003147 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003148 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003149 break;
3150 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003151 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003152 break;
3153 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003154 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003155 break;
3156 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003157 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003158 break;
3159 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003160 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003161 break;
3162 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003163 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003164 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003165 case glslang::EOpPackSnorm4x8:
3166 libCall = spv::GLSLstd450PackSnorm4x8;
3167 break;
3168 case glslang::EOpUnpackSnorm4x8:
3169 libCall = spv::GLSLstd450UnpackSnorm4x8;
3170 break;
3171 case glslang::EOpPackUnorm4x8:
3172 libCall = spv::GLSLstd450PackUnorm4x8;
3173 break;
3174 case glslang::EOpUnpackUnorm4x8:
3175 libCall = spv::GLSLstd450UnpackUnorm4x8;
3176 break;
3177 case glslang::EOpPackDouble2x32:
3178 libCall = spv::GLSLstd450PackDouble2x32;
3179 break;
3180 case glslang::EOpUnpackDouble2x32:
3181 libCall = spv::GLSLstd450UnpackDouble2x32;
3182 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003183
Rex Xu8ff43de2016-04-22 16:51:45 +08003184 case glslang::EOpPackInt2x32:
3185 case glslang::EOpUnpackInt2x32:
3186 case glslang::EOpPackUint2x32:
3187 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003188 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003189 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3190 break;
3191
John Kessenich140f3df2015-06-26 16:58:36 -06003192 case glslang::EOpDPdx:
3193 unaryOp = spv::OpDPdx;
3194 break;
3195 case glslang::EOpDPdy:
3196 unaryOp = spv::OpDPdy;
3197 break;
3198 case glslang::EOpFwidth:
3199 unaryOp = spv::OpFwidth;
3200 break;
3201 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003202 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003203 unaryOp = spv::OpDPdxFine;
3204 break;
3205 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003206 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003207 unaryOp = spv::OpDPdyFine;
3208 break;
3209 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003210 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003211 unaryOp = spv::OpFwidthFine;
3212 break;
3213 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003214 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003215 unaryOp = spv::OpDPdxCoarse;
3216 break;
3217 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003218 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003219 unaryOp = spv::OpDPdyCoarse;
3220 break;
3221 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003222 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003223 unaryOp = spv::OpFwidthCoarse;
3224 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003225 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003226 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003227 libCall = spv::GLSLstd450InterpolateAtCentroid;
3228 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003229 case glslang::EOpAny:
3230 unaryOp = spv::OpAny;
3231 break;
3232 case glslang::EOpAll:
3233 unaryOp = spv::OpAll;
3234 break;
3235
3236 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003237 if (isFloat)
3238 libCall = spv::GLSLstd450FAbs;
3239 else
3240 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 break;
3242 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003243 if (isFloat)
3244 libCall = spv::GLSLstd450FSign;
3245 else
3246 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003247 break;
3248
John Kessenichfc51d282015-08-19 13:34:18 -06003249 case glslang::EOpAtomicCounterIncrement:
3250 case glslang::EOpAtomicCounterDecrement:
3251 case glslang::EOpAtomicCounter:
3252 {
3253 // Handle all of the atomics in one place, in createAtomicOperation()
3254 std::vector<spv::Id> operands;
3255 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003256 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003257 }
3258
John Kessenichfc51d282015-08-19 13:34:18 -06003259 case glslang::EOpBitFieldReverse:
3260 unaryOp = spv::OpBitReverse;
3261 break;
3262 case glslang::EOpBitCount:
3263 unaryOp = spv::OpBitCount;
3264 break;
3265 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003266 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003267 break;
3268 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003269 if (isUnsigned)
3270 libCall = spv::GLSLstd450FindUMsb;
3271 else
3272 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003273 break;
3274
Rex Xu574ab042016-04-14 16:53:07 +08003275 case glslang::EOpBallot:
3276 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003277 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003278 libCall = spv::GLSLstd450Bad;
3279 break;
3280
Rex Xu338b1852016-05-05 20:38:33 +08003281 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003282 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003283 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003284 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003285
John Kessenich140f3df2015-06-26 16:58:36 -06003286 default:
3287 return 0;
3288 }
3289
3290 spv::Id id;
3291 if (libCall >= 0) {
3292 std::vector<spv::Id> args;
3293 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003294 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003295 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003296 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003297 }
John Kessenich140f3df2015-06-26 16:58:36 -06003298
qining25262b32016-05-06 17:25:16 -04003299 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003300 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003301}
3302
John Kessenich7a53f762016-01-20 11:19:27 -07003303// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003304spv::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 -07003305{
3306 // Handle unary operations vector by vector.
3307 // The result type is the same type as the original type.
3308 // The algorithm is to:
3309 // - break the matrix into vectors
3310 // - apply the operation to each vector
3311 // - make a matrix out the vector results
3312
3313 // get the types sorted out
3314 int numCols = builder.getNumColumns(operand);
3315 int numRows = builder.getNumRows(operand);
3316 spv::Id scalarType = builder.getScalarTypeId(typeId);
3317 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3318 std::vector<spv::Id> results;
3319
3320 // do each vector op
3321 for (int c = 0; c < numCols; ++c) {
3322 std::vector<unsigned int> indexes;
3323 indexes.push_back(c);
3324 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
qining25262b32016-05-06 17:25:16 -04003325 spv::Id vec_result = builder.createUnaryOp(op, vecType, vec);
3326 addDecoration(vec_result, noContraction);
3327 results.push_back(builder.setPrecision(vec_result, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003328 }
3329
3330 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003331 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003332}
3333
John Kessenich140f3df2015-06-26 16:58:36 -06003334spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3335{
3336 spv::Op convOp = spv::OpNop;
3337 spv::Id zero = 0;
3338 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003339 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003340
3341 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3342
3343 switch (op) {
3344 case glslang::EOpConvIntToBool:
3345 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003346 case glslang::EOpConvInt64ToBool:
3347 case glslang::EOpConvUint64ToBool:
3348 zero = (op == glslang::EOpConvInt64ToBool ||
3349 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003350 zero = makeSmearedConstant(zero, vectorSize);
3351 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3352
3353 case glslang::EOpConvFloatToBool:
3354 zero = builder.makeFloatConstant(0.0F);
3355 zero = makeSmearedConstant(zero, vectorSize);
3356 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3357
3358 case glslang::EOpConvDoubleToBool:
3359 zero = builder.makeDoubleConstant(0.0);
3360 zero = makeSmearedConstant(zero, vectorSize);
3361 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3362
3363 case glslang::EOpConvBoolToFloat:
3364 convOp = spv::OpSelect;
3365 zero = builder.makeFloatConstant(0.0);
3366 one = builder.makeFloatConstant(1.0);
3367 break;
3368 case glslang::EOpConvBoolToDouble:
3369 convOp = spv::OpSelect;
3370 zero = builder.makeDoubleConstant(0.0);
3371 one = builder.makeDoubleConstant(1.0);
3372 break;
3373 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003374 case glslang::EOpConvBoolToInt64:
3375 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3376 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003377 convOp = spv::OpSelect;
3378 break;
3379 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003380 case glslang::EOpConvBoolToUint64:
3381 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3382 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003383 convOp = spv::OpSelect;
3384 break;
3385
3386 case glslang::EOpConvIntToFloat:
3387 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003388 case glslang::EOpConvInt64ToFloat:
3389 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003390 convOp = spv::OpConvertSToF;
3391 break;
3392
3393 case glslang::EOpConvUintToFloat:
3394 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003395 case glslang::EOpConvUint64ToFloat:
3396 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003397 convOp = spv::OpConvertUToF;
3398 break;
3399
3400 case glslang::EOpConvDoubleToFloat:
3401 case glslang::EOpConvFloatToDouble:
3402 convOp = spv::OpFConvert;
3403 break;
3404
3405 case glslang::EOpConvFloatToInt:
3406 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003407 case glslang::EOpConvFloatToInt64:
3408 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003409 convOp = spv::OpConvertFToS;
3410 break;
3411
3412 case glslang::EOpConvUintToInt:
3413 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003414 case glslang::EOpConvUint64ToInt64:
3415 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003416 if (builder.isInSpecConstCodeGenMode()) {
3417 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003418 zero = (op == glslang::EOpConvUintToInt64 ||
3419 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003420 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003421 // Use OpIAdd, instead of OpBitcast to do the conversion when
3422 // generating for OpSpecConstantOp instruction.
3423 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3424 }
3425 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003426 convOp = spv::OpBitcast;
3427 break;
3428
3429 case glslang::EOpConvFloatToUint:
3430 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003431 case glslang::EOpConvFloatToUint64:
3432 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003433 convOp = spv::OpConvertFToU;
3434 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003435
3436 case glslang::EOpConvIntToInt64:
3437 case glslang::EOpConvInt64ToInt:
3438 convOp = spv::OpSConvert;
3439 break;
3440
3441 case glslang::EOpConvUintToUint64:
3442 case glslang::EOpConvUint64ToUint:
3443 convOp = spv::OpUConvert;
3444 break;
3445
3446 case glslang::EOpConvIntToUint64:
3447 case glslang::EOpConvInt64ToUint:
3448 case glslang::EOpConvUint64ToInt:
3449 case glslang::EOpConvUintToInt64:
3450 // OpSConvert/OpUConvert + OpBitCast
3451 switch (op) {
3452 case glslang::EOpConvIntToUint64:
3453 convOp = spv::OpSConvert;
3454 type = builder.makeIntType(64);
3455 break;
3456 case glslang::EOpConvInt64ToUint:
3457 convOp = spv::OpSConvert;
3458 type = builder.makeIntType(32);
3459 break;
3460 case glslang::EOpConvUint64ToInt:
3461 convOp = spv::OpUConvert;
3462 type = builder.makeUintType(32);
3463 break;
3464 case glslang::EOpConvUintToInt64:
3465 convOp = spv::OpUConvert;
3466 type = builder.makeUintType(64);
3467 break;
3468 default:
3469 assert(0);
3470 break;
3471 }
3472
3473 if (vectorSize > 0)
3474 type = builder.makeVectorType(type, vectorSize);
3475
3476 operand = builder.createUnaryOp(convOp, type, operand);
3477
3478 if (builder.isInSpecConstCodeGenMode()) {
3479 // Build zero scalar or vector for OpIAdd.
3480 zero = (op == glslang::EOpConvIntToUint64 ||
3481 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3482 zero = makeSmearedConstant(zero, vectorSize);
3483 // Use OpIAdd, instead of OpBitcast to do the conversion when
3484 // generating for OpSpecConstantOp instruction.
3485 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3486 }
3487 // For normal run-time conversion instruction, use OpBitcast.
3488 convOp = spv::OpBitcast;
3489 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003490 default:
3491 break;
3492 }
3493
3494 spv::Id result = 0;
3495 if (convOp == spv::OpNop)
3496 return result;
3497
3498 if (convOp == spv::OpSelect) {
3499 zero = makeSmearedConstant(zero, vectorSize);
3500 one = makeSmearedConstant(one, vectorSize);
3501 result = builder.createTriOp(convOp, destType, operand, one, zero);
3502 } else
3503 result = builder.createUnaryOp(convOp, destType, operand);
3504
John Kessenich32cfd492016-02-02 12:37:46 -07003505 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003506}
3507
3508spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3509{
3510 if (vectorSize == 0)
3511 return constant;
3512
3513 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3514 std::vector<spv::Id> components;
3515 for (int c = 0; c < vectorSize; ++c)
3516 components.push_back(constant);
3517 return builder.makeCompositeConstant(vectorTypeId, components);
3518}
3519
John Kessenich426394d2015-07-23 10:22:48 -06003520// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003521spv::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 -06003522{
3523 spv::Op opCode = spv::OpNop;
3524
3525 switch (op) {
3526 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003527 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003528 opCode = spv::OpAtomicIAdd;
3529 break;
3530 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003531 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003532 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003533 break;
3534 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003535 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003536 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003537 break;
3538 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003539 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003540 opCode = spv::OpAtomicAnd;
3541 break;
3542 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003543 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003544 opCode = spv::OpAtomicOr;
3545 break;
3546 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003547 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003548 opCode = spv::OpAtomicXor;
3549 break;
3550 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003551 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003552 opCode = spv::OpAtomicExchange;
3553 break;
3554 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003555 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003556 opCode = spv::OpAtomicCompareExchange;
3557 break;
3558 case glslang::EOpAtomicCounterIncrement:
3559 opCode = spv::OpAtomicIIncrement;
3560 break;
3561 case glslang::EOpAtomicCounterDecrement:
3562 opCode = spv::OpAtomicIDecrement;
3563 break;
3564 case glslang::EOpAtomicCounter:
3565 opCode = spv::OpAtomicLoad;
3566 break;
3567 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003568 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003569 break;
3570 }
3571
3572 // Sort out the operands
3573 // - mapping from glslang -> SPV
3574 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003575 // - compare-exchange swaps the value and comparator
3576 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003577 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3578 auto opIt = operands.begin(); // walk the glslang operands
3579 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003580 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3581 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3582 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003583 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3584 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003585 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003586 spvAtomicOperands.push_back(*(opIt + 1));
3587 spvAtomicOperands.push_back(*opIt);
3588 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003589 }
John Kessenich426394d2015-07-23 10:22:48 -06003590
John Kessenich3e60a6f2015-09-14 22:45:16 -06003591 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003592 for (; opIt != operands.end(); ++opIt)
3593 spvAtomicOperands.push_back(*opIt);
3594
3595 return builder.createOp(opCode, typeId, spvAtomicOperands);
3596}
3597
John Kessenich91cef522016-05-05 16:45:40 -06003598// Create group invocation operations.
3599spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3600{
3601 builder.addCapability(spv::CapabilityGroups);
3602
3603 std::vector<spv::Id> operands;
3604 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3605 operands.push_back(operand);
3606
3607 switch (op) {
3608 case glslang::EOpAnyInvocation:
3609 case glslang::EOpAllInvocations:
3610 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3611
3612 case glslang::EOpAllInvocationsEqual:
3613 {
3614 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3615 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3616
3617 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3618 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3619 }
3620 default:
3621 logger->missingFunctionality("invocation operation");
3622 return spv::NoResult;
3623 }
3624}
3625
John Kessenich5e4b1242015-08-06 22:53:06 -06003626spv::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 -06003627{
Rex Xu8ff43de2016-04-22 16:51:45 +08003628 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3630
John Kessenich140f3df2015-06-26 16:58:36 -06003631 spv::Op opCode = spv::OpNop;
3632 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003633 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003634 spv::Id typeId0 = 0;
3635 if (consumedOperands > 0)
3636 typeId0 = builder.getTypeId(operands[0]);
3637 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003638
3639 switch (op) {
3640 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003641 if (isFloat)
3642 libCall = spv::GLSLstd450FMin;
3643 else if (isUnsigned)
3644 libCall = spv::GLSLstd450UMin;
3645 else
3646 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003647 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003648 break;
3649 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003650 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003651 break;
3652 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003653 if (isFloat)
3654 libCall = spv::GLSLstd450FMax;
3655 else if (isUnsigned)
3656 libCall = spv::GLSLstd450UMax;
3657 else
3658 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003659 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003660 break;
3661 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003662 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003663 break;
3664 case glslang::EOpDot:
3665 opCode = spv::OpDot;
3666 break;
3667 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003668 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003669 break;
3670
3671 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003672 if (isFloat)
3673 libCall = spv::GLSLstd450FClamp;
3674 else if (isUnsigned)
3675 libCall = spv::GLSLstd450UClamp;
3676 else
3677 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003678 builder.promoteScalar(precision, operands.front(), operands[1]);
3679 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003680 break;
3681 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003682 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3683 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003684 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003685 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003686 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003687 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003688 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003689 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003690 break;
3691 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003692 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003693 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003697 builder.promoteScalar(precision, operands[0], operands[2]);
3698 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700
3701 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003708 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003711 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003712 break;
3713 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003714 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003715 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003716 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003717 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003718 libCall = spv::GLSLstd450InterpolateAtSample;
3719 break;
3720 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003721 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003722 libCall = spv::GLSLstd450InterpolateAtOffset;
3723 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003724 case glslang::EOpAddCarry:
3725 opCode = spv::OpIAddCarry;
3726 typeId = builder.makeStructResultType(typeId0, typeId0);
3727 consumedOperands = 2;
3728 break;
3729 case glslang::EOpSubBorrow:
3730 opCode = spv::OpISubBorrow;
3731 typeId = builder.makeStructResultType(typeId0, typeId0);
3732 consumedOperands = 2;
3733 break;
3734 case glslang::EOpUMulExtended:
3735 opCode = spv::OpUMulExtended;
3736 typeId = builder.makeStructResultType(typeId0, typeId0);
3737 consumedOperands = 2;
3738 break;
3739 case glslang::EOpIMulExtended:
3740 opCode = spv::OpSMulExtended;
3741 typeId = builder.makeStructResultType(typeId0, typeId0);
3742 consumedOperands = 2;
3743 break;
3744 case glslang::EOpBitfieldExtract:
3745 if (isUnsigned)
3746 opCode = spv::OpBitFieldUExtract;
3747 else
3748 opCode = spv::OpBitFieldSExtract;
3749 break;
3750 case glslang::EOpBitfieldInsert:
3751 opCode = spv::OpBitFieldInsert;
3752 break;
3753
3754 case glslang::EOpFma:
3755 libCall = spv::GLSLstd450Fma;
3756 break;
3757 case glslang::EOpFrexp:
3758 libCall = spv::GLSLstd450FrexpStruct;
3759 if (builder.getNumComponents(operands[0]) == 1)
3760 frexpIntType = builder.makeIntegerType(32, true);
3761 else
3762 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3763 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3764 consumedOperands = 1;
3765 break;
3766 case glslang::EOpLdexp:
3767 libCall = spv::GLSLstd450Ldexp;
3768 break;
3769
Rex Xu574ab042016-04-14 16:53:07 +08003770 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003771 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003772 libCall = spv::GLSLstd450Bad;
3773 break;
3774
John Kessenich140f3df2015-06-26 16:58:36 -06003775 default:
3776 return 0;
3777 }
3778
3779 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003780 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003781 // Use an extended instruction from the standard library.
3782 // Construct the call arguments, without modifying the original operands vector.
3783 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3784 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003785 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003786 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003787 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003788 case 0:
3789 // should all be handled by visitAggregate and createNoArgOperation
3790 assert(0);
3791 return 0;
3792 case 1:
3793 // should all be handled by createUnaryOperation
3794 assert(0);
3795 return 0;
3796 case 2:
3797 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3798 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003799 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003800 // anything 3 or over doesn't have l-value operands, so all should be consumed
3801 assert(consumedOperands == operands.size());
3802 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003803 break;
3804 }
3805 }
3806
John Kessenich55e7d112015-11-15 21:33:39 -07003807 // Decode the return types that were structures
3808 switch (op) {
3809 case glslang::EOpAddCarry:
3810 case glslang::EOpSubBorrow:
3811 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3812 id = builder.createCompositeExtract(id, typeId0, 0);
3813 break;
3814 case glslang::EOpUMulExtended:
3815 case glslang::EOpIMulExtended:
3816 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3817 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3818 break;
3819 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003820 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003821 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3822 id = builder.createCompositeExtract(id, typeId0, 0);
3823 break;
3824 default:
3825 break;
3826 }
3827
John Kessenich32cfd492016-02-02 12:37:46 -07003828 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003829}
3830
3831// Intrinsics with no arguments, no return value, and no precision.
3832spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3833{
3834 // TODO: get the barrier operands correct
3835
3836 switch (op) {
3837 case glslang::EOpEmitVertex:
3838 builder.createNoResultOp(spv::OpEmitVertex);
3839 return 0;
3840 case glslang::EOpEndPrimitive:
3841 builder.createNoResultOp(spv::OpEndPrimitive);
3842 return 0;
3843 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003844 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3845 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003846 return 0;
3847 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003848 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003849 return 0;
3850 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003851 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003852 return 0;
3853 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003854 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 return 0;
3856 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003858 return 0;
3859 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003860 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003861 return 0;
3862 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003863 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003864 return 0;
3865 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003866 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003867 return 0;
3868 }
3869}
3870
3871spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3872{
John Kessenich2f273362015-07-18 22:34:27 -06003873 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003874 spv::Id id;
3875 if (symbolValues.end() != iter) {
3876 id = iter->second;
3877 return id;
3878 }
3879
3880 // it was not found, create it
3881 id = createSpvVariable(symbol);
3882 symbolValues[symbol->getId()] = id;
3883
3884 if (! symbol->getType().isStruct()) {
3885 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003886 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003887 if (symbol->getType().getQualifier().hasSpecConstantId())
3888 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003889 if (symbol->getQualifier().hasLocation())
3890 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3891 if (symbol->getQualifier().hasIndex())
3892 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3893 if (symbol->getQualifier().hasComponent())
3894 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3895 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003896 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003897 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003898 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003899 if (symbol->getQualifier().hasXfbBuffer())
3900 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3901 if (symbol->getQualifier().hasXfbOffset())
3902 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3903 }
3904 }
3905
John Kesseniche0b6cad2015-12-24 10:30:13 -07003906 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003907 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003908 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003909 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003910 }
John Kessenich140f3df2015-06-26 16:58:36 -06003911 if (symbol->getQualifier().hasSet())
3912 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003913 else if (IsDescriptorResource(symbol->getType())) {
3914 // default to 0
3915 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3916 }
John Kessenich140f3df2015-06-26 16:58:36 -06003917 if (symbol->getQualifier().hasBinding())
3918 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003919 if (symbol->getQualifier().hasAttachment())
3920 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003921 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003922 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003923 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003924 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003925 if (symbol->getQualifier().hasXfbBuffer())
3926 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3927 }
3928
Rex Xu1da878f2016-02-21 20:59:01 +08003929 if (symbol->getType().isImage()) {
3930 std::vector<spv::Decoration> memory;
3931 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3932 for (unsigned int i = 0; i < memory.size(); ++i)
3933 addDecoration(id, memory[i]);
3934 }
3935
John Kessenich140f3df2015-06-26 16:58:36 -06003936 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003937 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003938 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003939 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003940
John Kessenich140f3df2015-06-26 16:58:36 -06003941 return id;
3942}
3943
John Kessenich55e7d112015-11-15 21:33:39 -07003944// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003945void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3946{
3947 if (dec != spv::BadValue)
3948 builder.addDecoration(id, dec);
3949}
3950
John Kessenich55e7d112015-11-15 21:33:39 -07003951// If 'dec' is valid, add a one-operand decoration to an object
3952void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3953{
3954 if (dec != spv::BadValue)
3955 builder.addDecoration(id, dec, value);
3956}
3957
3958// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003959void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3960{
3961 if (dec != spv::BadValue)
3962 builder.addMemberDecoration(id, (unsigned)member, dec);
3963}
3964
John Kessenich92187592016-02-01 13:45:25 -07003965// If 'dec' is valid, add a one-operand decoration to a struct member
3966void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3967{
3968 if (dec != spv::BadValue)
3969 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3970}
3971
John Kessenich55e7d112015-11-15 21:33:39 -07003972// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003973// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003974//
3975// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3976//
3977// Recursively walk the nodes. The nodes form a tree whose leaves are
3978// regular constants, which themselves are trees that createSpvConstant()
3979// recursively walks. So, this function walks the "top" of the tree:
3980// - emit specialization constant-building instructions for specConstant
3981// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003982spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003983{
John Kessenich7cc0e282016-03-20 00:46:02 -06003984 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003985
qining4f4bb812016-04-03 23:55:17 -04003986 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003987 if (! node.getQualifier().specConstant) {
3988 // hand off to the non-spec-constant path
3989 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3990 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003991 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003992 nextConst, false);
3993 }
3994
3995 // We now know we have a specialization constant to build
3996
qining4f4bb812016-04-03 23:55:17 -04003997 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3998 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3999 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4000 std::vector<spv::Id> dimConstId;
4001 for (int dim = 0; dim < 3; ++dim) {
4002 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4003 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4004 if (specConst)
4005 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4006 }
4007 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4008 }
4009
4010 // An AST node labelled as specialization constant should be a symbol node.
4011 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4012 if (auto* sn = node.getAsSymbolNode()) {
4013 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004014 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4015 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4016 // will set the builder into spec constant op instruction generating mode.
4017 sub_tree->traverse(this);
4018 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004019 } else if (auto* const_union_array = &sn->getConstArray()){
4020 int nextConst = 0;
4021 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004022 }
4023 }
qining4f4bb812016-04-03 23:55:17 -04004024
4025 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4026 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004027 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004028 exit(1);
4029 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004030}
4031
John Kessenich140f3df2015-06-26 16:58:36 -06004032// Use 'consts' as the flattened glslang source of scalar constants to recursively
4033// build the aggregate SPIR-V constant.
4034//
4035// If there are not enough elements present in 'consts', 0 will be substituted;
4036// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4037//
qining08408382016-03-21 09:51:37 -04004038spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004039{
4040 // vector of constants for SPIR-V
4041 std::vector<spv::Id> spvConsts;
4042
4043 // Type is used for struct and array constants
4044 spv::Id typeId = convertGlslangToSpvType(glslangType);
4045
4046 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004047 glslang::TType elementType(glslangType, 0);
4048 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004049 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004050 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004051 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004052 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004053 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004054 } else if (glslangType.getStruct()) {
4055 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4056 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004057 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004058 } else if (glslangType.isVector()) {
4059 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4060 bool zero = nextConst >= consts.size();
4061 switch (glslangType.getBasicType()) {
4062 case glslang::EbtInt:
4063 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4064 break;
4065 case glslang::EbtUint:
4066 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4067 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004068 case glslang::EbtInt64:
4069 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4070 break;
4071 case glslang::EbtUint64:
4072 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4073 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004074 case glslang::EbtFloat:
4075 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4076 break;
4077 case glslang::EbtDouble:
4078 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4079 break;
4080 case glslang::EbtBool:
4081 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4082 break;
4083 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004084 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 }
4087 ++nextConst;
4088 }
4089 } else {
4090 // we have a non-aggregate (scalar) constant
4091 bool zero = nextConst >= consts.size();
4092 spv::Id scalar = 0;
4093 switch (glslangType.getBasicType()) {
4094 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004095 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004096 break;
4097 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004098 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004099 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004100 case glslang::EbtInt64:
4101 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4102 break;
4103 case glslang::EbtUint64:
4104 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4105 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004106 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004107 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004110 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004113 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004116 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118 }
4119 ++nextConst;
4120 return scalar;
4121 }
4122
4123 return builder.makeCompositeConstant(typeId, spvConsts);
4124}
4125
John Kessenich7c1aa102015-10-15 13:29:11 -06004126// Return true if the node is a constant or symbol whose reading has no
4127// non-trivial observable cost or effect.
4128bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4129{
4130 // don't know what this is
4131 if (node == nullptr)
4132 return false;
4133
4134 // a constant is safe
4135 if (node->getAsConstantUnion() != nullptr)
4136 return true;
4137
4138 // not a symbol means non-trivial
4139 if (node->getAsSymbolNode() == nullptr)
4140 return false;
4141
4142 // a symbol, depends on what's being read
4143 switch (node->getType().getQualifier().storage) {
4144 case glslang::EvqTemporary:
4145 case glslang::EvqGlobal:
4146 case glslang::EvqIn:
4147 case glslang::EvqInOut:
4148 case glslang::EvqConst:
4149 case glslang::EvqConstReadOnly:
4150 case glslang::EvqUniform:
4151 return true;
4152 default:
4153 return false;
4154 }
qining25262b32016-05-06 17:25:16 -04004155}
John Kessenich7c1aa102015-10-15 13:29:11 -06004156
4157// A node is trivial if it is a single operation with no side effects.
4158// Error on the side of saying non-trivial.
4159// Return true if trivial.
4160bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4161{
4162 if (node == nullptr)
4163 return false;
4164
4165 // symbols and constants are trivial
4166 if (isTrivialLeaf(node))
4167 return true;
4168
4169 // otherwise, it needs to be a simple operation or one or two leaf nodes
4170
4171 // not a simple operation
4172 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4173 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4174 if (binaryNode == nullptr && unaryNode == nullptr)
4175 return false;
4176
4177 // not on leaf nodes
4178 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4179 return false;
4180
4181 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4182 return false;
4183 }
4184
4185 switch (node->getAsOperator()->getOp()) {
4186 case glslang::EOpLogicalNot:
4187 case glslang::EOpConvIntToBool:
4188 case glslang::EOpConvUintToBool:
4189 case glslang::EOpConvFloatToBool:
4190 case glslang::EOpConvDoubleToBool:
4191 case glslang::EOpEqual:
4192 case glslang::EOpNotEqual:
4193 case glslang::EOpLessThan:
4194 case glslang::EOpGreaterThan:
4195 case glslang::EOpLessThanEqual:
4196 case glslang::EOpGreaterThanEqual:
4197 case glslang::EOpIndexDirect:
4198 case glslang::EOpIndexDirectStruct:
4199 case glslang::EOpLogicalXor:
4200 case glslang::EOpAny:
4201 case glslang::EOpAll:
4202 return true;
4203 default:
4204 return false;
4205 }
4206}
4207
4208// Emit short-circuiting code, where 'right' is never evaluated unless
4209// the left side is true (for &&) or false (for ||).
4210spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4211{
4212 spv::Id boolTypeId = builder.makeBoolType();
4213
4214 // emit left operand
4215 builder.clearAccessChain();
4216 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004217 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004218
4219 // Operands to accumulate OpPhi operands
4220 std::vector<spv::Id> phiOperands;
4221 // accumulate left operand's phi information
4222 phiOperands.push_back(leftId);
4223 phiOperands.push_back(builder.getBuildPoint()->getId());
4224
4225 // Make the two kinds of operation symmetric with a "!"
4226 // || => emit "if (! left) result = right"
4227 // && => emit "if ( left) result = right"
4228 //
4229 // TODO: this runtime "not" for || could be avoided by adding functionality
4230 // to 'builder' to have an "else" without an "then"
4231 if (op == glslang::EOpLogicalOr)
4232 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4233
4234 // make an "if" based on the left value
4235 spv::Builder::If ifBuilder(leftId, builder);
4236
4237 // emit right operand as the "then" part of the "if"
4238 builder.clearAccessChain();
4239 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004240 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004241
4242 // accumulate left operand's phi information
4243 phiOperands.push_back(rightId);
4244 phiOperands.push_back(builder.getBuildPoint()->getId());
4245
4246 // finish the "if"
4247 ifBuilder.makeEndIf();
4248
4249 // phi together the two results
4250 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4251}
4252
John Kessenich140f3df2015-06-26 16:58:36 -06004253}; // end anonymous namespace
4254
4255namespace glslang {
4256
John Kessenich68d78fd2015-07-12 19:28:10 -06004257void GetSpirvVersion(std::string& version)
4258{
John Kessenich9e55f632015-07-15 10:03:39 -06004259 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004260 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004261 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004262 version = buf;
4263}
4264
John Kessenich140f3df2015-06-26 16:58:36 -06004265// Write SPIR-V out to a binary file
4266void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4267{
4268 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004269 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004270 for (int i = 0; i < (int)spirv.size(); ++i) {
4271 unsigned int word = spirv[i];
4272 out.write((const char*)&word, 4);
4273 }
4274 out.close();
4275}
4276
4277//
4278// Set up the glslang traversal
4279//
4280void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4281{
Lei Zhang17535f72016-05-04 15:55:59 -04004282 spv::SpvBuildLogger logger;
4283 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004284}
4285
Lei Zhang17535f72016-05-04 15:55:59 -04004286void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004287{
John Kessenich140f3df2015-06-26 16:58:36 -06004288 TIntermNode* root = intermediate.getTreeRoot();
4289
4290 if (root == 0)
4291 return;
4292
4293 glslang::GetThreadPoolAllocator().push();
4294
Lei Zhang17535f72016-05-04 15:55:59 -04004295 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004296
4297 root->traverse(&it);
4298
4299 it.dumpSpv(spirv);
4300
4301 glslang::GetThreadPoolAllocator().pop();
4302}
4303
4304}; // end namespace glslang