blob: 66194663ece5ad71a46fbc21c30a0d98975053a9 [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 Kessenichebb50532016-05-16 19:22:05 -0600112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool member);
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 Kessenichebb50532016-05-16 19:22:05 -0600125 void declareClipCullCapability(const glslang::TTypeList& members, int member);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
128 void makeFunctions(const glslang::TIntermSequence&);
129 void makeGlobalInitializers(const glslang::TIntermSequence&);
130 void visitFunctions(const glslang::TIntermSequence&);
131 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800132 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600133 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
134 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600135 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
136
qining25262b32016-05-06 17:25:16 -0400137 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
138 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
139 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
140 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800141 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800143 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich91cef522016-05-05 16:45:40 -0600144 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600154 bool isTrivialLeaf(const glslang::TIntermTyped* node);
155 bool isTrivial(const glslang::TIntermTyped* node);
156 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
158 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700159 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600160 int sequenceDepth;
161
Lei Zhang17535f72016-05-04 15:55:59 -0400162 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400163
John Kessenich140f3df2015-06-26 16:58:36 -0600164 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
165 spv::Builder builder;
166 bool inMain;
167 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700168 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700169 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600170 const glslang::TIntermediate* glslangIntermediate;
171 spv::Id stdBuiltins;
172
John Kessenich2f273362015-07-18 22:34:27 -0600173 std::unordered_map<int, spv::Id> symbolValues;
174 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
175 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700176 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600177 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600178 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600179};
180
181//
182// Helper functions for translating glslang representations to SPIR-V enumerants.
183//
184
185// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700186spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600187{
John Kessenich66e2faf2016-03-12 18:34:36 -0700188 switch (source) {
189 case glslang::EShSourceGlsl:
190 switch (profile) {
191 case ENoProfile:
192 case ECoreProfile:
193 case ECompatibilityProfile:
194 return spv::SourceLanguageGLSL;
195 case EEsProfile:
196 return spv::SourceLanguageESSL;
197 default:
198 return spv::SourceLanguageUnknown;
199 }
200 case glslang::EShSourceHlsl:
201 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 default:
203 return spv::SourceLanguageUnknown;
204 }
205}
206
207// Translate glslang language (stage) to SPIR-V execution model.
208spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
209{
210 switch (stage) {
211 case EShLangVertex: return spv::ExecutionModelVertex;
212 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
213 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
214 case EShLangGeometry: return spv::ExecutionModelGeometry;
215 case EShLangFragment: return spv::ExecutionModelFragment;
216 case EShLangCompute: return spv::ExecutionModelGLCompute;
217 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600219 return spv::ExecutionModelFragment;
220 }
221}
222
223// Translate glslang type to SPIR-V storage class.
224spv::StorageClass TranslateStorageClass(const glslang::TType& type)
225{
226 if (type.getQualifier().isPipeInput())
227 return spv::StorageClassInput;
228 else if (type.getQualifier().isPipeOutput())
229 return spv::StorageClassOutput;
230 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700231 if (type.getQualifier().layoutPushConstant)
232 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 if (type.getBasicType() == glslang::EbtBlock)
234 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800235 else if (type.getBasicType() == glslang::EbtAtomicUint)
236 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 else
238 return spv::StorageClassUniformConstant;
239 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
240 } else {
241 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700242 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
243 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600244 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
245 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400246 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700247 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600248 return spv::StorageClassFunction;
249 }
250 }
251}
252
253// Translate glslang sampler type to SPIR-V dimensionality.
254spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
255{
256 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700257 case glslang::Esd1D: return spv::Dim1D;
258 case glslang::Esd2D: return spv::Dim2D;
259 case glslang::Esd3D: return spv::Dim3D;
260 case glslang::EsdCube: return spv::DimCube;
261 case glslang::EsdRect: return spv::DimRect;
262 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700263 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700265 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600266 return spv::Dim2D;
267 }
268}
269
270// Translate glslang type to SPIR-V precision decorations.
271spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
272{
273 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700274 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600275 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600276 default:
277 return spv::NoPrecision;
278 }
279}
280
281// Translate glslang type to SPIR-V block decorations.
282spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
283{
284 if (type.getBasicType() == glslang::EbtBlock) {
285 switch (type.getQualifier().storage) {
286 case glslang::EvqUniform: return spv::DecorationBlock;
287 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
288 case glslang::EvqVaryingIn: return spv::DecorationBlock;
289 case glslang::EvqVaryingOut: return spv::DecorationBlock;
290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 break;
293 }
294 }
295
296 return (spv::Decoration)spv::BadValue;
297}
298
Rex Xu1da878f2016-02-21 20:59:01 +0800299// Translate glslang type to SPIR-V memory decorations.
300void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
301{
302 if (qualifier.coherent)
303 memory.push_back(spv::DecorationCoherent);
304 if (qualifier.volatil)
305 memory.push_back(spv::DecorationVolatile);
306 if (qualifier.restrict)
307 memory.push_back(spv::DecorationRestrict);
308 if (qualifier.readonly)
309 memory.push_back(spv::DecorationNonWritable);
310 if (qualifier.writeonly)
311 memory.push_back(spv::DecorationNonReadable);
312}
313
John Kessenich140f3df2015-06-26 16:58:36 -0600314// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700315spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600316{
317 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700318 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600319 case glslang::ElmRowMajor:
320 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 default:
324 // opaque layouts don't need a majorness
325 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 }
327 } else {
328 switch (type.getBasicType()) {
329 default:
330 return (spv::Decoration)spv::BadValue;
331 break;
332 case glslang::EbtBlock:
333 switch (type.getQualifier().storage) {
334 case glslang::EvqUniform:
335 case glslang::EvqBuffer:
336 switch (type.getQualifier().layoutPacking) {
337 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
339 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600340 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 }
342 case glslang::EvqVaryingIn:
343 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700344 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return (spv::Decoration)spv::BadValue;
349 }
350 }
351 }
352}
353
354// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700355// Returns spv::Decoration(spv::BadValue) when no decoration
356// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700357spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600358{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700359 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700360 // Smooth decoration doesn't exist in SPIR-V 1.0
361 return (spv::Decoration)spv::BadValue;
362 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700363 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700365 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600366 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700369 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600370 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700371 else if (qualifier.sample) {
372 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600373 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700374 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600375 return (spv::Decoration)spv::BadValue;
376}
377
John Kessenich92187592016-02-01 13:45:25 -0700378// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600380{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700381 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600382 return spv::DecorationInvariant;
383 else
384 return (spv::Decoration)spv::BadValue;
385}
386
qining9220dbb2016-05-04 17:34:38 -0400387// If glslang type is noContraction, return SPIR-V NoContraction decoration.
388spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
389{
390 if (qualifier.noContraction)
391 return spv::DecorationNoContraction;
392 else
393 return (spv::Decoration)spv::BadValue;
394}
395
John Kessenich140f3df2015-06-26 16:58:36 -0600396// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenichebb50532016-05-16 19:22:05 -0600397spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool member)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
399 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700400 case glslang::EbvPointSize:
401 switch (glslangIntermediate->getStage()) {
402 case EShLangGeometry:
403 builder.addCapability(spv::CapabilityGeometryPointSize);
404 break;
405 case EShLangTessControl:
406 case EShLangTessEvaluation:
407 builder.addCapability(spv::CapabilityTessellationPointSize);
408 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100409 default:
410 break;
John Kessenich92187592016-02-01 13:45:25 -0700411 }
412 return spv::BuiltInPointSize;
413
John Kessenichebb50532016-05-16 19:22:05 -0600414 // These *Distance capabilities logically belong here, but if the member is declared and
415 // then never used, consumers of SPIR-V prefer the capability not be declared.
416 // They are now generated when used, rather than here when declared.
417 // Potentially, the specification should be more clear what the minimum
418 // use needed is to trigger the capability.
419 //
John Kessenich92187592016-02-01 13:45:25 -0700420 case glslang::EbvClipDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600421 if (! member)
422 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700423 return spv::BuiltInClipDistance;
424
425 case glslang::EbvCullDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600426 if (! member)
427 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700428 return spv::BuiltInCullDistance;
429
430 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500431 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700432 return spv::BuiltInViewportIndex;
433
John Kessenich5e801132016-02-15 11:09:46 -0700434 case glslang::EbvSampleId:
435 builder.addCapability(spv::CapabilitySampleRateShading);
436 return spv::BuiltInSampleId;
437
438 case glslang::EbvSamplePosition:
439 builder.addCapability(spv::CapabilitySampleRateShading);
440 return spv::BuiltInSamplePosition;
441
442 case glslang::EbvSampleMask:
443 builder.addCapability(spv::CapabilitySampleRateShading);
444 return spv::BuiltInSampleMask;
445
John Kessenich140f3df2015-06-26 16:58:36 -0600446 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600447 case glslang::EbvVertexId: return spv::BuiltInVertexId;
448 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700449 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
450 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600451 case glslang::EbvBaseVertex:
452 case glslang::EbvBaseInstance:
453 case glslang::EbvDrawId:
454 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600455 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600456 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600457 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
458 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
459 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600460 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
461 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
462 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
463 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
464 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
465 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
466 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600467 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
468 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
469 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
470 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
471 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
472 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
473 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
474 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800475 case glslang::EbvSubGroupSize:
476 case glslang::EbvSubGroupInvocation:
477 case glslang::EbvSubGroupEqMask:
478 case glslang::EbvSubGroupGeMask:
479 case glslang::EbvSubGroupGtMask:
480 case glslang::EbvSubGroupLeMask:
481 case glslang::EbvSubGroupLtMask:
482 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600483 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800484 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600485 default: return (spv::BuiltIn)spv::BadValue;
486 }
487}
488
Rex Xufc618912015-09-09 16:42:49 +0800489// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700490spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800491{
492 assert(type.getBasicType() == glslang::EbtSampler);
493
John Kessenich5d0fa972016-02-15 11:57:00 -0700494 // Check for capabilities
495 switch (type.getQualifier().layoutFormat) {
496 case glslang::ElfRg32f:
497 case glslang::ElfRg16f:
498 case glslang::ElfR11fG11fB10f:
499 case glslang::ElfR16f:
500 case glslang::ElfRgba16:
501 case glslang::ElfRgb10A2:
502 case glslang::ElfRg16:
503 case glslang::ElfRg8:
504 case glslang::ElfR16:
505 case glslang::ElfR8:
506 case glslang::ElfRgba16Snorm:
507 case glslang::ElfRg16Snorm:
508 case glslang::ElfRg8Snorm:
509 case glslang::ElfR16Snorm:
510 case glslang::ElfR8Snorm:
511
512 case glslang::ElfRg32i:
513 case glslang::ElfRg16i:
514 case glslang::ElfRg8i:
515 case glslang::ElfR16i:
516 case glslang::ElfR8i:
517
518 case glslang::ElfRgb10a2ui:
519 case glslang::ElfRg32ui:
520 case glslang::ElfRg16ui:
521 case glslang::ElfRg8ui:
522 case glslang::ElfR16ui:
523 case glslang::ElfR8ui:
524 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
525 break;
526
527 default:
528 break;
529 }
530
531 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800532 switch (type.getQualifier().layoutFormat) {
533 case glslang::ElfNone: return spv::ImageFormatUnknown;
534 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
535 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
536 case glslang::ElfR32f: return spv::ImageFormatR32f;
537 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
538 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
539 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
540 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
541 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
542 case glslang::ElfR16f: return spv::ImageFormatR16f;
543 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
544 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
545 case glslang::ElfRg16: return spv::ImageFormatRg16;
546 case glslang::ElfRg8: return spv::ImageFormatRg8;
547 case glslang::ElfR16: return spv::ImageFormatR16;
548 case glslang::ElfR8: return spv::ImageFormatR8;
549 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
550 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
551 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
552 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
553 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
554 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
555 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
556 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
557 case glslang::ElfR32i: return spv::ImageFormatR32i;
558 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
559 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
560 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
561 case glslang::ElfR16i: return spv::ImageFormatR16i;
562 case glslang::ElfR8i: return spv::ImageFormatR8i;
563 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
564 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
565 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
566 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
567 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
568 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
569 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
570 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
571 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
572 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
573 default: return (spv::ImageFormat)spv::BadValue;
574 }
575}
576
qining25262b32016-05-06 17:25:16 -0400577// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700578// descriptor set.
579bool IsDescriptorResource(const glslang::TType& type)
580{
John Kessenichf7497e22016-03-08 21:36:22 -0700581 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700582 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700583 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700584
585 // non block...
586 // basically samplerXXX/subpass/sampler/texture are all included
587 // if they are the global-scope-class, not the function parameter
588 // (or local, if they ever exist) class.
589 if (type.getBasicType() == glslang::EbtSampler)
590 return type.getQualifier().isUniformOrBuffer();
591
592 // None of the above.
593 return false;
594}
595
John Kesseniche0b6cad2015-12-24 10:30:13 -0700596void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
597{
598 if (child.layoutMatrix == glslang::ElmNone)
599 child.layoutMatrix = parent.layoutMatrix;
600
601 if (parent.invariant)
602 child.invariant = true;
603 if (parent.nopersp)
604 child.nopersp = true;
605 if (parent.flat)
606 child.flat = true;
607 if (parent.centroid)
608 child.centroid = true;
609 if (parent.patch)
610 child.patch = true;
611 if (parent.sample)
612 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800613 if (parent.coherent)
614 child.coherent = true;
615 if (parent.volatil)
616 child.volatil = true;
617 if (parent.restrict)
618 child.restrict = true;
619 if (parent.readonly)
620 child.readonly = true;
621 if (parent.writeonly)
622 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700623}
624
625bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
626{
John Kessenich7b9fa252016-01-21 18:56:57 -0700627 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700628 // - struct members can inherit from a struct declaration
629 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
630 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400631 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700632}
633
John Kessenich140f3df2015-06-26 16:58:36 -0600634//
635// Implement the TGlslangToSpvTraverser class.
636//
637
Lei Zhang17535f72016-05-04 15:55:59 -0400638TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
639 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
640 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600641 inMain(false), mainTerminated(false), linkageOnly(false),
642 glslangIntermediate(glslangIntermediate)
643{
644 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
645
646 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700647 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600648 stdBuiltins = builder.import("GLSL.std.450");
649 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700650 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
651 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600652
653 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600654 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
655 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600656 builder.addSourceExtension(it->c_str());
657
658 // Add the top-level modes for this shader.
659
John Kessenich92187592016-02-01 13:45:25 -0700660 if (glslangIntermediate->getXfbMode()) {
661 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600662 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700663 }
John Kessenich140f3df2015-06-26 16:58:36 -0600664
665 unsigned int mode;
666 switch (glslangIntermediate->getStage()) {
667 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600668 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600669 break;
670
671 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600672 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600673 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
674 break;
675
676 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600677 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600678 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700679 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
680 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
681 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600682 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600683 }
684 if (mode != spv::BadValue)
685 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
686
John Kesseniche6903322015-10-13 16:29:02 -0600687 switch (glslangIntermediate->getVertexSpacing()) {
688 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
689 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
690 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
691 default: mode = spv::BadValue; break;
692 }
693 if (mode != spv::BadValue)
694 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
695
696 switch (glslangIntermediate->getVertexOrder()) {
697 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
698 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
699 default: mode = spv::BadValue; break;
700 }
701 if (mode != spv::BadValue)
702 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
703
704 if (glslangIntermediate->getPointMode())
705 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600706 break;
707
708 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600709 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600710 switch (glslangIntermediate->getInputPrimitive()) {
711 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
712 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
713 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700714 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600715 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
716 default: mode = spv::BadValue; break;
717 }
718 if (mode != spv::BadValue)
719 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600720
John Kessenich140f3df2015-06-26 16:58:36 -0600721 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
722
723 switch (glslangIntermediate->getOutputPrimitive()) {
724 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
725 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
726 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
727 default: mode = spv::BadValue; break;
728 }
729 if (mode != spv::BadValue)
730 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
731 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
732 break;
733
734 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600735 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600736 if (glslangIntermediate->getPixelCenterInteger())
737 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600738
John Kessenich140f3df2015-06-26 16:58:36 -0600739 if (glslangIntermediate->getOriginUpperLeft())
740 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600741 else
742 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600743
744 if (glslangIntermediate->getEarlyFragmentTests())
745 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
746
747 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600748 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
749 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
750 default: mode = spv::BadValue; break;
751 }
752 if (mode != spv::BadValue)
753 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
754
755 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
756 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600757 break;
758
759 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600760 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600761 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
762 glslangIntermediate->getLocalSize(1),
763 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600764 break;
765
766 default:
767 break;
768 }
769
770}
771
John Kessenich7ba63412015-12-20 17:37:07 -0700772// Finish everything and dump
773void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
774{
775 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100776 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
777 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700778
qiningda397332016-03-09 19:54:03 -0500779 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700780 builder.dump(out);
781}
782
John Kessenich140f3df2015-06-26 16:58:36 -0600783TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
784{
785 if (! mainTerminated) {
786 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
787 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600788 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600789 }
790}
791
792//
793// Implement the traversal functions.
794//
795// Return true from interior nodes to have the external traversal
796// continue on to children. Return false if children were
797// already processed.
798//
799
800//
qining25262b32016-05-06 17:25:16 -0400801// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600802// - uniform/input reads
803// - output writes
804// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
805// - something simple that degenerates into the last bullet
806//
807void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
808{
qining75d1d802016-04-06 14:42:01 -0400809 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
810 if (symbol->getType().getQualifier().isSpecConstant())
811 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
812
John Kessenich140f3df2015-06-26 16:58:36 -0600813 // getSymbolId() will set up all the IO decorations on the first call.
814 // Formal function parameters were mapped during makeFunctions().
815 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700816
817 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
818 if (builder.isPointer(id)) {
819 spv::StorageClass sc = builder.getStorageClass(id);
820 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
821 iOSet.insert(id);
822 }
823
824 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700825 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600826 // Prepare to generate code for the access
827
828 // L-value chains will be computed left to right. We're on the symbol now,
829 // which is the left-most part of the access chain, so now is "clear" time,
830 // followed by setting the base.
831 builder.clearAccessChain();
832
833 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700834 // except for
835 // A) "const in" arguments to a function, which are an intermediate object.
836 // See comments in handleUserFunctionCall().
837 // B) Specialization constants (normal constant don't even come in as a variable),
838 // These are also pure R-values.
839 glslang::TQualifier qualifier = symbol->getQualifier();
840 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
841 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600842 builder.setAccessChainRValue(id);
843 else
844 builder.setAccessChainLValue(id);
845 }
846}
847
848bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
849{
qining40887662016-04-03 22:20:42 -0400850 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
851 if (node->getType().getQualifier().isSpecConstant())
852 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
853
John Kessenich140f3df2015-06-26 16:58:36 -0600854 // First, handle special cases
855 switch (node->getOp()) {
856 case glslang::EOpAssign:
857 case glslang::EOpAddAssign:
858 case glslang::EOpSubAssign:
859 case glslang::EOpMulAssign:
860 case glslang::EOpVectorTimesMatrixAssign:
861 case glslang::EOpVectorTimesScalarAssign:
862 case glslang::EOpMatrixTimesScalarAssign:
863 case glslang::EOpMatrixTimesMatrixAssign:
864 case glslang::EOpDivAssign:
865 case glslang::EOpModAssign:
866 case glslang::EOpAndAssign:
867 case glslang::EOpInclusiveOrAssign:
868 case glslang::EOpExclusiveOrAssign:
869 case glslang::EOpLeftShiftAssign:
870 case glslang::EOpRightShiftAssign:
871 // A bin-op assign "a += b" means the same thing as "a = a + b"
872 // where a is evaluated before b. For a simple assignment, GLSL
873 // says to evaluate the left before the right. So, always, left
874 // node then right node.
875 {
876 // get the left l-value, save it away
877 builder.clearAccessChain();
878 node->getLeft()->traverse(this);
879 spv::Builder::AccessChain lValue = builder.getAccessChain();
880
881 // evaluate the right
882 builder.clearAccessChain();
883 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700884 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600885
886 if (node->getOp() != glslang::EOpAssign) {
887 // the left is also an r-value
888 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700889 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600890
891 // do the operation
qining25262b32016-05-06 17:25:16 -0400892 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
893 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600894 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
895 node->getType().getBasicType());
896
897 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700898 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600899 }
900
901 // store the result
902 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800903 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600904
905 // assignments are expressions having an rValue after they are evaluated...
906 builder.clearAccessChain();
907 builder.setAccessChainRValue(rValue);
908 }
909 return false;
910 case glslang::EOpIndexDirect:
911 case glslang::EOpIndexDirectStruct:
912 {
913 // Get the left part of the access chain.
914 node->getLeft()->traverse(this);
915
916 // Add the next element in the chain
917
John Kessenich55e7d112015-11-15 21:33:39 -0700918 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600919 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
920 // This may be, e.g., an anonymous block-member selection, which generally need
921 // index remapping due to hidden members in anonymous blocks.
922 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700923 assert(remapper.size() > 0);
924 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600925 }
926
927 if (! node->getLeft()->getType().isArray() &&
928 node->getLeft()->getType().isVector() &&
929 node->getOp() == glslang::EOpIndexDirect) {
930 // This is essentially a hard-coded vector swizzle of size 1,
931 // so short circuit the access-chain stuff with a swizzle.
932 std::vector<unsigned> swizzle;
933 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600934 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600935 } else {
936 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600937 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenichebb50532016-05-16 19:22:05 -0600938
939 // Add capabilities here for accessing clip/cull distance
940 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
941 declareClipCullCapability(*node->getLeft()->getType().getStruct(), index);
John Kessenich140f3df2015-06-26 16:58:36 -0600942 }
943 }
944 return false;
945 case glslang::EOpIndexIndirect:
946 {
947 // Structure or array or vector indirection.
948 // Will use native SPIR-V access-chain for struct and array indirection;
949 // matrices are arrays of vectors, so will also work for a matrix.
950 // Will use the access chain's 'component' for variable index into a vector.
951
952 // This adapter is building access chains left to right.
953 // Set up the access chain to the left.
954 node->getLeft()->traverse(this);
955
956 // save it so that computing the right side doesn't trash it
957 spv::Builder::AccessChain partial = builder.getAccessChain();
958
959 // compute the next index in the chain
960 builder.clearAccessChain();
961 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700962 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600963
964 // restore the saved access chain
965 builder.setAccessChain(partial);
966
967 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600968 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600969 else
John Kessenichfa668da2015-09-13 14:46:30 -0600970 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600971 }
972 return false;
973 case glslang::EOpVectorSwizzle:
974 {
975 node->getLeft()->traverse(this);
976 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
977 std::vector<unsigned> swizzle;
978 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
979 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600980 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600981 }
982 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600983 case glslang::EOpLogicalOr:
984 case glslang::EOpLogicalAnd:
985 {
986
987 // These may require short circuiting, but can sometimes be done as straight
988 // binary operations. The right operand must be short circuited if it has
989 // side effects, and should probably be if it is complex.
990 if (isTrivial(node->getRight()->getAsTyped()))
991 break; // handle below as a normal binary operation
992 // otherwise, we need to do dynamic short circuiting on the right operand
993 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
994 builder.clearAccessChain();
995 builder.setAccessChainRValue(result);
996 }
997 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600998 default:
999 break;
1000 }
1001
1002 // Assume generic binary op...
1003
John Kessenich32cfd492016-02-02 12:37:46 -07001004 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001005 builder.clearAccessChain();
1006 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001007 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001008
John Kessenich32cfd492016-02-02 12:37:46 -07001009 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001010 builder.clearAccessChain();
1011 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001012 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001013
John Kessenich32cfd492016-02-02 12:37:46 -07001014 // get result
1015 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001016 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001017 convertGlslangToSpvType(node->getType()), left, right,
1018 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001019
John Kessenich50e57562015-12-21 21:21:11 -07001020 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001021 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001022 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001023 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001024 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001025 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001026 return false;
1027 }
John Kessenich140f3df2015-06-26 16:58:36 -06001028}
1029
1030bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1031{
qining40887662016-04-03 22:20:42 -04001032 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1033 if (node->getType().getQualifier().isSpecConstant())
1034 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1035
John Kessenichfc51d282015-08-19 13:34:18 -06001036 spv::Id result = spv::NoResult;
1037
1038 // try texturing first
1039 result = createImageTextureFunctionCall(node);
1040 if (result != spv::NoResult) {
1041 builder.clearAccessChain();
1042 builder.setAccessChainRValue(result);
1043
1044 return false; // done with this node
1045 }
1046
1047 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001048
1049 if (node->getOp() == glslang::EOpArrayLength) {
1050 // Quite special; won't want to evaluate the operand.
1051
1052 // Normal .length() would have been constant folded by the front-end.
1053 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001054 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001055 assert(node->getOperand()->getType().isRuntimeSizedArray());
1056 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1057 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001058 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1059 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001060
1061 builder.clearAccessChain();
1062 builder.setAccessChainRValue(length);
1063
1064 return false;
1065 }
1066
John Kessenichfc51d282015-08-19 13:34:18 -06001067 // Start by evaluating the operand
1068
John Kessenich140f3df2015-06-26 16:58:36 -06001069 builder.clearAccessChain();
1070 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001071
Rex Xufc618912015-09-09 16:42:49 +08001072 spv::Id operand = spv::NoResult;
1073
1074 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1075 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001076 node->getOp() == glslang::EOpAtomicCounter ||
1077 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001078 operand = builder.accessChainGetLValue(); // Special case l-value operands
1079 else
John Kessenich32cfd492016-02-02 12:37:46 -07001080 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001081
1082 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001083 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001084
1085 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001086 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001087 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001088
1089 // if not, then possibly an operation
1090 if (! result)
qining25262b32016-05-06 17:25:16 -04001091 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001092
1093 if (result) {
1094 builder.clearAccessChain();
1095 builder.setAccessChainRValue(result);
1096
1097 return false; // done with this node
1098 }
1099
1100 // it must be a special case, check...
1101 switch (node->getOp()) {
1102 case glslang::EOpPostIncrement:
1103 case glslang::EOpPostDecrement:
1104 case glslang::EOpPreIncrement:
1105 case glslang::EOpPreDecrement:
1106 {
1107 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001108 spv::Id one = 0;
1109 if (node->getBasicType() == glslang::EbtFloat)
1110 one = builder.makeFloatConstant(1.0F);
1111 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1112 one = builder.makeInt64Constant(1);
1113 else
1114 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001115 glslang::TOperator op;
1116 if (node->getOp() == glslang::EOpPreIncrement ||
1117 node->getOp() == glslang::EOpPostIncrement)
1118 op = glslang::EOpAdd;
1119 else
1120 op = glslang::EOpSub;
1121
qining25262b32016-05-06 17:25:16 -04001122 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1123 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001124 convertGlslangToSpvType(node->getType()), operand, one,
1125 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001126 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001127
1128 // The result of operation is always stored, but conditionally the
1129 // consumed result. The consumed result is always an r-value.
1130 builder.accessChainStore(result);
1131 builder.clearAccessChain();
1132 if (node->getOp() == glslang::EOpPreIncrement ||
1133 node->getOp() == glslang::EOpPreDecrement)
1134 builder.setAccessChainRValue(result);
1135 else
1136 builder.setAccessChainRValue(operand);
1137 }
1138
1139 return false;
1140
1141 case glslang::EOpEmitStreamVertex:
1142 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1143 return false;
1144 case glslang::EOpEndStreamPrimitive:
1145 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1146 return false;
1147
1148 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001149 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001150 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001151 }
John Kessenich140f3df2015-06-26 16:58:36 -06001152}
1153
1154bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1155{
qining27e04a02016-04-14 16:40:20 -04001156 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1157 if (node->getType().getQualifier().isSpecConstant())
1158 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1159
John Kessenichfc51d282015-08-19 13:34:18 -06001160 spv::Id result = spv::NoResult;
1161
1162 // try texturing
1163 result = createImageTextureFunctionCall(node);
1164 if (result != spv::NoResult) {
1165 builder.clearAccessChain();
1166 builder.setAccessChainRValue(result);
1167
1168 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001169 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001170 // "imageStore" is a special case, which has no result
1171 return false;
1172 }
John Kessenichfc51d282015-08-19 13:34:18 -06001173
John Kessenich140f3df2015-06-26 16:58:36 -06001174 glslang::TOperator binOp = glslang::EOpNull;
1175 bool reduceComparison = true;
1176 bool isMatrix = false;
1177 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001178 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001179
1180 assert(node->getOp());
1181
1182 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1183
1184 switch (node->getOp()) {
1185 case glslang::EOpSequence:
1186 {
1187 if (preVisit)
1188 ++sequenceDepth;
1189 else
1190 --sequenceDepth;
1191
1192 if (sequenceDepth == 1) {
1193 // If this is the parent node of all the functions, we want to see them
1194 // early, so all call points have actual SPIR-V functions to reference.
1195 // In all cases, still let the traverser visit the children for us.
1196 makeFunctions(node->getAsAggregate()->getSequence());
1197
1198 // Also, we want all globals initializers to go into the entry of main(), before
1199 // anything else gets there, so visit out of order, doing them all now.
1200 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1201
1202 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1203 // so do them manually.
1204 visitFunctions(node->getAsAggregate()->getSequence());
1205
1206 return false;
1207 }
1208
1209 return true;
1210 }
1211 case glslang::EOpLinkerObjects:
1212 {
1213 if (visit == glslang::EvPreVisit)
1214 linkageOnly = true;
1215 else
1216 linkageOnly = false;
1217
1218 return true;
1219 }
1220 case glslang::EOpComma:
1221 {
1222 // processing from left to right naturally leaves the right-most
1223 // lying around in the access chain
1224 glslang::TIntermSequence& glslangOperands = node->getSequence();
1225 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1226 glslangOperands[i]->traverse(this);
1227
1228 return false;
1229 }
1230 case glslang::EOpFunction:
1231 if (visit == glslang::EvPreVisit) {
1232 if (isShaderEntrypoint(node)) {
1233 inMain = true;
1234 builder.setBuildPoint(shaderEntry->getLastBlock());
1235 } else {
1236 handleFunctionEntry(node);
1237 }
1238 } else {
1239 if (inMain)
1240 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001241 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001242 inMain = false;
1243 }
1244
1245 return true;
1246 case glslang::EOpParameters:
1247 // Parameters will have been consumed by EOpFunction processing, but not
1248 // the body, so we still visited the function node's children, making this
1249 // child redundant.
1250 return false;
1251 case glslang::EOpFunctionCall:
1252 {
1253 if (node->isUserDefined())
1254 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001255 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1256 if (result) {
1257 builder.clearAccessChain();
1258 builder.setAccessChainRValue(result);
1259 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001260 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001261
1262 return false;
1263 }
1264 case glslang::EOpConstructMat2x2:
1265 case glslang::EOpConstructMat2x3:
1266 case glslang::EOpConstructMat2x4:
1267 case glslang::EOpConstructMat3x2:
1268 case glslang::EOpConstructMat3x3:
1269 case glslang::EOpConstructMat3x4:
1270 case glslang::EOpConstructMat4x2:
1271 case glslang::EOpConstructMat4x3:
1272 case glslang::EOpConstructMat4x4:
1273 case glslang::EOpConstructDMat2x2:
1274 case glslang::EOpConstructDMat2x3:
1275 case glslang::EOpConstructDMat2x4:
1276 case glslang::EOpConstructDMat3x2:
1277 case glslang::EOpConstructDMat3x3:
1278 case glslang::EOpConstructDMat3x4:
1279 case glslang::EOpConstructDMat4x2:
1280 case glslang::EOpConstructDMat4x3:
1281 case glslang::EOpConstructDMat4x4:
1282 isMatrix = true;
1283 // fall through
1284 case glslang::EOpConstructFloat:
1285 case glslang::EOpConstructVec2:
1286 case glslang::EOpConstructVec3:
1287 case glslang::EOpConstructVec4:
1288 case glslang::EOpConstructDouble:
1289 case glslang::EOpConstructDVec2:
1290 case glslang::EOpConstructDVec3:
1291 case glslang::EOpConstructDVec4:
1292 case glslang::EOpConstructBool:
1293 case glslang::EOpConstructBVec2:
1294 case glslang::EOpConstructBVec3:
1295 case glslang::EOpConstructBVec4:
1296 case glslang::EOpConstructInt:
1297 case glslang::EOpConstructIVec2:
1298 case glslang::EOpConstructIVec3:
1299 case glslang::EOpConstructIVec4:
1300 case glslang::EOpConstructUint:
1301 case glslang::EOpConstructUVec2:
1302 case glslang::EOpConstructUVec3:
1303 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001304 case glslang::EOpConstructInt64:
1305 case glslang::EOpConstructI64Vec2:
1306 case glslang::EOpConstructI64Vec3:
1307 case glslang::EOpConstructI64Vec4:
1308 case glslang::EOpConstructUint64:
1309 case glslang::EOpConstructU64Vec2:
1310 case glslang::EOpConstructU64Vec3:
1311 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001312 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001313 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001314 {
1315 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001316 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1318 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001319 if (node->getOp() == glslang::EOpConstructTextureSampler)
1320 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1321 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001322 std::vector<spv::Id> constituents;
1323 for (int c = 0; c < (int)arguments.size(); ++c)
1324 constituents.push_back(arguments[c]);
1325 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001326 } else if (isMatrix)
1327 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1328 else
1329 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001330
1331 builder.clearAccessChain();
1332 builder.setAccessChainRValue(constructed);
1333
1334 return false;
1335 }
1336
1337 // These six are component-wise compares with component-wise results.
1338 // Forward on to createBinaryOperation(), requesting a vector result.
1339 case glslang::EOpLessThan:
1340 case glslang::EOpGreaterThan:
1341 case glslang::EOpLessThanEqual:
1342 case glslang::EOpGreaterThanEqual:
1343 case glslang::EOpVectorEqual:
1344 case glslang::EOpVectorNotEqual:
1345 {
1346 // Map the operation to a binary
1347 binOp = node->getOp();
1348 reduceComparison = false;
1349 switch (node->getOp()) {
1350 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1351 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1352 default: binOp = node->getOp(); break;
1353 }
1354
1355 break;
1356 }
1357 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001358 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001359 binOp = glslang::EOpMul;
1360 break;
1361 case glslang::EOpOuterProduct:
1362 // two vectors multiplied to make a matrix
1363 binOp = glslang::EOpOuterProduct;
1364 break;
1365 case glslang::EOpDot:
1366 {
qining25262b32016-05-06 17:25:16 -04001367 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001368 glslang::TIntermSequence& glslangOperands = node->getSequence();
1369 if (! glslangOperands[0]->getAsTyped()->isVector())
1370 binOp = glslang::EOpMul;
1371 break;
1372 }
1373 case glslang::EOpMod:
1374 // when an aggregate, this is the floating-point mod built-in function,
1375 // which can be emitted by the one in createBinaryOperation()
1376 binOp = glslang::EOpMod;
1377 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001378 case glslang::EOpEmitVertex:
1379 case glslang::EOpEndPrimitive:
1380 case glslang::EOpBarrier:
1381 case glslang::EOpMemoryBarrier:
1382 case glslang::EOpMemoryBarrierAtomicCounter:
1383 case glslang::EOpMemoryBarrierBuffer:
1384 case glslang::EOpMemoryBarrierImage:
1385 case glslang::EOpMemoryBarrierShared:
1386 case glslang::EOpGroupMemoryBarrier:
1387 noReturnValue = true;
1388 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1389 break;
1390
John Kessenich426394d2015-07-23 10:22:48 -06001391 case glslang::EOpAtomicAdd:
1392 case glslang::EOpAtomicMin:
1393 case glslang::EOpAtomicMax:
1394 case glslang::EOpAtomicAnd:
1395 case glslang::EOpAtomicOr:
1396 case glslang::EOpAtomicXor:
1397 case glslang::EOpAtomicExchange:
1398 case glslang::EOpAtomicCompSwap:
1399 atomic = true;
1400 break;
1401
John Kessenich140f3df2015-06-26 16:58:36 -06001402 default:
1403 break;
1404 }
1405
1406 //
1407 // See if it maps to a regular operation.
1408 //
John Kessenich140f3df2015-06-26 16:58:36 -06001409 if (binOp != glslang::EOpNull) {
1410 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1411 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1412 assert(left && right);
1413
1414 builder.clearAccessChain();
1415 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001416 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001417
1418 builder.clearAccessChain();
1419 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001420 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001421
qining25262b32016-05-06 17:25:16 -04001422 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1423 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001424 left->getType().getBasicType(), reduceComparison);
1425
1426 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001427 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001428 builder.clearAccessChain();
1429 builder.setAccessChainRValue(result);
1430
1431 return false;
1432 }
1433
John Kessenich426394d2015-07-23 10:22:48 -06001434 //
1435 // Create the list of operands.
1436 //
John Kessenich140f3df2015-06-26 16:58:36 -06001437 glslang::TIntermSequence& glslangOperands = node->getSequence();
1438 std::vector<spv::Id> operands;
1439 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1440 builder.clearAccessChain();
1441 glslangOperands[arg]->traverse(this);
1442
1443 // special case l-value operands; there are just a few
1444 bool lvalue = false;
1445 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001446 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001447 case glslang::EOpModf:
1448 if (arg == 1)
1449 lvalue = true;
1450 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001451 case glslang::EOpInterpolateAtSample:
1452 case glslang::EOpInterpolateAtOffset:
1453 if (arg == 0)
1454 lvalue = true;
1455 break;
Rex Xud4782c12015-09-06 16:30:11 +08001456 case glslang::EOpAtomicAdd:
1457 case glslang::EOpAtomicMin:
1458 case glslang::EOpAtomicMax:
1459 case glslang::EOpAtomicAnd:
1460 case glslang::EOpAtomicOr:
1461 case glslang::EOpAtomicXor:
1462 case glslang::EOpAtomicExchange:
1463 case glslang::EOpAtomicCompSwap:
1464 if (arg == 0)
1465 lvalue = true;
1466 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001467 case glslang::EOpAddCarry:
1468 case glslang::EOpSubBorrow:
1469 if (arg == 2)
1470 lvalue = true;
1471 break;
1472 case glslang::EOpUMulExtended:
1473 case glslang::EOpIMulExtended:
1474 if (arg >= 2)
1475 lvalue = true;
1476 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001477 default:
1478 break;
1479 }
1480 if (lvalue)
1481 operands.push_back(builder.accessChainGetLValue());
1482 else
John Kessenich32cfd492016-02-02 12:37:46 -07001483 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001484 }
John Kessenich426394d2015-07-23 10:22:48 -06001485
1486 if (atomic) {
1487 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001488 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001489 } else {
1490 // Pass through to generic operations.
1491 switch (glslangOperands.size()) {
1492 case 0:
1493 result = createNoArgOperation(node->getOp());
1494 break;
1495 case 1:
qining25262b32016-05-06 17:25:16 -04001496 result = createUnaryOperation(
1497 node->getOp(), precision,
1498 TranslateNoContractionDecoration(node->getType().getQualifier()),
1499 convertGlslangToSpvType(node->getType()), operands.front(),
1500 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001501 break;
1502 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001503 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001504 break;
1505 }
John Kessenich140f3df2015-06-26 16:58:36 -06001506 }
1507
1508 if (noReturnValue)
1509 return false;
1510
1511 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001512 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001513 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001514 } else {
1515 builder.clearAccessChain();
1516 builder.setAccessChainRValue(result);
1517 return false;
1518 }
1519}
1520
1521bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1522{
1523 // This path handles both if-then-else and ?:
1524 // The if-then-else has a node type of void, while
1525 // ?: has a non-void node type
1526 spv::Id result = 0;
1527 if (node->getBasicType() != glslang::EbtVoid) {
1528 // don't handle this as just on-the-fly temporaries, because there will be two names
1529 // and better to leave SSA to later passes
1530 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1531 }
1532
1533 // emit the condition before doing anything with selection
1534 node->getCondition()->traverse(this);
1535
1536 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001537 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001538
1539 if (node->getTrueBlock()) {
1540 // emit the "then" statement
1541 node->getTrueBlock()->traverse(this);
1542 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001543 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001544 }
1545
1546 if (node->getFalseBlock()) {
1547 ifBuilder.makeBeginElse();
1548 // emit the "else" statement
1549 node->getFalseBlock()->traverse(this);
1550 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001551 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001552 }
1553
1554 ifBuilder.makeEndIf();
1555
1556 if (result) {
1557 // GLSL only has r-values as the result of a :?, but
1558 // if we have an l-value, that can be more efficient if it will
1559 // become the base of a complex r-value expression, because the
1560 // next layer copies r-values into memory to use the access-chain mechanism
1561 builder.clearAccessChain();
1562 builder.setAccessChainLValue(result);
1563 }
1564
1565 return false;
1566}
1567
1568bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1569{
1570 // emit and get the condition before doing anything with switch
1571 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001572 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001573
1574 // browse the children to sort out code segments
1575 int defaultSegment = -1;
1576 std::vector<TIntermNode*> codeSegments;
1577 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1578 std::vector<int> caseValues;
1579 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1580 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1581 TIntermNode* child = *c;
1582 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001583 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001584 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001585 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001586 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1587 } else
1588 codeSegments.push_back(child);
1589 }
1590
qining25262b32016-05-06 17:25:16 -04001591 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001592 // statements between the last case and the end of the switch statement
1593 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1594 (int)codeSegments.size() == defaultSegment)
1595 codeSegments.push_back(nullptr);
1596
1597 // make the switch statement
1598 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001599 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001600
1601 // emit all the code in the segments
1602 breakForLoop.push(false);
1603 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1604 builder.nextSwitchSegment(segmentBlocks, s);
1605 if (codeSegments[s])
1606 codeSegments[s]->traverse(this);
1607 else
1608 builder.addSwitchBreak();
1609 }
1610 breakForLoop.pop();
1611
1612 builder.endSwitch(segmentBlocks);
1613
1614 return false;
1615}
1616
1617void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1618{
1619 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001620 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001621
1622 builder.clearAccessChain();
1623 builder.setAccessChainRValue(constant);
1624}
1625
1626bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1627{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001628 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001629 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001630 // Spec requires back edges to target header blocks, and every header block
1631 // must dominate its merge block. Make a header block first to ensure these
1632 // conditions are met. By definition, it will contain OpLoopMerge, followed
1633 // by a block-ending branch. But we don't want to put any other body/test
1634 // instructions in it, since the body/test may have arbitrary instructions,
1635 // including merges of its own.
1636 builder.setBuildPoint(&blocks.head);
1637 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001638 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001639 spv::Block& test = builder.makeNewBlock();
1640 builder.createBranch(&test);
1641
1642 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001643 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001644 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001645 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001646 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1647
1648 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001649 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001650 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001651 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001652 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001653 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001654
1655 builder.setBuildPoint(&blocks.continue_target);
1656 if (node->getTerminal())
1657 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001658 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001659 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001660 builder.createBranch(&blocks.body);
1661
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001662 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001663 builder.setBuildPoint(&blocks.body);
1664 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001665 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001666 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001667 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001668
1669 builder.setBuildPoint(&blocks.continue_target);
1670 if (node->getTerminal())
1671 node->getTerminal()->traverse(this);
1672 if (node->getTest()) {
1673 node->getTest()->traverse(this);
1674 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001675 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001676 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001677 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001678 // TODO: unless there was a break/return/discard instruction
1679 // somewhere in the body, this is an infinite loop, so we should
1680 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001681 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001682 }
John Kessenich140f3df2015-06-26 16:58:36 -06001683 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001684 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001685 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001686 return false;
1687}
1688
1689bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1690{
1691 if (node->getExpression())
1692 node->getExpression()->traverse(this);
1693
1694 switch (node->getFlowOp()) {
1695 case glslang::EOpKill:
1696 builder.makeDiscard();
1697 break;
1698 case glslang::EOpBreak:
1699 if (breakForLoop.top())
1700 builder.createLoopExit();
1701 else
1702 builder.addSwitchBreak();
1703 break;
1704 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001705 builder.createLoopContinue();
1706 break;
1707 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001708 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001709 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001710 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001711 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001712
1713 builder.clearAccessChain();
1714 break;
1715
1716 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001717 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001718 break;
1719 }
1720
1721 return false;
1722}
1723
1724spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1725{
qining25262b32016-05-06 17:25:16 -04001726 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001727 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001728 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001729 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001730 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001731 }
1732
1733 // Now, handle actual variables
1734 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1735 spv::Id spvType = convertGlslangToSpvType(node->getType());
1736
1737 const char* name = node->getName().c_str();
1738 if (glslang::IsAnonymous(name))
1739 name = "";
1740
1741 return builder.createVariable(storageClass, spvType, name);
1742}
1743
1744// Return type Id of the sampled type.
1745spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1746{
1747 switch (sampler.type) {
1748 case glslang::EbtFloat: return builder.makeFloatType(32);
1749 case glslang::EbtInt: return builder.makeIntType(32);
1750 case glslang::EbtUint: return builder.makeUintType(32);
1751 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001752 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001753 return builder.makeFloatType(32);
1754 }
1755}
1756
John Kessenich3ac051e2015-12-20 11:29:16 -07001757// Convert from a glslang type to an SPV type, by calling into a
1758// recursive version of this function. This establishes the inherited
1759// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001760spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1761{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001762 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001763}
1764
1765// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001766// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001767spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001768{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001769 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001770
1771 switch (type.getBasicType()) {
1772 case glslang::EbtVoid:
1773 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001774 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001775 break;
1776 case glslang::EbtFloat:
1777 spvType = builder.makeFloatType(32);
1778 break;
1779 case glslang::EbtDouble:
1780 spvType = builder.makeFloatType(64);
1781 break;
1782 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001783 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1784 // a 32-bit int where non-0 means true.
1785 if (explicitLayout != glslang::ElpNone)
1786 spvType = builder.makeUintType(32);
1787 else
1788 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001789 break;
1790 case glslang::EbtInt:
1791 spvType = builder.makeIntType(32);
1792 break;
1793 case glslang::EbtUint:
1794 spvType = builder.makeUintType(32);
1795 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001796 case glslang::EbtInt64:
1797 builder.addCapability(spv::CapabilityInt64);
1798 spvType = builder.makeIntType(64);
1799 break;
1800 case glslang::EbtUint64:
1801 builder.addCapability(spv::CapabilityInt64);
1802 spvType = builder.makeUintType(64);
1803 break;
John Kessenich426394d2015-07-23 10:22:48 -06001804 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001805 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 -06001806 spvType = builder.makeUintType(32);
1807 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001808 case glslang::EbtSampler:
1809 {
1810 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001811 if (sampler.sampler) {
1812 // pure sampler
1813 spvType = builder.makeSamplerType();
1814 } else {
1815 // an image is present, make its type
1816 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1817 sampler.image ? 2 : 1, TranslateImageFormat(type));
1818 if (sampler.combined) {
1819 // already has both image and sampler, make the combined type
1820 spvType = builder.makeSampledImageType(spvType);
1821 }
John Kessenich55e7d112015-11-15 21:33:39 -07001822 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001823 }
John Kessenich140f3df2015-06-26 16:58:36 -06001824 break;
1825 case glslang::EbtStruct:
1826 case glslang::EbtBlock:
1827 {
1828 // If we've seen this struct type, return it
1829 const glslang::TTypeList* glslangStruct = type.getStruct();
1830 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001831
1832 // Try to share structs for different layouts, but not yet for other
1833 // kinds of qualification (primarily not yet including interpolant qualification).
1834 if (! HasNonLayoutQualifiers(qualifier))
1835 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1836 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001837 break;
1838
1839 // else, we haven't seen it...
1840
1841 // Create a vector of struct types for SPIR-V to consume
1842 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1843 if (type.getBasicType() == glslang::EbtBlock)
1844 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001845 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001846 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1847 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1848 if (glslangType.hiddenMember()) {
1849 ++memberDelta;
1850 if (type.getBasicType() == glslang::EbtBlock)
1851 memberRemapper[glslangStruct][i] = -1;
1852 } else {
1853 if (type.getBasicType() == glslang::EbtBlock)
1854 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001855 // modify just this child's view of the qualifier
1856 glslang::TQualifier subQualifier = glslangType.getQualifier();
1857 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001858
1859 // manually inherit location; it's more complex
1860 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1861 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1862 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001863 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001864
1865 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001866 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001867 }
1868 }
1869
1870 // Make the SPIR-V type
1871 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001872 if (! HasNonLayoutQualifiers(qualifier))
1873 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001874
1875 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001876 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001877 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001878 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1879 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1880 int member = i;
1881 if (type.getBasicType() == glslang::EbtBlock)
1882 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001883
John Kesseniche0b6cad2015-12-24 10:30:13 -07001884 // modify just this child's view of the qualifier
1885 glslang::TQualifier subQualifier = glslangType.getQualifier();
1886 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001887
John Kessenich140f3df2015-06-26 16:58:36 -06001888 // using -1 above to indicate a hidden member
1889 if (member >= 0) {
1890 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001891 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001892 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1894 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001895
Rex Xu1da878f2016-02-21 20:59:01 +08001896 if (qualifier.storage == glslang::EvqBuffer) {
1897 std::vector<spv::Decoration> memory;
1898 TranslateMemoryDecoration(subQualifier, memory);
1899 for (unsigned int i = 0; i < memory.size(); ++i)
1900 addMemberDecoration(spvType, member, memory[i]);
1901 }
1902
John Kessenich09677482016-02-19 12:21:50 -07001903 // compute location decoration; tricky based on whether inheritance is at play
1904 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1905 // probably move to the linker stage of the front end proper, and just have the
1906 // answer sitting already distributed throughout the individual member locations.
1907 int location = -1; // will only decorate if present or inherited
1908 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1909 location = subQualifier.layoutLocation;
1910 else if (qualifier.hasLocation()) // inheritance
1911 location = qualifier.layoutLocation + locationOffset;
1912 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001913 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001914 if (location >= 0)
1915 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1916
1917 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001918 if (glslangType.getQualifier().hasComponent())
1919 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1920 if (glslangType.getQualifier().hasXfbOffset())
1921 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001922 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001923 // figure out what to do with offset, which is accumulating
1924 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001925 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001926 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001927 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001928 offset = nextOffset;
1929 }
John Kessenich140f3df2015-06-26 16:58:36 -06001930
John Kessenichf85e8062015-12-19 13:57:10 -07001931 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001932 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001933
John Kessenich140f3df2015-06-26 16:58:36 -06001934 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001935 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001936 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001937 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001938 }
1939 }
1940
1941 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001942 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001943 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001944 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001945 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001946 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001947 }
John Kessenich140f3df2015-06-26 16:58:36 -06001948 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001949 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001950 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001951 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001952 if (type.getQualifier().hasXfbBuffer())
1953 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1954 }
1955 }
1956 break;
1957 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001958 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001959 break;
1960 }
1961
1962 if (type.isMatrix())
1963 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1964 else {
1965 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1966 if (type.getVectorSize() > 1)
1967 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1968 }
1969
1970 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001971 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1972
John Kessenichc9a80832015-09-12 12:17:44 -06001973 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001974 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001975 // We need to decorate array strides for types needing explicit layout, except blocks.
1976 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001977 // Use a dummy glslang type for querying internal strides of
1978 // arrays of arrays, but using just a one-dimensional array.
1979 glslang::TType simpleArrayType(type, 0); // deference type of the array
1980 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1981 simpleArrayType.getArraySizes().dereference();
1982
1983 // Will compute the higher-order strides here, rather than making a whole
1984 // pile of types and doing repetitive recursion on their contents.
1985 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1986 }
John Kessenichf8842e52016-01-04 19:22:56 -07001987
1988 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001989 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001990 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001991 if (stride > 0)
1992 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001993 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001994 }
1995 } else {
1996 // single-dimensional array, and don't yet have stride
1997
John Kessenichf8842e52016-01-04 19:22:56 -07001998 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001999 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2000 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002001 }
John Kessenich31ed4832015-09-09 17:51:38 -06002002
John Kessenichc9a80832015-09-12 12:17:44 -06002003 // Do the outer dimension, which might not be known for a runtime-sized array
2004 if (type.isRuntimeSizedArray()) {
2005 spvType = builder.makeRuntimeArray(spvType);
2006 } else {
2007 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002008 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002009 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002010 if (stride > 0)
2011 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002012 }
2013
2014 return spvType;
2015}
2016
John Kessenich6c292d32016-02-15 20:58:50 -07002017// Turn the expression forming the array size into an id.
2018// This is not quite trivial, because of specialization constants.
2019// Sometimes, a raw constant is turned into an Id, and sometimes
2020// a specialization constant expression is.
2021spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2022{
2023 // First, see if this is sized with a node, meaning a specialization constant:
2024 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2025 if (specNode != nullptr) {
2026 builder.clearAccessChain();
2027 specNode->traverse(this);
2028 return accessChainLoad(specNode->getAsTyped()->getType());
2029 }
qining25262b32016-05-06 17:25:16 -04002030
John Kessenich6c292d32016-02-15 20:58:50 -07002031 // Otherwise, need a compile-time (front end) size, get it:
2032 int size = arraySizes.getDimSize(dim);
2033 assert(size > 0);
2034 return builder.makeUintConstant(size);
2035}
2036
John Kessenich103bef92016-02-08 21:38:15 -07002037// Wrap the builder's accessChainLoad to:
2038// - localize handling of RelaxedPrecision
2039// - use the SPIR-V inferred type instead of another conversion of the glslang type
2040// (avoids unnecessary work and possible type punning for structures)
2041// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002042spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2043{
John Kessenich103bef92016-02-08 21:38:15 -07002044 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2045 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2046
2047 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002048 if (type.getBasicType() == glslang::EbtBool) {
2049 if (builder.isScalarType(nominalTypeId)) {
2050 // Conversion for bool
2051 spv::Id boolType = builder.makeBoolType();
2052 if (nominalTypeId != boolType)
2053 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2054 } else if (builder.isVectorType(nominalTypeId)) {
2055 // Conversion for bvec
2056 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2057 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2058 if (nominalTypeId != bvecType)
2059 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2060 }
2061 }
John Kessenich103bef92016-02-08 21:38:15 -07002062
2063 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002064}
2065
Rex Xu27253232016-02-23 17:51:09 +08002066// Wrap the builder's accessChainStore to:
2067// - do conversion of concrete to abstract type
2068void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2069{
2070 // Need to convert to abstract types when necessary
2071 if (type.getBasicType() == glslang::EbtBool) {
2072 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2073
2074 if (builder.isScalarType(nominalTypeId)) {
2075 // Conversion for bool
2076 spv::Id boolType = builder.makeBoolType();
2077 if (nominalTypeId != boolType) {
2078 spv::Id zero = builder.makeUintConstant(0);
2079 spv::Id one = builder.makeUintConstant(1);
2080 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2081 }
2082 } else if (builder.isVectorType(nominalTypeId)) {
2083 // Conversion for bvec
2084 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2085 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2086 if (nominalTypeId != bvecType) {
2087 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2088 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2089 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2090 }
2091 }
2092 }
2093
2094 builder.accessChainStore(rvalue);
2095}
2096
John Kessenichf85e8062015-12-19 13:57:10 -07002097// Decide whether or not this type should be
2098// decorated with offsets and strides, and if so
2099// whether std140 or std430 rules should be applied.
2100glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002101{
John Kessenichf85e8062015-12-19 13:57:10 -07002102 // has to be a block
2103 if (type.getBasicType() != glslang::EbtBlock)
2104 return glslang::ElpNone;
2105
2106 // has to be a uniform or buffer block
2107 if (type.getQualifier().storage != glslang::EvqUniform &&
2108 type.getQualifier().storage != glslang::EvqBuffer)
2109 return glslang::ElpNone;
2110
2111 // return the layout to use
2112 switch (type.getQualifier().layoutPacking) {
2113 case glslang::ElpStd140:
2114 case glslang::ElpStd430:
2115 return type.getQualifier().layoutPacking;
2116 default:
2117 return glslang::ElpNone;
2118 }
John Kessenich31ed4832015-09-09 17:51:38 -06002119}
2120
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002121// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002122int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002123{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002124 int size;
John Kessenich49987892015-12-29 17:11:44 -07002125 int stride;
2126 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002127
2128 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002129}
2130
John Kessenich49987892015-12-29 17:11:44 -07002131// 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 -07002132// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002133int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002134{
John Kessenich49987892015-12-29 17:11:44 -07002135 glslang::TType elementType;
2136 elementType.shallowCopy(matrixType);
2137 elementType.clearArraySizes();
2138
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002139 int size;
John Kessenich49987892015-12-29 17:11:44 -07002140 int stride;
2141 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2142
2143 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002144}
2145
John Kessenich5e4b1242015-08-06 22:53:06 -06002146// Given a member type of a struct, realign the current offset for it, and compute
2147// the next (not yet aligned) offset for the next member, which will get aligned
2148// on the next call.
2149// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2150// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2151// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002152void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002153 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002154{
2155 // this will get a positive value when deemed necessary
2156 nextOffset = -1;
2157
John Kessenich5e4b1242015-08-06 22:53:06 -06002158 // override anything in currentOffset with user-set offset
2159 if (memberType.getQualifier().hasOffset())
2160 currentOffset = memberType.getQualifier().layoutOffset;
2161
2162 // It could be that current linker usage in glslang updated all the layoutOffset,
2163 // in which case the following code does not matter. But, that's not quite right
2164 // once cross-compilation unit GLSL validation is done, as the original user
2165 // settings are needed in layoutOffset, and then the following will come into play.
2166
John Kessenichf85e8062015-12-19 13:57:10 -07002167 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002168 if (! memberType.getQualifier().hasOffset())
2169 currentOffset = -1;
2170
2171 return;
2172 }
2173
John Kessenichf85e8062015-12-19 13:57:10 -07002174 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002175 if (currentOffset < 0)
2176 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002177
John Kessenich5e4b1242015-08-06 22:53:06 -06002178 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2179 // but possibly not yet correctly aligned.
2180
2181 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002182 int dummyStride;
2183 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002184 glslang::RoundToPow2(currentOffset, memberAlignment);
2185 nextOffset = currentOffset + memberSize;
2186}
2187
John Kessenichebb50532016-05-16 19:22:05 -06002188void TGlslangToSpvTraverser::declareClipCullCapability(const glslang::TTypeList& members, int member)
2189{
2190 if (members[member].type->getQualifier().builtIn == glslang::EbvClipDistance)
2191 builder.addCapability(spv::CapabilityClipDistance);
2192 if (members[member].type->getQualifier().builtIn == glslang::EbvCullDistance)
2193 builder.addCapability(spv::CapabilityCullDistance);
2194}
2195
John Kessenich140f3df2015-06-26 16:58:36 -06002196bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2197{
John Kessenich4d65ee32016-03-12 18:17:47 -07002198 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002199 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002200 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002201}
2202
2203// Make all the functions, skeletally, without actually visiting their bodies.
2204void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2205{
2206 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2207 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2208 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2209 continue;
2210
2211 // We're on a user function. Set up the basic interface for the function now,
2212 // so that it's available to call.
2213 // Translating the body will happen later.
2214 //
qining25262b32016-05-06 17:25:16 -04002215 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002216 // function. What it is an address of varies:
2217 //
2218 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2219 // so that write needs to be to a copy, hence the address of a copy works.
2220 //
2221 // - "const in" parameters can just be the r-value, as no writes need occur.
2222 //
2223 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2224 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2225
2226 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002227 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002228 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2229
2230 for (int p = 0; p < (int)parameters.size(); ++p) {
2231 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2232 spv::Id typeId = convertGlslangToSpvType(paramType);
2233 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2234 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2235 else
2236 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002237 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002238 paramTypes.push_back(typeId);
2239 }
2240
2241 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002242 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2243 convertGlslangToSpvType(glslFunction->getType()),
2244 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002245
2246 // Track function to emit/call later
2247 functionMap[glslFunction->getName().c_str()] = function;
2248
2249 // Set the parameter id's
2250 for (int p = 0; p < (int)parameters.size(); ++p) {
2251 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2252 // give a name too
2253 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2254 }
2255 }
2256}
2257
2258// Process all the initializers, while skipping the functions and link objects
2259void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2260{
2261 builder.setBuildPoint(shaderEntry->getLastBlock());
2262 for (int i = 0; i < (int)initializers.size(); ++i) {
2263 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2264 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2265
2266 // We're on a top-level node that's not a function. Treat as an initializer, whose
2267 // code goes into the beginning of main.
2268 initializer->traverse(this);
2269 }
2270 }
2271}
2272
2273// Process all the functions, while skipping initializers.
2274void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2275{
2276 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2277 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2278 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2279 node->traverse(this);
2280 }
2281}
2282
2283void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2284{
qining25262b32016-05-06 17:25:16 -04002285 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002286 // that called makeFunctions().
2287 spv::Function* function = functionMap[node->getName().c_str()];
2288 spv::Block* functionBlock = function->getEntryBlock();
2289 builder.setBuildPoint(functionBlock);
2290}
2291
Rex Xu04db3f52015-09-16 11:44:02 +08002292void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002293{
Rex Xufc618912015-09-09 16:42:49 +08002294 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002295
2296 glslang::TSampler sampler = {};
2297 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002298 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002299 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2300 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2301 }
2302
John Kessenich140f3df2015-06-26 16:58:36 -06002303 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2304 builder.clearAccessChain();
2305 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002306
2307 // Special case l-value operands
2308 bool lvalue = false;
2309 switch (node.getOp()) {
2310 case glslang::EOpImageAtomicAdd:
2311 case glslang::EOpImageAtomicMin:
2312 case glslang::EOpImageAtomicMax:
2313 case glslang::EOpImageAtomicAnd:
2314 case glslang::EOpImageAtomicOr:
2315 case glslang::EOpImageAtomicXor:
2316 case glslang::EOpImageAtomicExchange:
2317 case glslang::EOpImageAtomicCompSwap:
2318 if (i == 0)
2319 lvalue = true;
2320 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002321 case glslang::EOpSparseImageLoad:
2322 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2323 lvalue = true;
2324 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002325 case glslang::EOpSparseTexture:
2326 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2327 lvalue = true;
2328 break;
2329 case glslang::EOpSparseTextureClamp:
2330 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2331 lvalue = true;
2332 break;
2333 case glslang::EOpSparseTextureLod:
2334 case glslang::EOpSparseTextureOffset:
2335 if (i == 3)
2336 lvalue = true;
2337 break;
2338 case glslang::EOpSparseTextureFetch:
2339 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2340 lvalue = true;
2341 break;
2342 case glslang::EOpSparseTextureFetchOffset:
2343 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2344 lvalue = true;
2345 break;
2346 case glslang::EOpSparseTextureLodOffset:
2347 case glslang::EOpSparseTextureGrad:
2348 case glslang::EOpSparseTextureOffsetClamp:
2349 if (i == 4)
2350 lvalue = true;
2351 break;
2352 case glslang::EOpSparseTextureGradOffset:
2353 case glslang::EOpSparseTextureGradClamp:
2354 if (i == 5)
2355 lvalue = true;
2356 break;
2357 case glslang::EOpSparseTextureGradOffsetClamp:
2358 if (i == 6)
2359 lvalue = true;
2360 break;
2361 case glslang::EOpSparseTextureGather:
2362 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2363 lvalue = true;
2364 break;
2365 case glslang::EOpSparseTextureGatherOffset:
2366 case glslang::EOpSparseTextureGatherOffsets:
2367 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2368 lvalue = true;
2369 break;
Rex Xufc618912015-09-09 16:42:49 +08002370 default:
2371 break;
2372 }
2373
Rex Xu6b86d492015-09-16 17:48:22 +08002374 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002375 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002376 else
John Kessenich32cfd492016-02-02 12:37:46 -07002377 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002378 }
2379}
2380
John Kessenichfc51d282015-08-19 13:34:18 -06002381void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002382{
John Kessenichfc51d282015-08-19 13:34:18 -06002383 builder.clearAccessChain();
2384 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002385 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002386}
John Kessenich140f3df2015-06-26 16:58:36 -06002387
John Kessenichfc51d282015-08-19 13:34:18 -06002388spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2389{
Rex Xufc618912015-09-09 16:42:49 +08002390 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002391 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002392 }
2393
John Kessenichfc51d282015-08-19 13:34:18 -06002394 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002395 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2396 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2397 std::vector<spv::Id> arguments;
2398 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002399 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002400 else
2401 translateArguments(*node->getAsUnaryNode(), arguments);
2402 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2403
2404 spv::Builder::TextureParameters params = { };
2405 params.sampler = arguments[0];
2406
Rex Xu04db3f52015-09-16 11:44:02 +08002407 glslang::TCrackedTextureOp cracked;
2408 node->crackTexture(sampler, cracked);
2409
John Kessenichfc51d282015-08-19 13:34:18 -06002410 // Check for queries
2411 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002412 // a sampled image needs to have the image extracted first
2413 if (builder.isSampledImage(params.sampler))
2414 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002415 switch (node->getOp()) {
2416 case glslang::EOpImageQuerySize:
2417 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002418 if (arguments.size() > 1) {
2419 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002420 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002421 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002422 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002423 case glslang::EOpImageQuerySamples:
2424 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002425 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002426 case glslang::EOpTextureQueryLod:
2427 params.coords = arguments[1];
2428 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2429 case glslang::EOpTextureQueryLevels:
2430 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002431 case glslang::EOpSparseTexelsResident:
2432 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002433 default:
2434 assert(0);
2435 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002436 }
John Kessenich140f3df2015-06-26 16:58:36 -06002437 }
2438
Rex Xufc618912015-09-09 16:42:49 +08002439 // Check for image functions other than queries
2440 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002441 std::vector<spv::Id> operands;
2442 auto opIt = arguments.begin();
2443 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002444
2445 // Handle subpass operations
2446 // TODO: GLSL should change to have the "MS" only on the type rather than the
2447 // built-in function.
2448 if (cracked.subpass) {
2449 // add on the (0,0) coordinate
2450 spv::Id zero = builder.makeIntConstant(0);
2451 std::vector<spv::Id> comps;
2452 comps.push_back(zero);
2453 comps.push_back(zero);
2454 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2455 if (sampler.ms) {
2456 operands.push_back(spv::ImageOperandsSampleMask);
2457 operands.push_back(*(opIt++));
2458 }
2459 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2460 }
2461
John Kessenich56bab042015-09-16 10:54:31 -06002462 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002463 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002464 if (sampler.ms) {
2465 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002466 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002467 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002468 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2469 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002470 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002471 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002472 if (sampler.ms) {
2473 operands.push_back(*(opIt + 1));
2474 operands.push_back(spv::ImageOperandsSampleMask);
2475 operands.push_back(*opIt);
2476 } else
2477 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002478 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002479 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2480 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002481 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002482 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2483 builder.addCapability(spv::CapabilitySparseResidency);
2484 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2485 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2486
2487 if (sampler.ms) {
2488 operands.push_back(spv::ImageOperandsSampleMask);
2489 operands.push_back(*opIt++);
2490 }
2491
2492 // Create the return type that was a special structure
2493 spv::Id texelOut = *opIt;
2494 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2495 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2496 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2497
2498 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2499
2500 // Decode the return type
2501 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2502 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002503 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002504 // Process image atomic operations
2505
2506 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2507 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002508 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002509
Rex Xufc618912015-09-09 16:42:49 +08002510 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002511 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002512
2513 std::vector<spv::Id> operands;
2514 operands.push_back(pointer);
2515 for (; opIt != arguments.end(); ++opIt)
2516 operands.push_back(*opIt);
2517
Rex Xu04db3f52015-09-16 11:44:02 +08002518 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002519 }
2520 }
2521
2522 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002523 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002524 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2525
John Kessenichfc51d282015-08-19 13:34:18 -06002526 // check for bias argument
2527 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002528 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002529 int nonBiasArgCount = 2;
2530 if (cracked.offset)
2531 ++nonBiasArgCount;
2532 if (cracked.grad)
2533 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002534 if (cracked.lodClamp)
2535 ++nonBiasArgCount;
2536 if (sparse)
2537 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002538
2539 if ((int)arguments.size() > nonBiasArgCount)
2540 bias = true;
2541 }
2542
John Kessenichfc51d282015-08-19 13:34:18 -06002543 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002544
John Kessenichfc51d282015-08-19 13:34:18 -06002545 params.coords = arguments[1];
2546 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002547 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002548
2549 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002550 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002551 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002552 ++extraArgs;
2553 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002554 params.Dref = arguments[2];
2555 ++extraArgs;
2556 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002557 std::vector<spv::Id> indexes;
2558 int comp;
2559 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002560 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002561 else
2562 comp = builder.getNumComponents(params.coords) - 1;
2563 indexes.push_back(comp);
2564 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2565 }
2566 if (cracked.lod) {
2567 params.lod = arguments[2];
2568 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002569 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2570 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2571 noImplicitLod = true;
2572 }
2573 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002574 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002575 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002576 }
2577 if (cracked.grad) {
2578 params.gradX = arguments[2 + extraArgs];
2579 params.gradY = arguments[3 + extraArgs];
2580 extraArgs += 2;
2581 }
John Kessenich55e7d112015-11-15 21:33:39 -07002582 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002583 params.offset = arguments[2 + extraArgs];
2584 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002585 } else if (cracked.offsets) {
2586 params.offsets = arguments[2 + extraArgs];
2587 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002588 }
Rex Xu48edadf2015-12-31 16:11:41 +08002589 if (cracked.lodClamp) {
2590 params.lodClamp = arguments[2 + extraArgs];
2591 ++extraArgs;
2592 }
2593 if (sparse) {
2594 params.texelOut = arguments[2 + extraArgs];
2595 ++extraArgs;
2596 }
John Kessenichfc51d282015-08-19 13:34:18 -06002597 if (bias) {
2598 params.bias = arguments[2 + extraArgs];
2599 ++extraArgs;
2600 }
John Kessenich55e7d112015-11-15 21:33:39 -07002601 if (cracked.gather && ! sampler.shadow) {
2602 // default component is 0, if missing, otherwise an argument
2603 if (2 + extraArgs < (int)arguments.size()) {
2604 params.comp = arguments[2 + extraArgs];
2605 ++extraArgs;
2606 } else {
2607 params.comp = builder.makeIntConstant(0);
2608 }
2609 }
John Kessenichfc51d282015-08-19 13:34:18 -06002610
John Kessenich019f08f2016-02-15 15:40:42 -07002611 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002612}
2613
2614spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2615{
2616 // Grab the function's pointer from the previously created function
2617 spv::Function* function = functionMap[node->getName().c_str()];
2618 if (! function)
2619 return 0;
2620
2621 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2622 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2623
2624 // See comments in makeFunctions() for details about the semantics for parameter passing.
2625 //
2626 // These imply we need a four step process:
2627 // 1. Evaluate the arguments
2628 // 2. Allocate and make copies of in, out, and inout arguments
2629 // 3. Make the call
2630 // 4. Copy back the results
2631
2632 // 1. Evaluate the arguments
2633 std::vector<spv::Builder::AccessChain> lValues;
2634 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002635 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002636 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2637 // build l-value
2638 builder.clearAccessChain();
2639 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002640 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002641 // keep outputs as l-values, evaluate input-only as r-values
2642 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2643 // save l-value
2644 lValues.push_back(builder.getAccessChain());
2645 } else {
2646 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002647 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002648 }
2649 }
2650
2651 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2652 // copy the original into that space.
2653 //
2654 // Also, build up the list of actual arguments to pass in for the call
2655 int lValueCount = 0;
2656 int rValueCount = 0;
2657 std::vector<spv::Id> spvArgs;
2658 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2659 spv::Id arg;
2660 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2661 // need space to hold the copy
2662 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2663 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2664 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2665 // need to copy the input into output space
2666 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002667 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002668 builder.createStore(copy, arg);
2669 }
2670 ++lValueCount;
2671 } else {
2672 arg = rValues[rValueCount];
2673 ++rValueCount;
2674 }
2675 spvArgs.push_back(arg);
2676 }
2677
2678 // 3. Make the call.
2679 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002680 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002681
2682 // 4. Copy back out an "out" arguments.
2683 lValueCount = 0;
2684 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2685 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2686 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2687 spv::Id copy = builder.createLoad(spvArgs[a]);
2688 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002689 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002690 }
2691 ++lValueCount;
2692 }
2693 }
2694
2695 return result;
2696}
2697
2698// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002699spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2700 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002701 spv::Id typeId, spv::Id left, spv::Id right,
2702 glslang::TBasicType typeProxy, bool reduceComparison)
2703{
Rex Xu8ff43de2016-04-22 16:51:45 +08002704 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002705 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002706 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002707
2708 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002709 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002710 bool comparison = false;
2711
2712 switch (op) {
2713 case glslang::EOpAdd:
2714 case glslang::EOpAddAssign:
2715 if (isFloat)
2716 binOp = spv::OpFAdd;
2717 else
2718 binOp = spv::OpIAdd;
2719 break;
2720 case glslang::EOpSub:
2721 case glslang::EOpSubAssign:
2722 if (isFloat)
2723 binOp = spv::OpFSub;
2724 else
2725 binOp = spv::OpISub;
2726 break;
2727 case glslang::EOpMul:
2728 case glslang::EOpMulAssign:
2729 if (isFloat)
2730 binOp = spv::OpFMul;
2731 else
2732 binOp = spv::OpIMul;
2733 break;
2734 case glslang::EOpVectorTimesScalar:
2735 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002736 if (isFloat) {
2737 if (builder.isVector(right))
2738 std::swap(left, right);
2739 assert(builder.isScalar(right));
2740 needMatchingVectors = false;
2741 binOp = spv::OpVectorTimesScalar;
2742 } else
2743 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002744 break;
2745 case glslang::EOpVectorTimesMatrix:
2746 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002747 binOp = spv::OpVectorTimesMatrix;
2748 break;
2749 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002750 binOp = spv::OpMatrixTimesVector;
2751 break;
2752 case glslang::EOpMatrixTimesScalar:
2753 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002754 binOp = spv::OpMatrixTimesScalar;
2755 break;
2756 case glslang::EOpMatrixTimesMatrix:
2757 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002758 binOp = spv::OpMatrixTimesMatrix;
2759 break;
2760 case glslang::EOpOuterProduct:
2761 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002762 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002763 break;
2764
2765 case glslang::EOpDiv:
2766 case glslang::EOpDivAssign:
2767 if (isFloat)
2768 binOp = spv::OpFDiv;
2769 else if (isUnsigned)
2770 binOp = spv::OpUDiv;
2771 else
2772 binOp = spv::OpSDiv;
2773 break;
2774 case glslang::EOpMod:
2775 case glslang::EOpModAssign:
2776 if (isFloat)
2777 binOp = spv::OpFMod;
2778 else if (isUnsigned)
2779 binOp = spv::OpUMod;
2780 else
2781 binOp = spv::OpSMod;
2782 break;
2783 case glslang::EOpRightShift:
2784 case glslang::EOpRightShiftAssign:
2785 if (isUnsigned)
2786 binOp = spv::OpShiftRightLogical;
2787 else
2788 binOp = spv::OpShiftRightArithmetic;
2789 break;
2790 case glslang::EOpLeftShift:
2791 case glslang::EOpLeftShiftAssign:
2792 binOp = spv::OpShiftLeftLogical;
2793 break;
2794 case glslang::EOpAnd:
2795 case glslang::EOpAndAssign:
2796 binOp = spv::OpBitwiseAnd;
2797 break;
2798 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002799 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002800 binOp = spv::OpLogicalAnd;
2801 break;
2802 case glslang::EOpInclusiveOr:
2803 case glslang::EOpInclusiveOrAssign:
2804 binOp = spv::OpBitwiseOr;
2805 break;
2806 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002807 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002808 binOp = spv::OpLogicalOr;
2809 break;
2810 case glslang::EOpExclusiveOr:
2811 case glslang::EOpExclusiveOrAssign:
2812 binOp = spv::OpBitwiseXor;
2813 break;
2814 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002815 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002816 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002817 break;
2818
2819 case glslang::EOpLessThan:
2820 case glslang::EOpGreaterThan:
2821 case glslang::EOpLessThanEqual:
2822 case glslang::EOpGreaterThanEqual:
2823 case glslang::EOpEqual:
2824 case glslang::EOpNotEqual:
2825 case glslang::EOpVectorEqual:
2826 case glslang::EOpVectorNotEqual:
2827 comparison = true;
2828 break;
2829 default:
2830 break;
2831 }
2832
John Kessenich7c1aa102015-10-15 13:29:11 -06002833 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002834 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002835 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002836 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002837 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002838
2839 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002840 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002841 builder.promoteScalar(precision, left, right);
2842
qining25262b32016-05-06 17:25:16 -04002843 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2844 addDecoration(result, noContraction);
2845 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002846 }
2847
2848 if (! comparison)
2849 return 0;
2850
John Kessenich7c1aa102015-10-15 13:29:11 -06002851 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002852
2853 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2854 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2855
John Kessenich22118352015-12-21 20:54:09 -07002856 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002857 }
2858
2859 switch (op) {
2860 case glslang::EOpLessThan:
2861 if (isFloat)
2862 binOp = spv::OpFOrdLessThan;
2863 else if (isUnsigned)
2864 binOp = spv::OpULessThan;
2865 else
2866 binOp = spv::OpSLessThan;
2867 break;
2868 case glslang::EOpGreaterThan:
2869 if (isFloat)
2870 binOp = spv::OpFOrdGreaterThan;
2871 else if (isUnsigned)
2872 binOp = spv::OpUGreaterThan;
2873 else
2874 binOp = spv::OpSGreaterThan;
2875 break;
2876 case glslang::EOpLessThanEqual:
2877 if (isFloat)
2878 binOp = spv::OpFOrdLessThanEqual;
2879 else if (isUnsigned)
2880 binOp = spv::OpULessThanEqual;
2881 else
2882 binOp = spv::OpSLessThanEqual;
2883 break;
2884 case glslang::EOpGreaterThanEqual:
2885 if (isFloat)
2886 binOp = spv::OpFOrdGreaterThanEqual;
2887 else if (isUnsigned)
2888 binOp = spv::OpUGreaterThanEqual;
2889 else
2890 binOp = spv::OpSGreaterThanEqual;
2891 break;
2892 case glslang::EOpEqual:
2893 case glslang::EOpVectorEqual:
2894 if (isFloat)
2895 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002896 else if (isBool)
2897 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002898 else
2899 binOp = spv::OpIEqual;
2900 break;
2901 case glslang::EOpNotEqual:
2902 case glslang::EOpVectorNotEqual:
2903 if (isFloat)
2904 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002905 else if (isBool)
2906 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002907 else
2908 binOp = spv::OpINotEqual;
2909 break;
2910 default:
2911 break;
2912 }
2913
qining25262b32016-05-06 17:25:16 -04002914 if (binOp != spv::OpNop) {
2915 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2916 addDecoration(result, noContraction);
2917 return builder.setPrecision(result, precision);
2918 }
John Kessenich140f3df2015-06-26 16:58:36 -06002919
2920 return 0;
2921}
2922
John Kessenich04bb8a02015-12-12 12:28:14 -07002923//
2924// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2925// These can be any of:
2926//
2927// matrix * scalar
2928// scalar * matrix
2929// matrix * matrix linear algebraic
2930// matrix * vector
2931// vector * matrix
2932// matrix * matrix componentwise
2933// matrix op matrix op in {+, -, /}
2934// matrix op scalar op in {+, -, /}
2935// scalar op matrix op in {+, -, /}
2936//
qining25262b32016-05-06 17:25:16 -04002937spv::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 -07002938{
2939 bool firstClass = true;
2940
2941 // First, handle first-class matrix operations (* and matrix/scalar)
2942 switch (op) {
2943 case spv::OpFDiv:
2944 if (builder.isMatrix(left) && builder.isScalar(right)) {
2945 // turn matrix / scalar into a multiply...
2946 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2947 op = spv::OpMatrixTimesScalar;
2948 } else
2949 firstClass = false;
2950 break;
2951 case spv::OpMatrixTimesScalar:
2952 if (builder.isMatrix(right))
2953 std::swap(left, right);
2954 assert(builder.isScalar(right));
2955 break;
2956 case spv::OpVectorTimesMatrix:
2957 assert(builder.isVector(left));
2958 assert(builder.isMatrix(right));
2959 break;
2960 case spv::OpMatrixTimesVector:
2961 assert(builder.isMatrix(left));
2962 assert(builder.isVector(right));
2963 break;
2964 case spv::OpMatrixTimesMatrix:
2965 assert(builder.isMatrix(left));
2966 assert(builder.isMatrix(right));
2967 break;
2968 default:
2969 firstClass = false;
2970 break;
2971 }
2972
qining25262b32016-05-06 17:25:16 -04002973 if (firstClass) {
2974 spv::Id result = builder.createBinOp(op, typeId, left, right);
2975 addDecoration(result, noContraction);
2976 return builder.setPrecision(result, precision);
2977 }
John Kessenich04bb8a02015-12-12 12:28:14 -07002978
2979 // Handle component-wise +, -, *, and / for all combinations of type.
2980 // The result type of all of them is the same type as the (a) matrix operand.
2981 // The algorithm is to:
2982 // - break the matrix(es) into vectors
2983 // - smear any scalar to a vector
2984 // - do vector operations
2985 // - make a matrix out the vector results
2986 switch (op) {
2987 case spv::OpFAdd:
2988 case spv::OpFSub:
2989 case spv::OpFDiv:
2990 case spv::OpFMul:
2991 {
2992 // one time set up...
2993 bool leftMat = builder.isMatrix(left);
2994 bool rightMat = builder.isMatrix(right);
2995 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2996 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2997 spv::Id scalarType = builder.getScalarTypeId(typeId);
2998 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2999 std::vector<spv::Id> results;
3000 spv::Id smearVec = spv::NoResult;
3001 if (builder.isScalar(left))
3002 smearVec = builder.smearScalar(precision, left, vecType);
3003 else if (builder.isScalar(right))
3004 smearVec = builder.smearScalar(precision, right, vecType);
3005
3006 // do each vector op
3007 for (unsigned int c = 0; c < numCols; ++c) {
3008 std::vector<unsigned int> indexes;
3009 indexes.push_back(c);
3010 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3011 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003012 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3013 addDecoration(result, noContraction);
3014 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003015 }
3016
3017 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003018 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003019 }
3020 default:
3021 assert(0);
3022 return spv::NoResult;
3023 }
3024}
3025
qining25262b32016-05-06 17:25:16 -04003026spv::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 -06003027{
3028 spv::Op unaryOp = spv::OpNop;
3029 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003030 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003031 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003032
3033 switch (op) {
3034 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003035 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003036 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003037 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003038 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003039 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003040 unaryOp = spv::OpSNegate;
3041 break;
3042
3043 case glslang::EOpLogicalNot:
3044 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003045 unaryOp = spv::OpLogicalNot;
3046 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003047 case glslang::EOpBitwiseNot:
3048 unaryOp = spv::OpNot;
3049 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003050
John Kessenich140f3df2015-06-26 16:58:36 -06003051 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003052 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003053 break;
3054 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003055 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003056 break;
3057 case glslang::EOpTranspose:
3058 unaryOp = spv::OpTranspose;
3059 break;
3060
3061 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003062 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003063 break;
3064 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003065 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003066 break;
3067 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003068 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003069 break;
3070 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003071 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003072 break;
3073 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003074 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003075 break;
3076 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003077 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003078 break;
3079 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003080 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003081 break;
3082 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003083 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003084 break;
3085
3086 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003087 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
3089 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003090 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003091 break;
3092 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003093 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003094 break;
3095 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003096 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003097 break;
3098 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003099 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003100 break;
3101 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003102 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003103 break;
3104
3105 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003106 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003107 break;
3108 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003109 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003110 break;
3111
3112 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003113 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003114 break;
3115 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003116 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003117 break;
3118 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003119 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003122 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 break;
3124 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003125 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003126 break;
3127 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003128 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003129 break;
3130
3131 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003135 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003136 break;
3137 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003138 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003139 break;
3140 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003141 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003142 break;
3143 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003144 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003145 break;
3146 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003147 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003148 break;
3149
3150 case glslang::EOpIsNan:
3151 unaryOp = spv::OpIsNan;
3152 break;
3153 case glslang::EOpIsInf:
3154 unaryOp = spv::OpIsInf;
3155 break;
3156
Rex Xucbc426e2015-12-15 16:03:10 +08003157 case glslang::EOpFloatBitsToInt:
3158 case glslang::EOpFloatBitsToUint:
3159 case glslang::EOpIntBitsToFloat:
3160 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003161 case glslang::EOpDoubleBitsToInt64:
3162 case glslang::EOpDoubleBitsToUint64:
3163 case glslang::EOpInt64BitsToDouble:
3164 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003165 unaryOp = spv::OpBitcast;
3166 break;
3167
John Kessenich140f3df2015-06-26 16:58:36 -06003168 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003169 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003170 break;
3171 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003172 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003173 break;
3174 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003175 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003176 break;
3177 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003178 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003179 break;
3180 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003181 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003182 break;
3183 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003184 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003186 case glslang::EOpPackSnorm4x8:
3187 libCall = spv::GLSLstd450PackSnorm4x8;
3188 break;
3189 case glslang::EOpUnpackSnorm4x8:
3190 libCall = spv::GLSLstd450UnpackSnorm4x8;
3191 break;
3192 case glslang::EOpPackUnorm4x8:
3193 libCall = spv::GLSLstd450PackUnorm4x8;
3194 break;
3195 case glslang::EOpUnpackUnorm4x8:
3196 libCall = spv::GLSLstd450UnpackUnorm4x8;
3197 break;
3198 case glslang::EOpPackDouble2x32:
3199 libCall = spv::GLSLstd450PackDouble2x32;
3200 break;
3201 case glslang::EOpUnpackDouble2x32:
3202 libCall = spv::GLSLstd450UnpackDouble2x32;
3203 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003204
Rex Xu8ff43de2016-04-22 16:51:45 +08003205 case glslang::EOpPackInt2x32:
3206 case glslang::EOpUnpackInt2x32:
3207 case glslang::EOpPackUint2x32:
3208 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003209 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003210 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3211 break;
3212
John Kessenich140f3df2015-06-26 16:58:36 -06003213 case glslang::EOpDPdx:
3214 unaryOp = spv::OpDPdx;
3215 break;
3216 case glslang::EOpDPdy:
3217 unaryOp = spv::OpDPdy;
3218 break;
3219 case glslang::EOpFwidth:
3220 unaryOp = spv::OpFwidth;
3221 break;
3222 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003223 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003224 unaryOp = spv::OpDPdxFine;
3225 break;
3226 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003227 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003228 unaryOp = spv::OpDPdyFine;
3229 break;
3230 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003231 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003232 unaryOp = spv::OpFwidthFine;
3233 break;
3234 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003235 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003236 unaryOp = spv::OpDPdxCoarse;
3237 break;
3238 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003239 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003240 unaryOp = spv::OpDPdyCoarse;
3241 break;
3242 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003243 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003244 unaryOp = spv::OpFwidthCoarse;
3245 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003246 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003247 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003248 libCall = spv::GLSLstd450InterpolateAtCentroid;
3249 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003250 case glslang::EOpAny:
3251 unaryOp = spv::OpAny;
3252 break;
3253 case glslang::EOpAll:
3254 unaryOp = spv::OpAll;
3255 break;
3256
3257 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003258 if (isFloat)
3259 libCall = spv::GLSLstd450FAbs;
3260 else
3261 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003262 break;
3263 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003264 if (isFloat)
3265 libCall = spv::GLSLstd450FSign;
3266 else
3267 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003268 break;
3269
John Kessenichfc51d282015-08-19 13:34:18 -06003270 case glslang::EOpAtomicCounterIncrement:
3271 case glslang::EOpAtomicCounterDecrement:
3272 case glslang::EOpAtomicCounter:
3273 {
3274 // Handle all of the atomics in one place, in createAtomicOperation()
3275 std::vector<spv::Id> operands;
3276 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003277 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003278 }
3279
John Kessenichfc51d282015-08-19 13:34:18 -06003280 case glslang::EOpBitFieldReverse:
3281 unaryOp = spv::OpBitReverse;
3282 break;
3283 case glslang::EOpBitCount:
3284 unaryOp = spv::OpBitCount;
3285 break;
3286 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003287 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003288 break;
3289 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003290 if (isUnsigned)
3291 libCall = spv::GLSLstd450FindUMsb;
3292 else
3293 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003294 break;
3295
Rex Xu574ab042016-04-14 16:53:07 +08003296 case glslang::EOpBallot:
3297 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003298 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003299 libCall = spv::GLSLstd450Bad;
3300 break;
3301
Rex Xu338b1852016-05-05 20:38:33 +08003302 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003303 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003304 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003305 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003306
John Kessenich140f3df2015-06-26 16:58:36 -06003307 default:
3308 return 0;
3309 }
3310
3311 spv::Id id;
3312 if (libCall >= 0) {
3313 std::vector<spv::Id> args;
3314 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003315 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003316 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003317 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003318 }
John Kessenich140f3df2015-06-26 16:58:36 -06003319
qining25262b32016-05-06 17:25:16 -04003320 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003321 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003322}
3323
John Kessenich7a53f762016-01-20 11:19:27 -07003324// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003325spv::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 -07003326{
3327 // Handle unary operations vector by vector.
3328 // The result type is the same type as the original type.
3329 // The algorithm is to:
3330 // - break the matrix into vectors
3331 // - apply the operation to each vector
3332 // - make a matrix out the vector results
3333
3334 // get the types sorted out
3335 int numCols = builder.getNumColumns(operand);
3336 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003337 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3338 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003339 std::vector<spv::Id> results;
3340
3341 // do each vector op
3342 for (int c = 0; c < numCols; ++c) {
3343 std::vector<unsigned int> indexes;
3344 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003345 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3346 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3347 addDecoration(destVec, noContraction);
3348 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003349 }
3350
3351 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003352 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003353}
3354
Rex Xu73e3ce72016-04-27 18:48:17 +08003355spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003356{
3357 spv::Op convOp = spv::OpNop;
3358 spv::Id zero = 0;
3359 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003360 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003361
3362 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3363
3364 switch (op) {
3365 case glslang::EOpConvIntToBool:
3366 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003367 case glslang::EOpConvInt64ToBool:
3368 case glslang::EOpConvUint64ToBool:
3369 zero = (op == glslang::EOpConvInt64ToBool ||
3370 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003371 zero = makeSmearedConstant(zero, vectorSize);
3372 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3373
3374 case glslang::EOpConvFloatToBool:
3375 zero = builder.makeFloatConstant(0.0F);
3376 zero = makeSmearedConstant(zero, vectorSize);
3377 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3378
3379 case glslang::EOpConvDoubleToBool:
3380 zero = builder.makeDoubleConstant(0.0);
3381 zero = makeSmearedConstant(zero, vectorSize);
3382 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3383
3384 case glslang::EOpConvBoolToFloat:
3385 convOp = spv::OpSelect;
3386 zero = builder.makeFloatConstant(0.0);
3387 one = builder.makeFloatConstant(1.0);
3388 break;
3389 case glslang::EOpConvBoolToDouble:
3390 convOp = spv::OpSelect;
3391 zero = builder.makeDoubleConstant(0.0);
3392 one = builder.makeDoubleConstant(1.0);
3393 break;
3394 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003395 case glslang::EOpConvBoolToInt64:
3396 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3397 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003398 convOp = spv::OpSelect;
3399 break;
3400 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003401 case glslang::EOpConvBoolToUint64:
3402 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3403 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003404 convOp = spv::OpSelect;
3405 break;
3406
3407 case glslang::EOpConvIntToFloat:
3408 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003409 case glslang::EOpConvInt64ToFloat:
3410 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003411 convOp = spv::OpConvertSToF;
3412 break;
3413
3414 case glslang::EOpConvUintToFloat:
3415 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003416 case glslang::EOpConvUint64ToFloat:
3417 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003418 convOp = spv::OpConvertUToF;
3419 break;
3420
3421 case glslang::EOpConvDoubleToFloat:
3422 case glslang::EOpConvFloatToDouble:
3423 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003424 if (builder.isMatrixType(destType))
3425 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003426 break;
3427
3428 case glslang::EOpConvFloatToInt:
3429 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003430 case glslang::EOpConvFloatToInt64:
3431 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003432 convOp = spv::OpConvertFToS;
3433 break;
3434
3435 case glslang::EOpConvUintToInt:
3436 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003437 case glslang::EOpConvUint64ToInt64:
3438 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003439 if (builder.isInSpecConstCodeGenMode()) {
3440 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003441 zero = (op == glslang::EOpConvUintToInt64 ||
3442 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003443 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003444 // Use OpIAdd, instead of OpBitcast to do the conversion when
3445 // generating for OpSpecConstantOp instruction.
3446 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3447 }
3448 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003449 convOp = spv::OpBitcast;
3450 break;
3451
3452 case glslang::EOpConvFloatToUint:
3453 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003454 case glslang::EOpConvFloatToUint64:
3455 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003456 convOp = spv::OpConvertFToU;
3457 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003458
3459 case glslang::EOpConvIntToInt64:
3460 case glslang::EOpConvInt64ToInt:
3461 convOp = spv::OpSConvert;
3462 break;
3463
3464 case glslang::EOpConvUintToUint64:
3465 case glslang::EOpConvUint64ToUint:
3466 convOp = spv::OpUConvert;
3467 break;
3468
3469 case glslang::EOpConvIntToUint64:
3470 case glslang::EOpConvInt64ToUint:
3471 case glslang::EOpConvUint64ToInt:
3472 case glslang::EOpConvUintToInt64:
3473 // OpSConvert/OpUConvert + OpBitCast
3474 switch (op) {
3475 case glslang::EOpConvIntToUint64:
3476 convOp = spv::OpSConvert;
3477 type = builder.makeIntType(64);
3478 break;
3479 case glslang::EOpConvInt64ToUint:
3480 convOp = spv::OpSConvert;
3481 type = builder.makeIntType(32);
3482 break;
3483 case glslang::EOpConvUint64ToInt:
3484 convOp = spv::OpUConvert;
3485 type = builder.makeUintType(32);
3486 break;
3487 case glslang::EOpConvUintToInt64:
3488 convOp = spv::OpUConvert;
3489 type = builder.makeUintType(64);
3490 break;
3491 default:
3492 assert(0);
3493 break;
3494 }
3495
3496 if (vectorSize > 0)
3497 type = builder.makeVectorType(type, vectorSize);
3498
3499 operand = builder.createUnaryOp(convOp, type, operand);
3500
3501 if (builder.isInSpecConstCodeGenMode()) {
3502 // Build zero scalar or vector for OpIAdd.
3503 zero = (op == glslang::EOpConvIntToUint64 ||
3504 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3505 zero = makeSmearedConstant(zero, vectorSize);
3506 // Use OpIAdd, instead of OpBitcast to do the conversion when
3507 // generating for OpSpecConstantOp instruction.
3508 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3509 }
3510 // For normal run-time conversion instruction, use OpBitcast.
3511 convOp = spv::OpBitcast;
3512 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003513 default:
3514 break;
3515 }
3516
3517 spv::Id result = 0;
3518 if (convOp == spv::OpNop)
3519 return result;
3520
3521 if (convOp == spv::OpSelect) {
3522 zero = makeSmearedConstant(zero, vectorSize);
3523 one = makeSmearedConstant(one, vectorSize);
3524 result = builder.createTriOp(convOp, destType, operand, one, zero);
3525 } else
3526 result = builder.createUnaryOp(convOp, destType, operand);
3527
John Kessenich32cfd492016-02-02 12:37:46 -07003528 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003529}
3530
3531spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3532{
3533 if (vectorSize == 0)
3534 return constant;
3535
3536 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3537 std::vector<spv::Id> components;
3538 for (int c = 0; c < vectorSize; ++c)
3539 components.push_back(constant);
3540 return builder.makeCompositeConstant(vectorTypeId, components);
3541}
3542
John Kessenich426394d2015-07-23 10:22:48 -06003543// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003544spv::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 -06003545{
3546 spv::Op opCode = spv::OpNop;
3547
3548 switch (op) {
3549 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003550 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003551 opCode = spv::OpAtomicIAdd;
3552 break;
3553 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003554 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003555 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003556 break;
3557 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003558 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003559 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003560 break;
3561 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003562 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003563 opCode = spv::OpAtomicAnd;
3564 break;
3565 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003566 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003567 opCode = spv::OpAtomicOr;
3568 break;
3569 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003570 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003571 opCode = spv::OpAtomicXor;
3572 break;
3573 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003574 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003575 opCode = spv::OpAtomicExchange;
3576 break;
3577 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003578 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003579 opCode = spv::OpAtomicCompareExchange;
3580 break;
3581 case glslang::EOpAtomicCounterIncrement:
3582 opCode = spv::OpAtomicIIncrement;
3583 break;
3584 case glslang::EOpAtomicCounterDecrement:
3585 opCode = spv::OpAtomicIDecrement;
3586 break;
3587 case glslang::EOpAtomicCounter:
3588 opCode = spv::OpAtomicLoad;
3589 break;
3590 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003591 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003592 break;
3593 }
3594
3595 // Sort out the operands
3596 // - mapping from glslang -> SPV
3597 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003598 // - compare-exchange swaps the value and comparator
3599 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003600 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3601 auto opIt = operands.begin(); // walk the glslang operands
3602 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003603 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3604 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3605 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003606 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3607 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003608 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003609 spvAtomicOperands.push_back(*(opIt + 1));
3610 spvAtomicOperands.push_back(*opIt);
3611 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003612 }
John Kessenich426394d2015-07-23 10:22:48 -06003613
John Kessenich3e60a6f2015-09-14 22:45:16 -06003614 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003615 for (; opIt != operands.end(); ++opIt)
3616 spvAtomicOperands.push_back(*opIt);
3617
3618 return builder.createOp(opCode, typeId, spvAtomicOperands);
3619}
3620
John Kessenich91cef522016-05-05 16:45:40 -06003621// Create group invocation operations.
3622spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3623{
3624 builder.addCapability(spv::CapabilityGroups);
3625
3626 std::vector<spv::Id> operands;
3627 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3628 operands.push_back(operand);
3629
3630 switch (op) {
3631 case glslang::EOpAnyInvocation:
3632 case glslang::EOpAllInvocations:
3633 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3634
3635 case glslang::EOpAllInvocationsEqual:
3636 {
3637 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3638 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3639
3640 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3641 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3642 }
3643 default:
3644 logger->missingFunctionality("invocation operation");
3645 return spv::NoResult;
3646 }
3647}
3648
John Kessenich5e4b1242015-08-06 22:53:06 -06003649spv::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 -06003650{
Rex Xu8ff43de2016-04-22 16:51:45 +08003651 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003652 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3653
John Kessenich140f3df2015-06-26 16:58:36 -06003654 spv::Op opCode = spv::OpNop;
3655 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003656 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003657 spv::Id typeId0 = 0;
3658 if (consumedOperands > 0)
3659 typeId0 = builder.getTypeId(operands[0]);
3660 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003661
3662 switch (op) {
3663 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003664 if (isFloat)
3665 libCall = spv::GLSLstd450FMin;
3666 else if (isUnsigned)
3667 libCall = spv::GLSLstd450UMin;
3668 else
3669 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003670 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003671 break;
3672 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003673 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003674 break;
3675 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 if (isFloat)
3677 libCall = spv::GLSLstd450FMax;
3678 else if (isUnsigned)
3679 libCall = spv::GLSLstd450UMax;
3680 else
3681 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003682 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003683 break;
3684 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003685 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003686 break;
3687 case glslang::EOpDot:
3688 opCode = spv::OpDot;
3689 break;
3690 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003691 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003692 break;
3693
3694 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003695 if (isFloat)
3696 libCall = spv::GLSLstd450FClamp;
3697 else if (isUnsigned)
3698 libCall = spv::GLSLstd450UClamp;
3699 else
3700 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003701 builder.promoteScalar(precision, operands.front(), operands[1]);
3702 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003705 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3706 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003707 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003708 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003709 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003710 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003711 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003712 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003716 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
3718 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003719 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003720 builder.promoteScalar(precision, operands[0], operands[2]);
3721 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723
3724 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003731 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003732 break;
3733 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003734 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003739 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003740 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003741 libCall = spv::GLSLstd450InterpolateAtSample;
3742 break;
3743 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003744 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003745 libCall = spv::GLSLstd450InterpolateAtOffset;
3746 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003747 case glslang::EOpAddCarry:
3748 opCode = spv::OpIAddCarry;
3749 typeId = builder.makeStructResultType(typeId0, typeId0);
3750 consumedOperands = 2;
3751 break;
3752 case glslang::EOpSubBorrow:
3753 opCode = spv::OpISubBorrow;
3754 typeId = builder.makeStructResultType(typeId0, typeId0);
3755 consumedOperands = 2;
3756 break;
3757 case glslang::EOpUMulExtended:
3758 opCode = spv::OpUMulExtended;
3759 typeId = builder.makeStructResultType(typeId0, typeId0);
3760 consumedOperands = 2;
3761 break;
3762 case glslang::EOpIMulExtended:
3763 opCode = spv::OpSMulExtended;
3764 typeId = builder.makeStructResultType(typeId0, typeId0);
3765 consumedOperands = 2;
3766 break;
3767 case glslang::EOpBitfieldExtract:
3768 if (isUnsigned)
3769 opCode = spv::OpBitFieldUExtract;
3770 else
3771 opCode = spv::OpBitFieldSExtract;
3772 break;
3773 case glslang::EOpBitfieldInsert:
3774 opCode = spv::OpBitFieldInsert;
3775 break;
3776
3777 case glslang::EOpFma:
3778 libCall = spv::GLSLstd450Fma;
3779 break;
3780 case glslang::EOpFrexp:
3781 libCall = spv::GLSLstd450FrexpStruct;
3782 if (builder.getNumComponents(operands[0]) == 1)
3783 frexpIntType = builder.makeIntegerType(32, true);
3784 else
3785 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3786 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3787 consumedOperands = 1;
3788 break;
3789 case glslang::EOpLdexp:
3790 libCall = spv::GLSLstd450Ldexp;
3791 break;
3792
Rex Xu574ab042016-04-14 16:53:07 +08003793 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003794 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003795 libCall = spv::GLSLstd450Bad;
3796 break;
3797
John Kessenich140f3df2015-06-26 16:58:36 -06003798 default:
3799 return 0;
3800 }
3801
3802 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003803 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003804 // Use an extended instruction from the standard library.
3805 // Construct the call arguments, without modifying the original operands vector.
3806 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3807 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003808 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003809 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003810 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003811 case 0:
3812 // should all be handled by visitAggregate and createNoArgOperation
3813 assert(0);
3814 return 0;
3815 case 1:
3816 // should all be handled by createUnaryOperation
3817 assert(0);
3818 return 0;
3819 case 2:
3820 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3821 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003822 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003823 // anything 3 or over doesn't have l-value operands, so all should be consumed
3824 assert(consumedOperands == operands.size());
3825 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003826 break;
3827 }
3828 }
3829
John Kessenich55e7d112015-11-15 21:33:39 -07003830 // Decode the return types that were structures
3831 switch (op) {
3832 case glslang::EOpAddCarry:
3833 case glslang::EOpSubBorrow:
3834 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3835 id = builder.createCompositeExtract(id, typeId0, 0);
3836 break;
3837 case glslang::EOpUMulExtended:
3838 case glslang::EOpIMulExtended:
3839 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3840 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3841 break;
3842 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003843 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003844 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3845 id = builder.createCompositeExtract(id, typeId0, 0);
3846 break;
3847 default:
3848 break;
3849 }
3850
John Kessenich32cfd492016-02-02 12:37:46 -07003851 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003852}
3853
3854// Intrinsics with no arguments, no return value, and no precision.
3855spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3856{
3857 // TODO: get the barrier operands correct
3858
3859 switch (op) {
3860 case glslang::EOpEmitVertex:
3861 builder.createNoResultOp(spv::OpEmitVertex);
3862 return 0;
3863 case glslang::EOpEndPrimitive:
3864 builder.createNoResultOp(spv::OpEndPrimitive);
3865 return 0;
3866 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003867 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3868 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003869 return 0;
3870 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003871 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003872 return 0;
3873 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003874 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003875 return 0;
3876 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003877 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003878 return 0;
3879 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003881 return 0;
3882 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003883 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003884 return 0;
3885 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003886 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003887 return 0;
3888 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003889 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003890 return 0;
3891 }
3892}
3893
3894spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3895{
John Kessenich2f273362015-07-18 22:34:27 -06003896 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003897 spv::Id id;
3898 if (symbolValues.end() != iter) {
3899 id = iter->second;
3900 return id;
3901 }
3902
3903 // it was not found, create it
3904 id = createSpvVariable(symbol);
3905 symbolValues[symbol->getId()] = id;
3906
3907 if (! symbol->getType().isStruct()) {
3908 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003909 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003910 if (symbol->getType().getQualifier().hasSpecConstantId())
3911 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003912 if (symbol->getQualifier().hasLocation())
3913 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3914 if (symbol->getQualifier().hasIndex())
3915 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3916 if (symbol->getQualifier().hasComponent())
3917 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3918 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003919 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003920 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003921 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003922 if (symbol->getQualifier().hasXfbBuffer())
3923 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3924 if (symbol->getQualifier().hasXfbOffset())
3925 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3926 }
3927 }
3928
John Kesseniche0b6cad2015-12-24 10:30:13 -07003929 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003930 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003931 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003932 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003933 }
John Kessenich140f3df2015-06-26 16:58:36 -06003934 if (symbol->getQualifier().hasSet())
3935 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003936 else if (IsDescriptorResource(symbol->getType())) {
3937 // default to 0
3938 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3939 }
John Kessenich140f3df2015-06-26 16:58:36 -06003940 if (symbol->getQualifier().hasBinding())
3941 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003942 if (symbol->getQualifier().hasAttachment())
3943 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003944 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003945 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003946 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003947 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003948 if (symbol->getQualifier().hasXfbBuffer())
3949 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3950 }
3951
Rex Xu1da878f2016-02-21 20:59:01 +08003952 if (symbol->getType().isImage()) {
3953 std::vector<spv::Decoration> memory;
3954 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3955 for (unsigned int i = 0; i < memory.size(); ++i)
3956 addDecoration(id, memory[i]);
3957 }
3958
John Kessenich140f3df2015-06-26 16:58:36 -06003959 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06003960 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06003961 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003962 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003963
John Kessenich140f3df2015-06-26 16:58:36 -06003964 return id;
3965}
3966
John Kessenich55e7d112015-11-15 21:33:39 -07003967// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003968void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3969{
3970 if (dec != spv::BadValue)
3971 builder.addDecoration(id, dec);
3972}
3973
John Kessenich55e7d112015-11-15 21:33:39 -07003974// If 'dec' is valid, add a one-operand decoration to an object
3975void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3976{
3977 if (dec != spv::BadValue)
3978 builder.addDecoration(id, dec, value);
3979}
3980
3981// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003982void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3983{
3984 if (dec != spv::BadValue)
3985 builder.addMemberDecoration(id, (unsigned)member, dec);
3986}
3987
John Kessenich92187592016-02-01 13:45:25 -07003988// If 'dec' is valid, add a one-operand decoration to a struct member
3989void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3990{
3991 if (dec != spv::BadValue)
3992 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3993}
3994
John Kessenich55e7d112015-11-15 21:33:39 -07003995// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003996// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003997//
3998// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3999//
4000// Recursively walk the nodes. The nodes form a tree whose leaves are
4001// regular constants, which themselves are trees that createSpvConstant()
4002// recursively walks. So, this function walks the "top" of the tree:
4003// - emit specialization constant-building instructions for specConstant
4004// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004005spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004006{
John Kessenich7cc0e282016-03-20 00:46:02 -06004007 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004008
qining4f4bb812016-04-03 23:55:17 -04004009 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004010 if (! node.getQualifier().specConstant) {
4011 // hand off to the non-spec-constant path
4012 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4013 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004014 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004015 nextConst, false);
4016 }
4017
4018 // We now know we have a specialization constant to build
4019
qining4f4bb812016-04-03 23:55:17 -04004020 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
4021 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4022 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4023 std::vector<spv::Id> dimConstId;
4024 for (int dim = 0; dim < 3; ++dim) {
4025 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4026 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4027 if (specConst)
4028 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4029 }
4030 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4031 }
4032
4033 // An AST node labelled as specialization constant should be a symbol node.
4034 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4035 if (auto* sn = node.getAsSymbolNode()) {
4036 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004037 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4038 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4039 // will set the builder into spec constant op instruction generating mode.
4040 sub_tree->traverse(this);
4041 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004042 } else if (auto* const_union_array = &sn->getConstArray()){
4043 int nextConst = 0;
4044 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004045 }
4046 }
qining4f4bb812016-04-03 23:55:17 -04004047
4048 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4049 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004050 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004051 exit(1);
4052 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004053}
4054
John Kessenich140f3df2015-06-26 16:58:36 -06004055// Use 'consts' as the flattened glslang source of scalar constants to recursively
4056// build the aggregate SPIR-V constant.
4057//
4058// If there are not enough elements present in 'consts', 0 will be substituted;
4059// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4060//
qining08408382016-03-21 09:51:37 -04004061spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004062{
4063 // vector of constants for SPIR-V
4064 std::vector<spv::Id> spvConsts;
4065
4066 // Type is used for struct and array constants
4067 spv::Id typeId = convertGlslangToSpvType(glslangType);
4068
4069 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004070 glslang::TType elementType(glslangType, 0);
4071 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004072 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004073 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004074 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004075 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004076 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004077 } else if (glslangType.getStruct()) {
4078 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4079 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004080 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004081 } else if (glslangType.isVector()) {
4082 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4083 bool zero = nextConst >= consts.size();
4084 switch (glslangType.getBasicType()) {
4085 case glslang::EbtInt:
4086 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4087 break;
4088 case glslang::EbtUint:
4089 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4090 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004091 case glslang::EbtInt64:
4092 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4093 break;
4094 case glslang::EbtUint64:
4095 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4096 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004097 case glslang::EbtFloat:
4098 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4099 break;
4100 case glslang::EbtDouble:
4101 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4102 break;
4103 case glslang::EbtBool:
4104 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4105 break;
4106 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004107 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109 }
4110 ++nextConst;
4111 }
4112 } else {
4113 // we have a non-aggregate (scalar) constant
4114 bool zero = nextConst >= consts.size();
4115 spv::Id scalar = 0;
4116 switch (glslangType.getBasicType()) {
4117 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004118 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
4120 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004121 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004122 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004123 case glslang::EbtInt64:
4124 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4125 break;
4126 case glslang::EbtUint64:
4127 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4128 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004129 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004130 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004131 break;
4132 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004133 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004134 break;
4135 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004136 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004137 break;
4138 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004139 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 }
4142 ++nextConst;
4143 return scalar;
4144 }
4145
4146 return builder.makeCompositeConstant(typeId, spvConsts);
4147}
4148
John Kessenich7c1aa102015-10-15 13:29:11 -06004149// Return true if the node is a constant or symbol whose reading has no
4150// non-trivial observable cost or effect.
4151bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4152{
4153 // don't know what this is
4154 if (node == nullptr)
4155 return false;
4156
4157 // a constant is safe
4158 if (node->getAsConstantUnion() != nullptr)
4159 return true;
4160
4161 // not a symbol means non-trivial
4162 if (node->getAsSymbolNode() == nullptr)
4163 return false;
4164
4165 // a symbol, depends on what's being read
4166 switch (node->getType().getQualifier().storage) {
4167 case glslang::EvqTemporary:
4168 case glslang::EvqGlobal:
4169 case glslang::EvqIn:
4170 case glslang::EvqInOut:
4171 case glslang::EvqConst:
4172 case glslang::EvqConstReadOnly:
4173 case glslang::EvqUniform:
4174 return true;
4175 default:
4176 return false;
4177 }
qining25262b32016-05-06 17:25:16 -04004178}
John Kessenich7c1aa102015-10-15 13:29:11 -06004179
4180// A node is trivial if it is a single operation with no side effects.
4181// Error on the side of saying non-trivial.
4182// Return true if trivial.
4183bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4184{
4185 if (node == nullptr)
4186 return false;
4187
4188 // symbols and constants are trivial
4189 if (isTrivialLeaf(node))
4190 return true;
4191
4192 // otherwise, it needs to be a simple operation or one or two leaf nodes
4193
4194 // not a simple operation
4195 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4196 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4197 if (binaryNode == nullptr && unaryNode == nullptr)
4198 return false;
4199
4200 // not on leaf nodes
4201 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4202 return false;
4203
4204 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4205 return false;
4206 }
4207
4208 switch (node->getAsOperator()->getOp()) {
4209 case glslang::EOpLogicalNot:
4210 case glslang::EOpConvIntToBool:
4211 case glslang::EOpConvUintToBool:
4212 case glslang::EOpConvFloatToBool:
4213 case glslang::EOpConvDoubleToBool:
4214 case glslang::EOpEqual:
4215 case glslang::EOpNotEqual:
4216 case glslang::EOpLessThan:
4217 case glslang::EOpGreaterThan:
4218 case glslang::EOpLessThanEqual:
4219 case glslang::EOpGreaterThanEqual:
4220 case glslang::EOpIndexDirect:
4221 case glslang::EOpIndexDirectStruct:
4222 case glslang::EOpLogicalXor:
4223 case glslang::EOpAny:
4224 case glslang::EOpAll:
4225 return true;
4226 default:
4227 return false;
4228 }
4229}
4230
4231// Emit short-circuiting code, where 'right' is never evaluated unless
4232// the left side is true (for &&) or false (for ||).
4233spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4234{
4235 spv::Id boolTypeId = builder.makeBoolType();
4236
4237 // emit left operand
4238 builder.clearAccessChain();
4239 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004240 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004241
4242 // Operands to accumulate OpPhi operands
4243 std::vector<spv::Id> phiOperands;
4244 // accumulate left operand's phi information
4245 phiOperands.push_back(leftId);
4246 phiOperands.push_back(builder.getBuildPoint()->getId());
4247
4248 // Make the two kinds of operation symmetric with a "!"
4249 // || => emit "if (! left) result = right"
4250 // && => emit "if ( left) result = right"
4251 //
4252 // TODO: this runtime "not" for || could be avoided by adding functionality
4253 // to 'builder' to have an "else" without an "then"
4254 if (op == glslang::EOpLogicalOr)
4255 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4256
4257 // make an "if" based on the left value
4258 spv::Builder::If ifBuilder(leftId, builder);
4259
4260 // emit right operand as the "then" part of the "if"
4261 builder.clearAccessChain();
4262 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004263 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004264
4265 // accumulate left operand's phi information
4266 phiOperands.push_back(rightId);
4267 phiOperands.push_back(builder.getBuildPoint()->getId());
4268
4269 // finish the "if"
4270 ifBuilder.makeEndIf();
4271
4272 // phi together the two results
4273 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4274}
4275
John Kessenich140f3df2015-06-26 16:58:36 -06004276}; // end anonymous namespace
4277
4278namespace glslang {
4279
John Kessenich68d78fd2015-07-12 19:28:10 -06004280void GetSpirvVersion(std::string& version)
4281{
John Kessenich9e55f632015-07-15 10:03:39 -06004282 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004283 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004284 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004285 version = buf;
4286}
4287
John Kessenich140f3df2015-06-26 16:58:36 -06004288// Write SPIR-V out to a binary file
4289void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4290{
4291 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004292 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004293 for (int i = 0; i < (int)spirv.size(); ++i) {
4294 unsigned int word = spirv[i];
4295 out.write((const char*)&word, 4);
4296 }
4297 out.close();
4298}
4299
4300//
4301// Set up the glslang traversal
4302//
4303void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4304{
Lei Zhang17535f72016-05-04 15:55:59 -04004305 spv::SpvBuildLogger logger;
4306 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004307}
4308
Lei Zhang17535f72016-05-04 15:55:59 -04004309void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004310{
John Kessenich140f3df2015-06-26 16:58:36 -06004311 TIntermNode* root = intermediate.getTreeRoot();
4312
4313 if (root == 0)
4314 return;
4315
4316 glslang::GetThreadPoolAllocator().push();
4317
Lei Zhang17535f72016-05-04 15:55:59 -04004318 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004319
4320 root->traverse(&it);
4321
4322 it.dumpSpv(spirv);
4323
4324 glslang::GetThreadPoolAllocator().pop();
4325}
4326
4327}; // end namespace glslang