blob: 0efccf46290e4e162918abbc86296ad2c852391c [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));
scygan8add1512016-05-06 16:54:54 +02001893 // Add interpolation decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001894 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
scygan8add1512016-05-06 16:54:54 +02001895 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1896 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001897 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001898
Rex Xu1da878f2016-02-21 20:59:01 +08001899 if (qualifier.storage == glslang::EvqBuffer) {
1900 std::vector<spv::Decoration> memory;
1901 TranslateMemoryDecoration(subQualifier, memory);
1902 for (unsigned int i = 0; i < memory.size(); ++i)
1903 addMemberDecoration(spvType, member, memory[i]);
1904 }
1905
John Kessenich09677482016-02-19 12:21:50 -07001906 // compute location decoration; tricky based on whether inheritance is at play
1907 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1908 // probably move to the linker stage of the front end proper, and just have the
1909 // answer sitting already distributed throughout the individual member locations.
1910 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001911 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001912 // struct members should not have explicit locations
1913 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001914 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001915 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001916 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1917 // The members, and their nested types, must not themselves have Location decorations.
1918 }
John Kessenich09677482016-02-19 12:21:50 -07001919 else if (qualifier.hasLocation()) // inheritance
1920 location = qualifier.layoutLocation + locationOffset;
1921 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001922 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001923 if (location >= 0)
1924 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1925
1926 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001927 if (glslangType.getQualifier().hasComponent())
1928 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1929 if (glslangType.getQualifier().hasXfbOffset())
1930 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001931 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001932 // figure out what to do with offset, which is accumulating
1933 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001934 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001935 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001936 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001937 offset = nextOffset;
1938 }
John Kessenich140f3df2015-06-26 16:58:36 -06001939
John Kessenichf85e8062015-12-19 13:57:10 -07001940 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001941 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001942
John Kessenich140f3df2015-06-26 16:58:36 -06001943 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001944 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001945 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001946 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001947 }
1948 }
1949
1950 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001951 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001952 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001953 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001954 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001955 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001956 }
John Kessenich140f3df2015-06-26 16:58:36 -06001957 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001958 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001959 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001960 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001961 if (type.getQualifier().hasXfbBuffer())
1962 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1963 }
1964 }
1965 break;
1966 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001967 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001968 break;
1969 }
1970
1971 if (type.isMatrix())
1972 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1973 else {
1974 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1975 if (type.getVectorSize() > 1)
1976 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1977 }
1978
1979 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001980 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1981
John Kessenichc9a80832015-09-12 12:17:44 -06001982 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001983 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001984 // We need to decorate array strides for types needing explicit layout, except blocks.
1985 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001986 // Use a dummy glslang type for querying internal strides of
1987 // arrays of arrays, but using just a one-dimensional array.
1988 glslang::TType simpleArrayType(type, 0); // deference type of the array
1989 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1990 simpleArrayType.getArraySizes().dereference();
1991
1992 // Will compute the higher-order strides here, rather than making a whole
1993 // pile of types and doing repetitive recursion on their contents.
1994 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1995 }
John Kessenichf8842e52016-01-04 19:22:56 -07001996
1997 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001998 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001999 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002000 if (stride > 0)
2001 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002002 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002003 }
2004 } else {
2005 // single-dimensional array, and don't yet have stride
2006
John Kessenichf8842e52016-01-04 19:22:56 -07002007 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002008 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2009 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002010 }
John Kessenich31ed4832015-09-09 17:51:38 -06002011
John Kessenichc9a80832015-09-12 12:17:44 -06002012 // Do the outer dimension, which might not be known for a runtime-sized array
2013 if (type.isRuntimeSizedArray()) {
2014 spvType = builder.makeRuntimeArray(spvType);
2015 } else {
2016 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002017 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002018 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002019 if (stride > 0)
2020 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002021 }
2022
2023 return spvType;
2024}
2025
John Kessenich6c292d32016-02-15 20:58:50 -07002026// Turn the expression forming the array size into an id.
2027// This is not quite trivial, because of specialization constants.
2028// Sometimes, a raw constant is turned into an Id, and sometimes
2029// a specialization constant expression is.
2030spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2031{
2032 // First, see if this is sized with a node, meaning a specialization constant:
2033 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2034 if (specNode != nullptr) {
2035 builder.clearAccessChain();
2036 specNode->traverse(this);
2037 return accessChainLoad(specNode->getAsTyped()->getType());
2038 }
qining25262b32016-05-06 17:25:16 -04002039
John Kessenich6c292d32016-02-15 20:58:50 -07002040 // Otherwise, need a compile-time (front end) size, get it:
2041 int size = arraySizes.getDimSize(dim);
2042 assert(size > 0);
2043 return builder.makeUintConstant(size);
2044}
2045
John Kessenich103bef92016-02-08 21:38:15 -07002046// Wrap the builder's accessChainLoad to:
2047// - localize handling of RelaxedPrecision
2048// - use the SPIR-V inferred type instead of another conversion of the glslang type
2049// (avoids unnecessary work and possible type punning for structures)
2050// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002051spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2052{
John Kessenich103bef92016-02-08 21:38:15 -07002053 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2054 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2055
2056 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002057 if (type.getBasicType() == glslang::EbtBool) {
2058 if (builder.isScalarType(nominalTypeId)) {
2059 // Conversion for bool
2060 spv::Id boolType = builder.makeBoolType();
2061 if (nominalTypeId != boolType)
2062 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2063 } else if (builder.isVectorType(nominalTypeId)) {
2064 // Conversion for bvec
2065 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2066 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2067 if (nominalTypeId != bvecType)
2068 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2069 }
2070 }
John Kessenich103bef92016-02-08 21:38:15 -07002071
2072 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002073}
2074
Rex Xu27253232016-02-23 17:51:09 +08002075// Wrap the builder's accessChainStore to:
2076// - do conversion of concrete to abstract type
2077void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2078{
2079 // Need to convert to abstract types when necessary
2080 if (type.getBasicType() == glslang::EbtBool) {
2081 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2082
2083 if (builder.isScalarType(nominalTypeId)) {
2084 // Conversion for bool
2085 spv::Id boolType = builder.makeBoolType();
2086 if (nominalTypeId != boolType) {
2087 spv::Id zero = builder.makeUintConstant(0);
2088 spv::Id one = builder.makeUintConstant(1);
2089 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2090 }
2091 } else if (builder.isVectorType(nominalTypeId)) {
2092 // Conversion for bvec
2093 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2094 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2095 if (nominalTypeId != bvecType) {
2096 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2097 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2098 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2099 }
2100 }
2101 }
2102
2103 builder.accessChainStore(rvalue);
2104}
2105
John Kessenichf85e8062015-12-19 13:57:10 -07002106// Decide whether or not this type should be
2107// decorated with offsets and strides, and if so
2108// whether std140 or std430 rules should be applied.
2109glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002110{
John Kessenichf85e8062015-12-19 13:57:10 -07002111 // has to be a block
2112 if (type.getBasicType() != glslang::EbtBlock)
2113 return glslang::ElpNone;
2114
2115 // has to be a uniform or buffer block
2116 if (type.getQualifier().storage != glslang::EvqUniform &&
2117 type.getQualifier().storage != glslang::EvqBuffer)
2118 return glslang::ElpNone;
2119
2120 // return the layout to use
2121 switch (type.getQualifier().layoutPacking) {
2122 case glslang::ElpStd140:
2123 case glslang::ElpStd430:
2124 return type.getQualifier().layoutPacking;
2125 default:
2126 return glslang::ElpNone;
2127 }
John Kessenich31ed4832015-09-09 17:51:38 -06002128}
2129
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002130// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002131int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002132{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002133 int size;
John Kessenich49987892015-12-29 17:11:44 -07002134 int stride;
2135 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002136
2137 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002138}
2139
John Kessenich49987892015-12-29 17:11:44 -07002140// 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 -07002141// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002142int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002143{
John Kessenich49987892015-12-29 17:11:44 -07002144 glslang::TType elementType;
2145 elementType.shallowCopy(matrixType);
2146 elementType.clearArraySizes();
2147
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002148 int size;
John Kessenich49987892015-12-29 17:11:44 -07002149 int stride;
2150 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2151
2152 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002153}
2154
John Kessenich5e4b1242015-08-06 22:53:06 -06002155// Given a member type of a struct, realign the current offset for it, and compute
2156// the next (not yet aligned) offset for the next member, which will get aligned
2157// on the next call.
2158// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2159// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2160// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002161void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002162 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002163{
2164 // this will get a positive value when deemed necessary
2165 nextOffset = -1;
2166
John Kessenich5e4b1242015-08-06 22:53:06 -06002167 // override anything in currentOffset with user-set offset
2168 if (memberType.getQualifier().hasOffset())
2169 currentOffset = memberType.getQualifier().layoutOffset;
2170
2171 // It could be that current linker usage in glslang updated all the layoutOffset,
2172 // in which case the following code does not matter. But, that's not quite right
2173 // once cross-compilation unit GLSL validation is done, as the original user
2174 // settings are needed in layoutOffset, and then the following will come into play.
2175
John Kessenichf85e8062015-12-19 13:57:10 -07002176 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002177 if (! memberType.getQualifier().hasOffset())
2178 currentOffset = -1;
2179
2180 return;
2181 }
2182
John Kessenichf85e8062015-12-19 13:57:10 -07002183 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002184 if (currentOffset < 0)
2185 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002186
John Kessenich5e4b1242015-08-06 22:53:06 -06002187 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2188 // but possibly not yet correctly aligned.
2189
2190 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002191 int dummyStride;
2192 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002193 glslang::RoundToPow2(currentOffset, memberAlignment);
2194 nextOffset = currentOffset + memberSize;
2195}
2196
John Kessenichebb50532016-05-16 19:22:05 -06002197void TGlslangToSpvTraverser::declareClipCullCapability(const glslang::TTypeList& members, int member)
2198{
2199 if (members[member].type->getQualifier().builtIn == glslang::EbvClipDistance)
2200 builder.addCapability(spv::CapabilityClipDistance);
2201 if (members[member].type->getQualifier().builtIn == glslang::EbvCullDistance)
2202 builder.addCapability(spv::CapabilityCullDistance);
2203}
2204
John Kessenich140f3df2015-06-26 16:58:36 -06002205bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2206{
John Kessenich4d65ee32016-03-12 18:17:47 -07002207 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002208 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002209 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002210}
2211
2212// Make all the functions, skeletally, without actually visiting their bodies.
2213void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2214{
2215 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2216 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2217 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2218 continue;
2219
2220 // We're on a user function. Set up the basic interface for the function now,
2221 // so that it's available to call.
2222 // Translating the body will happen later.
2223 //
qining25262b32016-05-06 17:25:16 -04002224 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002225 // function. What it is an address of varies:
2226 //
2227 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2228 // so that write needs to be to a copy, hence the address of a copy works.
2229 //
2230 // - "const in" parameters can just be the r-value, as no writes need occur.
2231 //
2232 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2233 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2234
2235 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002236 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002237 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2238
2239 for (int p = 0; p < (int)parameters.size(); ++p) {
2240 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2241 spv::Id typeId = convertGlslangToSpvType(paramType);
2242 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2243 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2244 else
2245 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002246 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002247 paramTypes.push_back(typeId);
2248 }
2249
2250 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002251 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2252 convertGlslangToSpvType(glslFunction->getType()),
2253 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002254
2255 // Track function to emit/call later
2256 functionMap[glslFunction->getName().c_str()] = function;
2257
2258 // Set the parameter id's
2259 for (int p = 0; p < (int)parameters.size(); ++p) {
2260 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2261 // give a name too
2262 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2263 }
2264 }
2265}
2266
2267// Process all the initializers, while skipping the functions and link objects
2268void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2269{
2270 builder.setBuildPoint(shaderEntry->getLastBlock());
2271 for (int i = 0; i < (int)initializers.size(); ++i) {
2272 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2273 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2274
2275 // We're on a top-level node that's not a function. Treat as an initializer, whose
2276 // code goes into the beginning of main.
2277 initializer->traverse(this);
2278 }
2279 }
2280}
2281
2282// Process all the functions, while skipping initializers.
2283void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2284{
2285 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2286 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2287 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2288 node->traverse(this);
2289 }
2290}
2291
2292void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2293{
qining25262b32016-05-06 17:25:16 -04002294 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002295 // that called makeFunctions().
2296 spv::Function* function = functionMap[node->getName().c_str()];
2297 spv::Block* functionBlock = function->getEntryBlock();
2298 builder.setBuildPoint(functionBlock);
2299}
2300
Rex Xu04db3f52015-09-16 11:44:02 +08002301void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002302{
Rex Xufc618912015-09-09 16:42:49 +08002303 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002304
2305 glslang::TSampler sampler = {};
2306 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002307 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002308 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2309 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2310 }
2311
John Kessenich140f3df2015-06-26 16:58:36 -06002312 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2313 builder.clearAccessChain();
2314 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002315
2316 // Special case l-value operands
2317 bool lvalue = false;
2318 switch (node.getOp()) {
2319 case glslang::EOpImageAtomicAdd:
2320 case glslang::EOpImageAtomicMin:
2321 case glslang::EOpImageAtomicMax:
2322 case glslang::EOpImageAtomicAnd:
2323 case glslang::EOpImageAtomicOr:
2324 case glslang::EOpImageAtomicXor:
2325 case glslang::EOpImageAtomicExchange:
2326 case glslang::EOpImageAtomicCompSwap:
2327 if (i == 0)
2328 lvalue = true;
2329 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002330 case glslang::EOpSparseImageLoad:
2331 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2332 lvalue = true;
2333 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002334 case glslang::EOpSparseTexture:
2335 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2336 lvalue = true;
2337 break;
2338 case glslang::EOpSparseTextureClamp:
2339 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2340 lvalue = true;
2341 break;
2342 case glslang::EOpSparseTextureLod:
2343 case glslang::EOpSparseTextureOffset:
2344 if (i == 3)
2345 lvalue = true;
2346 break;
2347 case glslang::EOpSparseTextureFetch:
2348 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2349 lvalue = true;
2350 break;
2351 case glslang::EOpSparseTextureFetchOffset:
2352 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2353 lvalue = true;
2354 break;
2355 case glslang::EOpSparseTextureLodOffset:
2356 case glslang::EOpSparseTextureGrad:
2357 case glslang::EOpSparseTextureOffsetClamp:
2358 if (i == 4)
2359 lvalue = true;
2360 break;
2361 case glslang::EOpSparseTextureGradOffset:
2362 case glslang::EOpSparseTextureGradClamp:
2363 if (i == 5)
2364 lvalue = true;
2365 break;
2366 case glslang::EOpSparseTextureGradOffsetClamp:
2367 if (i == 6)
2368 lvalue = true;
2369 break;
2370 case glslang::EOpSparseTextureGather:
2371 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2372 lvalue = true;
2373 break;
2374 case glslang::EOpSparseTextureGatherOffset:
2375 case glslang::EOpSparseTextureGatherOffsets:
2376 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2377 lvalue = true;
2378 break;
Rex Xufc618912015-09-09 16:42:49 +08002379 default:
2380 break;
2381 }
2382
Rex Xu6b86d492015-09-16 17:48:22 +08002383 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002384 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002385 else
John Kessenich32cfd492016-02-02 12:37:46 -07002386 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002387 }
2388}
2389
John Kessenichfc51d282015-08-19 13:34:18 -06002390void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002391{
John Kessenichfc51d282015-08-19 13:34:18 -06002392 builder.clearAccessChain();
2393 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002394 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002395}
John Kessenich140f3df2015-06-26 16:58:36 -06002396
John Kessenichfc51d282015-08-19 13:34:18 -06002397spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2398{
Rex Xufc618912015-09-09 16:42:49 +08002399 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002400 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002401 }
2402
John Kessenichfc51d282015-08-19 13:34:18 -06002403 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002404 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2405 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2406 std::vector<spv::Id> arguments;
2407 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002408 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002409 else
2410 translateArguments(*node->getAsUnaryNode(), arguments);
2411 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2412
2413 spv::Builder::TextureParameters params = { };
2414 params.sampler = arguments[0];
2415
Rex Xu04db3f52015-09-16 11:44:02 +08002416 glslang::TCrackedTextureOp cracked;
2417 node->crackTexture(sampler, cracked);
2418
John Kessenichfc51d282015-08-19 13:34:18 -06002419 // Check for queries
2420 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002421 // a sampled image needs to have the image extracted first
2422 if (builder.isSampledImage(params.sampler))
2423 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002424 switch (node->getOp()) {
2425 case glslang::EOpImageQuerySize:
2426 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002427 if (arguments.size() > 1) {
2428 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002429 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002430 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002431 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002432 case glslang::EOpImageQuerySamples:
2433 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002434 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002435 case glslang::EOpTextureQueryLod:
2436 params.coords = arguments[1];
2437 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2438 case glslang::EOpTextureQueryLevels:
2439 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002440 case glslang::EOpSparseTexelsResident:
2441 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002442 default:
2443 assert(0);
2444 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002445 }
John Kessenich140f3df2015-06-26 16:58:36 -06002446 }
2447
Rex Xufc618912015-09-09 16:42:49 +08002448 // Check for image functions other than queries
2449 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002450 std::vector<spv::Id> operands;
2451 auto opIt = arguments.begin();
2452 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002453
2454 // Handle subpass operations
2455 // TODO: GLSL should change to have the "MS" only on the type rather than the
2456 // built-in function.
2457 if (cracked.subpass) {
2458 // add on the (0,0) coordinate
2459 spv::Id zero = builder.makeIntConstant(0);
2460 std::vector<spv::Id> comps;
2461 comps.push_back(zero);
2462 comps.push_back(zero);
2463 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2464 if (sampler.ms) {
2465 operands.push_back(spv::ImageOperandsSampleMask);
2466 operands.push_back(*(opIt++));
2467 }
2468 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2469 }
2470
John Kessenich56bab042015-09-16 10:54:31 -06002471 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002472 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002473 if (sampler.ms) {
2474 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002475 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002476 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002477 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2478 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002479 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002480 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002481 if (sampler.ms) {
2482 operands.push_back(*(opIt + 1));
2483 operands.push_back(spv::ImageOperandsSampleMask);
2484 operands.push_back(*opIt);
2485 } else
2486 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002487 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002488 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2489 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002490 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002491 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2492 builder.addCapability(spv::CapabilitySparseResidency);
2493 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2494 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2495
2496 if (sampler.ms) {
2497 operands.push_back(spv::ImageOperandsSampleMask);
2498 operands.push_back(*opIt++);
2499 }
2500
2501 // Create the return type that was a special structure
2502 spv::Id texelOut = *opIt;
2503 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2504 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2505 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2506
2507 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2508
2509 // Decode the return type
2510 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2511 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002512 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002513 // Process image atomic operations
2514
2515 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2516 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002517 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002518
Rex Xufc618912015-09-09 16:42:49 +08002519 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002520 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002521
2522 std::vector<spv::Id> operands;
2523 operands.push_back(pointer);
2524 for (; opIt != arguments.end(); ++opIt)
2525 operands.push_back(*opIt);
2526
Rex Xu04db3f52015-09-16 11:44:02 +08002527 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002528 }
2529 }
2530
2531 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002532 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002533 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2534
John Kessenichfc51d282015-08-19 13:34:18 -06002535 // check for bias argument
2536 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002537 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002538 int nonBiasArgCount = 2;
2539 if (cracked.offset)
2540 ++nonBiasArgCount;
2541 if (cracked.grad)
2542 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002543 if (cracked.lodClamp)
2544 ++nonBiasArgCount;
2545 if (sparse)
2546 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002547
2548 if ((int)arguments.size() > nonBiasArgCount)
2549 bias = true;
2550 }
2551
John Kessenichfc51d282015-08-19 13:34:18 -06002552 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002553
John Kessenichfc51d282015-08-19 13:34:18 -06002554 params.coords = arguments[1];
2555 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002556 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002557
2558 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002559 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002560 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002561 ++extraArgs;
2562 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002563 params.Dref = arguments[2];
2564 ++extraArgs;
2565 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002566 std::vector<spv::Id> indexes;
2567 int comp;
2568 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002569 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002570 else
2571 comp = builder.getNumComponents(params.coords) - 1;
2572 indexes.push_back(comp);
2573 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2574 }
2575 if (cracked.lod) {
2576 params.lod = arguments[2];
2577 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002578 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2579 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2580 noImplicitLod = true;
2581 }
2582 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002583 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002584 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002585 }
2586 if (cracked.grad) {
2587 params.gradX = arguments[2 + extraArgs];
2588 params.gradY = arguments[3 + extraArgs];
2589 extraArgs += 2;
2590 }
John Kessenich55e7d112015-11-15 21:33:39 -07002591 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002592 params.offset = arguments[2 + extraArgs];
2593 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002594 } else if (cracked.offsets) {
2595 params.offsets = arguments[2 + extraArgs];
2596 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002597 }
Rex Xu48edadf2015-12-31 16:11:41 +08002598 if (cracked.lodClamp) {
2599 params.lodClamp = arguments[2 + extraArgs];
2600 ++extraArgs;
2601 }
2602 if (sparse) {
2603 params.texelOut = arguments[2 + extraArgs];
2604 ++extraArgs;
2605 }
John Kessenichfc51d282015-08-19 13:34:18 -06002606 if (bias) {
2607 params.bias = arguments[2 + extraArgs];
2608 ++extraArgs;
2609 }
John Kessenich55e7d112015-11-15 21:33:39 -07002610 if (cracked.gather && ! sampler.shadow) {
2611 // default component is 0, if missing, otherwise an argument
2612 if (2 + extraArgs < (int)arguments.size()) {
2613 params.comp = arguments[2 + extraArgs];
2614 ++extraArgs;
2615 } else {
2616 params.comp = builder.makeIntConstant(0);
2617 }
2618 }
John Kessenichfc51d282015-08-19 13:34:18 -06002619
John Kessenich019f08f2016-02-15 15:40:42 -07002620 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002621}
2622
2623spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2624{
2625 // Grab the function's pointer from the previously created function
2626 spv::Function* function = functionMap[node->getName().c_str()];
2627 if (! function)
2628 return 0;
2629
2630 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2631 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2632
2633 // See comments in makeFunctions() for details about the semantics for parameter passing.
2634 //
2635 // These imply we need a four step process:
2636 // 1. Evaluate the arguments
2637 // 2. Allocate and make copies of in, out, and inout arguments
2638 // 3. Make the call
2639 // 4. Copy back the results
2640
2641 // 1. Evaluate the arguments
2642 std::vector<spv::Builder::AccessChain> lValues;
2643 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002644 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002645 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2646 // build l-value
2647 builder.clearAccessChain();
2648 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002649 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002650 // keep outputs as l-values, evaluate input-only as r-values
2651 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2652 // save l-value
2653 lValues.push_back(builder.getAccessChain());
2654 } else {
2655 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002656 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002657 }
2658 }
2659
2660 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2661 // copy the original into that space.
2662 //
2663 // Also, build up the list of actual arguments to pass in for the call
2664 int lValueCount = 0;
2665 int rValueCount = 0;
2666 std::vector<spv::Id> spvArgs;
2667 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2668 spv::Id arg;
2669 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2670 // need space to hold the copy
2671 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2672 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2673 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2674 // need to copy the input into output space
2675 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002676 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002677 builder.createStore(copy, arg);
2678 }
2679 ++lValueCount;
2680 } else {
2681 arg = rValues[rValueCount];
2682 ++rValueCount;
2683 }
2684 spvArgs.push_back(arg);
2685 }
2686
2687 // 3. Make the call.
2688 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002689 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002690
2691 // 4. Copy back out an "out" arguments.
2692 lValueCount = 0;
2693 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2694 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2695 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2696 spv::Id copy = builder.createLoad(spvArgs[a]);
2697 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002698 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002699 }
2700 ++lValueCount;
2701 }
2702 }
2703
2704 return result;
2705}
2706
2707// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002708spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2709 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002710 spv::Id typeId, spv::Id left, spv::Id right,
2711 glslang::TBasicType typeProxy, bool reduceComparison)
2712{
Rex Xu8ff43de2016-04-22 16:51:45 +08002713 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002714 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002715 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002716
2717 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002718 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002719 bool comparison = false;
2720
2721 switch (op) {
2722 case glslang::EOpAdd:
2723 case glslang::EOpAddAssign:
2724 if (isFloat)
2725 binOp = spv::OpFAdd;
2726 else
2727 binOp = spv::OpIAdd;
2728 break;
2729 case glslang::EOpSub:
2730 case glslang::EOpSubAssign:
2731 if (isFloat)
2732 binOp = spv::OpFSub;
2733 else
2734 binOp = spv::OpISub;
2735 break;
2736 case glslang::EOpMul:
2737 case glslang::EOpMulAssign:
2738 if (isFloat)
2739 binOp = spv::OpFMul;
2740 else
2741 binOp = spv::OpIMul;
2742 break;
2743 case glslang::EOpVectorTimesScalar:
2744 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002745 if (isFloat) {
2746 if (builder.isVector(right))
2747 std::swap(left, right);
2748 assert(builder.isScalar(right));
2749 needMatchingVectors = false;
2750 binOp = spv::OpVectorTimesScalar;
2751 } else
2752 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002753 break;
2754 case glslang::EOpVectorTimesMatrix:
2755 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002756 binOp = spv::OpVectorTimesMatrix;
2757 break;
2758 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002759 binOp = spv::OpMatrixTimesVector;
2760 break;
2761 case glslang::EOpMatrixTimesScalar:
2762 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002763 binOp = spv::OpMatrixTimesScalar;
2764 break;
2765 case glslang::EOpMatrixTimesMatrix:
2766 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002767 binOp = spv::OpMatrixTimesMatrix;
2768 break;
2769 case glslang::EOpOuterProduct:
2770 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002771 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002772 break;
2773
2774 case glslang::EOpDiv:
2775 case glslang::EOpDivAssign:
2776 if (isFloat)
2777 binOp = spv::OpFDiv;
2778 else if (isUnsigned)
2779 binOp = spv::OpUDiv;
2780 else
2781 binOp = spv::OpSDiv;
2782 break;
2783 case glslang::EOpMod:
2784 case glslang::EOpModAssign:
2785 if (isFloat)
2786 binOp = spv::OpFMod;
2787 else if (isUnsigned)
2788 binOp = spv::OpUMod;
2789 else
2790 binOp = spv::OpSMod;
2791 break;
2792 case glslang::EOpRightShift:
2793 case glslang::EOpRightShiftAssign:
2794 if (isUnsigned)
2795 binOp = spv::OpShiftRightLogical;
2796 else
2797 binOp = spv::OpShiftRightArithmetic;
2798 break;
2799 case glslang::EOpLeftShift:
2800 case glslang::EOpLeftShiftAssign:
2801 binOp = spv::OpShiftLeftLogical;
2802 break;
2803 case glslang::EOpAnd:
2804 case glslang::EOpAndAssign:
2805 binOp = spv::OpBitwiseAnd;
2806 break;
2807 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002808 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002809 binOp = spv::OpLogicalAnd;
2810 break;
2811 case glslang::EOpInclusiveOr:
2812 case glslang::EOpInclusiveOrAssign:
2813 binOp = spv::OpBitwiseOr;
2814 break;
2815 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002816 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002817 binOp = spv::OpLogicalOr;
2818 break;
2819 case glslang::EOpExclusiveOr:
2820 case glslang::EOpExclusiveOrAssign:
2821 binOp = spv::OpBitwiseXor;
2822 break;
2823 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002824 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002825 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002826 break;
2827
2828 case glslang::EOpLessThan:
2829 case glslang::EOpGreaterThan:
2830 case glslang::EOpLessThanEqual:
2831 case glslang::EOpGreaterThanEqual:
2832 case glslang::EOpEqual:
2833 case glslang::EOpNotEqual:
2834 case glslang::EOpVectorEqual:
2835 case glslang::EOpVectorNotEqual:
2836 comparison = true;
2837 break;
2838 default:
2839 break;
2840 }
2841
John Kessenich7c1aa102015-10-15 13:29:11 -06002842 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002843 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002844 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002845 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002846 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002847
2848 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002849 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002850 builder.promoteScalar(precision, left, right);
2851
qining25262b32016-05-06 17:25:16 -04002852 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2853 addDecoration(result, noContraction);
2854 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002855 }
2856
2857 if (! comparison)
2858 return 0;
2859
John Kessenich7c1aa102015-10-15 13:29:11 -06002860 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002861
2862 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2863 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2864
John Kessenich22118352015-12-21 20:54:09 -07002865 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002866 }
2867
2868 switch (op) {
2869 case glslang::EOpLessThan:
2870 if (isFloat)
2871 binOp = spv::OpFOrdLessThan;
2872 else if (isUnsigned)
2873 binOp = spv::OpULessThan;
2874 else
2875 binOp = spv::OpSLessThan;
2876 break;
2877 case glslang::EOpGreaterThan:
2878 if (isFloat)
2879 binOp = spv::OpFOrdGreaterThan;
2880 else if (isUnsigned)
2881 binOp = spv::OpUGreaterThan;
2882 else
2883 binOp = spv::OpSGreaterThan;
2884 break;
2885 case glslang::EOpLessThanEqual:
2886 if (isFloat)
2887 binOp = spv::OpFOrdLessThanEqual;
2888 else if (isUnsigned)
2889 binOp = spv::OpULessThanEqual;
2890 else
2891 binOp = spv::OpSLessThanEqual;
2892 break;
2893 case glslang::EOpGreaterThanEqual:
2894 if (isFloat)
2895 binOp = spv::OpFOrdGreaterThanEqual;
2896 else if (isUnsigned)
2897 binOp = spv::OpUGreaterThanEqual;
2898 else
2899 binOp = spv::OpSGreaterThanEqual;
2900 break;
2901 case glslang::EOpEqual:
2902 case glslang::EOpVectorEqual:
2903 if (isFloat)
2904 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002905 else if (isBool)
2906 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002907 else
2908 binOp = spv::OpIEqual;
2909 break;
2910 case glslang::EOpNotEqual:
2911 case glslang::EOpVectorNotEqual:
2912 if (isFloat)
2913 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002914 else if (isBool)
2915 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002916 else
2917 binOp = spv::OpINotEqual;
2918 break;
2919 default:
2920 break;
2921 }
2922
qining25262b32016-05-06 17:25:16 -04002923 if (binOp != spv::OpNop) {
2924 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2925 addDecoration(result, noContraction);
2926 return builder.setPrecision(result, precision);
2927 }
John Kessenich140f3df2015-06-26 16:58:36 -06002928
2929 return 0;
2930}
2931
John Kessenich04bb8a02015-12-12 12:28:14 -07002932//
2933// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2934// These can be any of:
2935//
2936// matrix * scalar
2937// scalar * matrix
2938// matrix * matrix linear algebraic
2939// matrix * vector
2940// vector * matrix
2941// matrix * matrix componentwise
2942// matrix op matrix op in {+, -, /}
2943// matrix op scalar op in {+, -, /}
2944// scalar op matrix op in {+, -, /}
2945//
qining25262b32016-05-06 17:25:16 -04002946spv::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 -07002947{
2948 bool firstClass = true;
2949
2950 // First, handle first-class matrix operations (* and matrix/scalar)
2951 switch (op) {
2952 case spv::OpFDiv:
2953 if (builder.isMatrix(left) && builder.isScalar(right)) {
2954 // turn matrix / scalar into a multiply...
2955 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2956 op = spv::OpMatrixTimesScalar;
2957 } else
2958 firstClass = false;
2959 break;
2960 case spv::OpMatrixTimesScalar:
2961 if (builder.isMatrix(right))
2962 std::swap(left, right);
2963 assert(builder.isScalar(right));
2964 break;
2965 case spv::OpVectorTimesMatrix:
2966 assert(builder.isVector(left));
2967 assert(builder.isMatrix(right));
2968 break;
2969 case spv::OpMatrixTimesVector:
2970 assert(builder.isMatrix(left));
2971 assert(builder.isVector(right));
2972 break;
2973 case spv::OpMatrixTimesMatrix:
2974 assert(builder.isMatrix(left));
2975 assert(builder.isMatrix(right));
2976 break;
2977 default:
2978 firstClass = false;
2979 break;
2980 }
2981
qining25262b32016-05-06 17:25:16 -04002982 if (firstClass) {
2983 spv::Id result = builder.createBinOp(op, typeId, left, right);
2984 addDecoration(result, noContraction);
2985 return builder.setPrecision(result, precision);
2986 }
John Kessenich04bb8a02015-12-12 12:28:14 -07002987
2988 // Handle component-wise +, -, *, and / for all combinations of type.
2989 // The result type of all of them is the same type as the (a) matrix operand.
2990 // The algorithm is to:
2991 // - break the matrix(es) into vectors
2992 // - smear any scalar to a vector
2993 // - do vector operations
2994 // - make a matrix out the vector results
2995 switch (op) {
2996 case spv::OpFAdd:
2997 case spv::OpFSub:
2998 case spv::OpFDiv:
2999 case spv::OpFMul:
3000 {
3001 // one time set up...
3002 bool leftMat = builder.isMatrix(left);
3003 bool rightMat = builder.isMatrix(right);
3004 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3005 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3006 spv::Id scalarType = builder.getScalarTypeId(typeId);
3007 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3008 std::vector<spv::Id> results;
3009 spv::Id smearVec = spv::NoResult;
3010 if (builder.isScalar(left))
3011 smearVec = builder.smearScalar(precision, left, vecType);
3012 else if (builder.isScalar(right))
3013 smearVec = builder.smearScalar(precision, right, vecType);
3014
3015 // do each vector op
3016 for (unsigned int c = 0; c < numCols; ++c) {
3017 std::vector<unsigned int> indexes;
3018 indexes.push_back(c);
3019 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3020 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003021 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3022 addDecoration(result, noContraction);
3023 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003024 }
3025
3026 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003027 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003028 }
3029 default:
3030 assert(0);
3031 return spv::NoResult;
3032 }
3033}
3034
qining25262b32016-05-06 17:25:16 -04003035spv::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 -06003036{
3037 spv::Op unaryOp = spv::OpNop;
3038 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003039 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003040 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003041
3042 switch (op) {
3043 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003044 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003045 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003046 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003047 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003048 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003049 unaryOp = spv::OpSNegate;
3050 break;
3051
3052 case glslang::EOpLogicalNot:
3053 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003054 unaryOp = spv::OpLogicalNot;
3055 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003056 case glslang::EOpBitwiseNot:
3057 unaryOp = spv::OpNot;
3058 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003059
John Kessenich140f3df2015-06-26 16:58:36 -06003060 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003061 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003062 break;
3063 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003064 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003065 break;
3066 case glslang::EOpTranspose:
3067 unaryOp = spv::OpTranspose;
3068 break;
3069
3070 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003071 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003072 break;
3073 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003074 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003075 break;
3076 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003077 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003078 break;
3079 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003080 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003081 break;
3082 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003083 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003084 break;
3085 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 break;
3088 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003089 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003090 break;
3091 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094
3095 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003096 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003097 break;
3098 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003099 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003100 break;
3101 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003102 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003103 break;
3104 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003105 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003106 break;
3107 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003108 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003109 break;
3110 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003111 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003112 break;
3113
3114 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003115 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003116 break;
3117 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003118 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003119 break;
3120
3121 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003122 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 break;
3124 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003125 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003126 break;
3127 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003128 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003129 break;
3130 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003131 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003132 break;
3133 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003134 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003135 break;
3136 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003137 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 break;
3139
3140 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003141 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003142 break;
3143 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003144 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003145 break;
3146 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003147 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003148 break;
3149 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003150 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003151 break;
3152 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 break;
3155 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003156 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003157 break;
3158
3159 case glslang::EOpIsNan:
3160 unaryOp = spv::OpIsNan;
3161 break;
3162 case glslang::EOpIsInf:
3163 unaryOp = spv::OpIsInf;
3164 break;
3165
Rex Xucbc426e2015-12-15 16:03:10 +08003166 case glslang::EOpFloatBitsToInt:
3167 case glslang::EOpFloatBitsToUint:
3168 case glslang::EOpIntBitsToFloat:
3169 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003170 case glslang::EOpDoubleBitsToInt64:
3171 case glslang::EOpDoubleBitsToUint64:
3172 case glslang::EOpInt64BitsToDouble:
3173 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003174 unaryOp = spv::OpBitcast;
3175 break;
3176
John Kessenich140f3df2015-06-26 16:58:36 -06003177 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003178 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003179 break;
3180 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003181 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003182 break;
3183 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003184 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 break;
3186 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003187 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003188 break;
3189 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003195 case glslang::EOpPackSnorm4x8:
3196 libCall = spv::GLSLstd450PackSnorm4x8;
3197 break;
3198 case glslang::EOpUnpackSnorm4x8:
3199 libCall = spv::GLSLstd450UnpackSnorm4x8;
3200 break;
3201 case glslang::EOpPackUnorm4x8:
3202 libCall = spv::GLSLstd450PackUnorm4x8;
3203 break;
3204 case glslang::EOpUnpackUnorm4x8:
3205 libCall = spv::GLSLstd450UnpackUnorm4x8;
3206 break;
3207 case glslang::EOpPackDouble2x32:
3208 libCall = spv::GLSLstd450PackDouble2x32;
3209 break;
3210 case glslang::EOpUnpackDouble2x32:
3211 libCall = spv::GLSLstd450UnpackDouble2x32;
3212 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003213
Rex Xu8ff43de2016-04-22 16:51:45 +08003214 case glslang::EOpPackInt2x32:
3215 case glslang::EOpUnpackInt2x32:
3216 case glslang::EOpPackUint2x32:
3217 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003218 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003219 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3220 break;
3221
John Kessenich140f3df2015-06-26 16:58:36 -06003222 case glslang::EOpDPdx:
3223 unaryOp = spv::OpDPdx;
3224 break;
3225 case glslang::EOpDPdy:
3226 unaryOp = spv::OpDPdy;
3227 break;
3228 case glslang::EOpFwidth:
3229 unaryOp = spv::OpFwidth;
3230 break;
3231 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003232 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003233 unaryOp = spv::OpDPdxFine;
3234 break;
3235 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003236 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003237 unaryOp = spv::OpDPdyFine;
3238 break;
3239 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003240 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003241 unaryOp = spv::OpFwidthFine;
3242 break;
3243 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003244 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003245 unaryOp = spv::OpDPdxCoarse;
3246 break;
3247 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003248 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 unaryOp = spv::OpDPdyCoarse;
3250 break;
3251 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003252 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003253 unaryOp = spv::OpFwidthCoarse;
3254 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003255 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003256 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003257 libCall = spv::GLSLstd450InterpolateAtCentroid;
3258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003259 case glslang::EOpAny:
3260 unaryOp = spv::OpAny;
3261 break;
3262 case glslang::EOpAll:
3263 unaryOp = spv::OpAll;
3264 break;
3265
3266 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003267 if (isFloat)
3268 libCall = spv::GLSLstd450FAbs;
3269 else
3270 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003271 break;
3272 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003273 if (isFloat)
3274 libCall = spv::GLSLstd450FSign;
3275 else
3276 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003277 break;
3278
John Kessenichfc51d282015-08-19 13:34:18 -06003279 case glslang::EOpAtomicCounterIncrement:
3280 case glslang::EOpAtomicCounterDecrement:
3281 case glslang::EOpAtomicCounter:
3282 {
3283 // Handle all of the atomics in one place, in createAtomicOperation()
3284 std::vector<spv::Id> operands;
3285 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003286 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003287 }
3288
John Kessenichfc51d282015-08-19 13:34:18 -06003289 case glslang::EOpBitFieldReverse:
3290 unaryOp = spv::OpBitReverse;
3291 break;
3292 case glslang::EOpBitCount:
3293 unaryOp = spv::OpBitCount;
3294 break;
3295 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003296 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003297 break;
3298 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003299 if (isUnsigned)
3300 libCall = spv::GLSLstd450FindUMsb;
3301 else
3302 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003303 break;
3304
Rex Xu574ab042016-04-14 16:53:07 +08003305 case glslang::EOpBallot:
3306 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003307 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003308 libCall = spv::GLSLstd450Bad;
3309 break;
3310
Rex Xu338b1852016-05-05 20:38:33 +08003311 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003312 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003313 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003314 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003315
John Kessenich140f3df2015-06-26 16:58:36 -06003316 default:
3317 return 0;
3318 }
3319
3320 spv::Id id;
3321 if (libCall >= 0) {
3322 std::vector<spv::Id> args;
3323 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003324 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003325 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003326 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003327 }
John Kessenich140f3df2015-06-26 16:58:36 -06003328
qining25262b32016-05-06 17:25:16 -04003329 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003330 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003331}
3332
John Kessenich7a53f762016-01-20 11:19:27 -07003333// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003334spv::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 -07003335{
3336 // Handle unary operations vector by vector.
3337 // The result type is the same type as the original type.
3338 // The algorithm is to:
3339 // - break the matrix into vectors
3340 // - apply the operation to each vector
3341 // - make a matrix out the vector results
3342
3343 // get the types sorted out
3344 int numCols = builder.getNumColumns(operand);
3345 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003346 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3347 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003348 std::vector<spv::Id> results;
3349
3350 // do each vector op
3351 for (int c = 0; c < numCols; ++c) {
3352 std::vector<unsigned int> indexes;
3353 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003354 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3355 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3356 addDecoration(destVec, noContraction);
3357 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003358 }
3359
3360 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003361 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003362}
3363
Rex Xu73e3ce72016-04-27 18:48:17 +08003364spv::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 -06003365{
3366 spv::Op convOp = spv::OpNop;
3367 spv::Id zero = 0;
3368 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003369 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003370
3371 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3372
3373 switch (op) {
3374 case glslang::EOpConvIntToBool:
3375 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003376 case glslang::EOpConvInt64ToBool:
3377 case glslang::EOpConvUint64ToBool:
3378 zero = (op == glslang::EOpConvInt64ToBool ||
3379 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003380 zero = makeSmearedConstant(zero, vectorSize);
3381 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3382
3383 case glslang::EOpConvFloatToBool:
3384 zero = builder.makeFloatConstant(0.0F);
3385 zero = makeSmearedConstant(zero, vectorSize);
3386 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3387
3388 case glslang::EOpConvDoubleToBool:
3389 zero = builder.makeDoubleConstant(0.0);
3390 zero = makeSmearedConstant(zero, vectorSize);
3391 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3392
3393 case glslang::EOpConvBoolToFloat:
3394 convOp = spv::OpSelect;
3395 zero = builder.makeFloatConstant(0.0);
3396 one = builder.makeFloatConstant(1.0);
3397 break;
3398 case glslang::EOpConvBoolToDouble:
3399 convOp = spv::OpSelect;
3400 zero = builder.makeDoubleConstant(0.0);
3401 one = builder.makeDoubleConstant(1.0);
3402 break;
3403 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003404 case glslang::EOpConvBoolToInt64:
3405 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3406 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003407 convOp = spv::OpSelect;
3408 break;
3409 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003410 case glslang::EOpConvBoolToUint64:
3411 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3412 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003413 convOp = spv::OpSelect;
3414 break;
3415
3416 case glslang::EOpConvIntToFloat:
3417 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003418 case glslang::EOpConvInt64ToFloat:
3419 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003420 convOp = spv::OpConvertSToF;
3421 break;
3422
3423 case glslang::EOpConvUintToFloat:
3424 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003425 case glslang::EOpConvUint64ToFloat:
3426 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003427 convOp = spv::OpConvertUToF;
3428 break;
3429
3430 case glslang::EOpConvDoubleToFloat:
3431 case glslang::EOpConvFloatToDouble:
3432 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003433 if (builder.isMatrixType(destType))
3434 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003435 break;
3436
3437 case glslang::EOpConvFloatToInt:
3438 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003439 case glslang::EOpConvFloatToInt64:
3440 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003441 convOp = spv::OpConvertFToS;
3442 break;
3443
3444 case glslang::EOpConvUintToInt:
3445 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003446 case glslang::EOpConvUint64ToInt64:
3447 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003448 if (builder.isInSpecConstCodeGenMode()) {
3449 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003450 zero = (op == glslang::EOpConvUintToInt64 ||
3451 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003452 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003453 // Use OpIAdd, instead of OpBitcast to do the conversion when
3454 // generating for OpSpecConstantOp instruction.
3455 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3456 }
3457 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003458 convOp = spv::OpBitcast;
3459 break;
3460
3461 case glslang::EOpConvFloatToUint:
3462 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003463 case glslang::EOpConvFloatToUint64:
3464 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003465 convOp = spv::OpConvertFToU;
3466 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003467
3468 case glslang::EOpConvIntToInt64:
3469 case glslang::EOpConvInt64ToInt:
3470 convOp = spv::OpSConvert;
3471 break;
3472
3473 case glslang::EOpConvUintToUint64:
3474 case glslang::EOpConvUint64ToUint:
3475 convOp = spv::OpUConvert;
3476 break;
3477
3478 case glslang::EOpConvIntToUint64:
3479 case glslang::EOpConvInt64ToUint:
3480 case glslang::EOpConvUint64ToInt:
3481 case glslang::EOpConvUintToInt64:
3482 // OpSConvert/OpUConvert + OpBitCast
3483 switch (op) {
3484 case glslang::EOpConvIntToUint64:
3485 convOp = spv::OpSConvert;
3486 type = builder.makeIntType(64);
3487 break;
3488 case glslang::EOpConvInt64ToUint:
3489 convOp = spv::OpSConvert;
3490 type = builder.makeIntType(32);
3491 break;
3492 case glslang::EOpConvUint64ToInt:
3493 convOp = spv::OpUConvert;
3494 type = builder.makeUintType(32);
3495 break;
3496 case glslang::EOpConvUintToInt64:
3497 convOp = spv::OpUConvert;
3498 type = builder.makeUintType(64);
3499 break;
3500 default:
3501 assert(0);
3502 break;
3503 }
3504
3505 if (vectorSize > 0)
3506 type = builder.makeVectorType(type, vectorSize);
3507
3508 operand = builder.createUnaryOp(convOp, type, operand);
3509
3510 if (builder.isInSpecConstCodeGenMode()) {
3511 // Build zero scalar or vector for OpIAdd.
3512 zero = (op == glslang::EOpConvIntToUint64 ||
3513 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3514 zero = makeSmearedConstant(zero, vectorSize);
3515 // Use OpIAdd, instead of OpBitcast to do the conversion when
3516 // generating for OpSpecConstantOp instruction.
3517 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3518 }
3519 // For normal run-time conversion instruction, use OpBitcast.
3520 convOp = spv::OpBitcast;
3521 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003522 default:
3523 break;
3524 }
3525
3526 spv::Id result = 0;
3527 if (convOp == spv::OpNop)
3528 return result;
3529
3530 if (convOp == spv::OpSelect) {
3531 zero = makeSmearedConstant(zero, vectorSize);
3532 one = makeSmearedConstant(one, vectorSize);
3533 result = builder.createTriOp(convOp, destType, operand, one, zero);
3534 } else
3535 result = builder.createUnaryOp(convOp, destType, operand);
3536
John Kessenich32cfd492016-02-02 12:37:46 -07003537 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003538}
3539
3540spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3541{
3542 if (vectorSize == 0)
3543 return constant;
3544
3545 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3546 std::vector<spv::Id> components;
3547 for (int c = 0; c < vectorSize; ++c)
3548 components.push_back(constant);
3549 return builder.makeCompositeConstant(vectorTypeId, components);
3550}
3551
John Kessenich426394d2015-07-23 10:22:48 -06003552// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003553spv::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 -06003554{
3555 spv::Op opCode = spv::OpNop;
3556
3557 switch (op) {
3558 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003559 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003560 opCode = spv::OpAtomicIAdd;
3561 break;
3562 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003563 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003564 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003565 break;
3566 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003567 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003568 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003569 break;
3570 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003571 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003572 opCode = spv::OpAtomicAnd;
3573 break;
3574 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003575 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003576 opCode = spv::OpAtomicOr;
3577 break;
3578 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003579 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003580 opCode = spv::OpAtomicXor;
3581 break;
3582 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003583 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003584 opCode = spv::OpAtomicExchange;
3585 break;
3586 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003587 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003588 opCode = spv::OpAtomicCompareExchange;
3589 break;
3590 case glslang::EOpAtomicCounterIncrement:
3591 opCode = spv::OpAtomicIIncrement;
3592 break;
3593 case glslang::EOpAtomicCounterDecrement:
3594 opCode = spv::OpAtomicIDecrement;
3595 break;
3596 case glslang::EOpAtomicCounter:
3597 opCode = spv::OpAtomicLoad;
3598 break;
3599 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003600 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003601 break;
3602 }
3603
3604 // Sort out the operands
3605 // - mapping from glslang -> SPV
3606 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003607 // - compare-exchange swaps the value and comparator
3608 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003609 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3610 auto opIt = operands.begin(); // walk the glslang operands
3611 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003612 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3613 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3614 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003615 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3616 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003617 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003618 spvAtomicOperands.push_back(*(opIt + 1));
3619 spvAtomicOperands.push_back(*opIt);
3620 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003621 }
John Kessenich426394d2015-07-23 10:22:48 -06003622
John Kessenich3e60a6f2015-09-14 22:45:16 -06003623 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003624 for (; opIt != operands.end(); ++opIt)
3625 spvAtomicOperands.push_back(*opIt);
3626
3627 return builder.createOp(opCode, typeId, spvAtomicOperands);
3628}
3629
John Kessenich91cef522016-05-05 16:45:40 -06003630// Create group invocation operations.
3631spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3632{
3633 builder.addCapability(spv::CapabilityGroups);
3634
3635 std::vector<spv::Id> operands;
3636 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3637 operands.push_back(operand);
3638
3639 switch (op) {
3640 case glslang::EOpAnyInvocation:
3641 case glslang::EOpAllInvocations:
3642 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3643
3644 case glslang::EOpAllInvocationsEqual:
3645 {
3646 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3647 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3648
3649 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3650 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3651 }
3652 default:
3653 logger->missingFunctionality("invocation operation");
3654 return spv::NoResult;
3655 }
3656}
3657
John Kessenich5e4b1242015-08-06 22:53:06 -06003658spv::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 -06003659{
Rex Xu8ff43de2016-04-22 16:51:45 +08003660 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003661 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3662
John Kessenich140f3df2015-06-26 16:58:36 -06003663 spv::Op opCode = spv::OpNop;
3664 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003665 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003666 spv::Id typeId0 = 0;
3667 if (consumedOperands > 0)
3668 typeId0 = builder.getTypeId(operands[0]);
3669 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003670
3671 switch (op) {
3672 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003673 if (isFloat)
3674 libCall = spv::GLSLstd450FMin;
3675 else if (isUnsigned)
3676 libCall = spv::GLSLstd450UMin;
3677 else
3678 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003679 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003680 break;
3681 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003682 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003683 break;
3684 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003685 if (isFloat)
3686 libCall = spv::GLSLstd450FMax;
3687 else if (isUnsigned)
3688 libCall = spv::GLSLstd450UMax;
3689 else
3690 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003691 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003692 break;
3693 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003694 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003695 break;
3696 case glslang::EOpDot:
3697 opCode = spv::OpDot;
3698 break;
3699 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003700 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702
3703 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003704 if (isFloat)
3705 libCall = spv::GLSLstd450FClamp;
3706 else if (isUnsigned)
3707 libCall = spv::GLSLstd450UClamp;
3708 else
3709 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003710 builder.promoteScalar(precision, operands.front(), operands[1]);
3711 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003712 break;
3713 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003714 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3715 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003716 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003717 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003718 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003719 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003720 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003721 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003725 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003729 builder.promoteScalar(precision, operands[0], operands[2]);
3730 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732
3733 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003734 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
3739 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003741 break;
3742 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003743 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
3745 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003746 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003748 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003749 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003750 libCall = spv::GLSLstd450InterpolateAtSample;
3751 break;
3752 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003753 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003754 libCall = spv::GLSLstd450InterpolateAtOffset;
3755 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003756 case glslang::EOpAddCarry:
3757 opCode = spv::OpIAddCarry;
3758 typeId = builder.makeStructResultType(typeId0, typeId0);
3759 consumedOperands = 2;
3760 break;
3761 case glslang::EOpSubBorrow:
3762 opCode = spv::OpISubBorrow;
3763 typeId = builder.makeStructResultType(typeId0, typeId0);
3764 consumedOperands = 2;
3765 break;
3766 case glslang::EOpUMulExtended:
3767 opCode = spv::OpUMulExtended;
3768 typeId = builder.makeStructResultType(typeId0, typeId0);
3769 consumedOperands = 2;
3770 break;
3771 case glslang::EOpIMulExtended:
3772 opCode = spv::OpSMulExtended;
3773 typeId = builder.makeStructResultType(typeId0, typeId0);
3774 consumedOperands = 2;
3775 break;
3776 case glslang::EOpBitfieldExtract:
3777 if (isUnsigned)
3778 opCode = spv::OpBitFieldUExtract;
3779 else
3780 opCode = spv::OpBitFieldSExtract;
3781 break;
3782 case glslang::EOpBitfieldInsert:
3783 opCode = spv::OpBitFieldInsert;
3784 break;
3785
3786 case glslang::EOpFma:
3787 libCall = spv::GLSLstd450Fma;
3788 break;
3789 case glslang::EOpFrexp:
3790 libCall = spv::GLSLstd450FrexpStruct;
3791 if (builder.getNumComponents(operands[0]) == 1)
3792 frexpIntType = builder.makeIntegerType(32, true);
3793 else
3794 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3795 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3796 consumedOperands = 1;
3797 break;
3798 case glslang::EOpLdexp:
3799 libCall = spv::GLSLstd450Ldexp;
3800 break;
3801
Rex Xu574ab042016-04-14 16:53:07 +08003802 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003803 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003804 libCall = spv::GLSLstd450Bad;
3805 break;
3806
John Kessenich140f3df2015-06-26 16:58:36 -06003807 default:
3808 return 0;
3809 }
3810
3811 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003812 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003813 // Use an extended instruction from the standard library.
3814 // Construct the call arguments, without modifying the original operands vector.
3815 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3816 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003817 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003818 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003819 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003820 case 0:
3821 // should all be handled by visitAggregate and createNoArgOperation
3822 assert(0);
3823 return 0;
3824 case 1:
3825 // should all be handled by createUnaryOperation
3826 assert(0);
3827 return 0;
3828 case 2:
3829 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3830 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003831 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003832 // anything 3 or over doesn't have l-value operands, so all should be consumed
3833 assert(consumedOperands == operands.size());
3834 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003835 break;
3836 }
3837 }
3838
John Kessenich55e7d112015-11-15 21:33:39 -07003839 // Decode the return types that were structures
3840 switch (op) {
3841 case glslang::EOpAddCarry:
3842 case glslang::EOpSubBorrow:
3843 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3844 id = builder.createCompositeExtract(id, typeId0, 0);
3845 break;
3846 case glslang::EOpUMulExtended:
3847 case glslang::EOpIMulExtended:
3848 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3849 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3850 break;
3851 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003852 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003853 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3854 id = builder.createCompositeExtract(id, typeId0, 0);
3855 break;
3856 default:
3857 break;
3858 }
3859
John Kessenich32cfd492016-02-02 12:37:46 -07003860 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003861}
3862
3863// Intrinsics with no arguments, no return value, and no precision.
3864spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3865{
3866 // TODO: get the barrier operands correct
3867
3868 switch (op) {
3869 case glslang::EOpEmitVertex:
3870 builder.createNoResultOp(spv::OpEmitVertex);
3871 return 0;
3872 case glslang::EOpEndPrimitive:
3873 builder.createNoResultOp(spv::OpEndPrimitive);
3874 return 0;
3875 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003876 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3877 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003878 return 0;
3879 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003880 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003881 return 0;
3882 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003883 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003884 return 0;
3885 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003886 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003887 return 0;
3888 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003889 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003890 return 0;
3891 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003892 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003893 return 0;
3894 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003895 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003896 return 0;
3897 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003898 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003899 return 0;
3900 }
3901}
3902
3903spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3904{
John Kessenich2f273362015-07-18 22:34:27 -06003905 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003906 spv::Id id;
3907 if (symbolValues.end() != iter) {
3908 id = iter->second;
3909 return id;
3910 }
3911
3912 // it was not found, create it
3913 id = createSpvVariable(symbol);
3914 symbolValues[symbol->getId()] = id;
3915
3916 if (! symbol->getType().isStruct()) {
3917 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003918 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003919 if (symbol->getType().getQualifier().hasSpecConstantId())
3920 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003921 if (symbol->getQualifier().hasLocation())
3922 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3923 if (symbol->getQualifier().hasIndex())
3924 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3925 if (symbol->getQualifier().hasComponent())
3926 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3927 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003928 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003929 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003930 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003931 if (symbol->getQualifier().hasXfbBuffer())
3932 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3933 if (symbol->getQualifier().hasXfbOffset())
3934 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3935 }
3936 }
3937
John Kesseniche0b6cad2015-12-24 10:30:13 -07003938 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003939 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003940 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003941 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003942 }
John Kessenich140f3df2015-06-26 16:58:36 -06003943 if (symbol->getQualifier().hasSet())
3944 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003945 else if (IsDescriptorResource(symbol->getType())) {
3946 // default to 0
3947 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3948 }
John Kessenich140f3df2015-06-26 16:58:36 -06003949 if (symbol->getQualifier().hasBinding())
3950 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003951 if (symbol->getQualifier().hasAttachment())
3952 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003953 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003954 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003955 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003956 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003957 if (symbol->getQualifier().hasXfbBuffer())
3958 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3959 }
3960
Rex Xu1da878f2016-02-21 20:59:01 +08003961 if (symbol->getType().isImage()) {
3962 std::vector<spv::Decoration> memory;
3963 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3964 for (unsigned int i = 0; i < memory.size(); ++i)
3965 addDecoration(id, memory[i]);
3966 }
3967
John Kessenich140f3df2015-06-26 16:58:36 -06003968 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06003969 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06003970 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003971 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003972
John Kessenich140f3df2015-06-26 16:58:36 -06003973 return id;
3974}
3975
John Kessenich55e7d112015-11-15 21:33:39 -07003976// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003977void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3978{
3979 if (dec != spv::BadValue)
3980 builder.addDecoration(id, dec);
3981}
3982
John Kessenich55e7d112015-11-15 21:33:39 -07003983// If 'dec' is valid, add a one-operand decoration to an object
3984void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3985{
3986 if (dec != spv::BadValue)
3987 builder.addDecoration(id, dec, value);
3988}
3989
3990// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003991void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3992{
3993 if (dec != spv::BadValue)
3994 builder.addMemberDecoration(id, (unsigned)member, dec);
3995}
3996
John Kessenich92187592016-02-01 13:45:25 -07003997// If 'dec' is valid, add a one-operand decoration to a struct member
3998void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3999{
4000 if (dec != spv::BadValue)
4001 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4002}
4003
John Kessenich55e7d112015-11-15 21:33:39 -07004004// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004005// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004006//
4007// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4008//
4009// Recursively walk the nodes. The nodes form a tree whose leaves are
4010// regular constants, which themselves are trees that createSpvConstant()
4011// recursively walks. So, this function walks the "top" of the tree:
4012// - emit specialization constant-building instructions for specConstant
4013// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004014spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004015{
John Kessenich7cc0e282016-03-20 00:46:02 -06004016 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004017
qining4f4bb812016-04-03 23:55:17 -04004018 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004019 if (! node.getQualifier().specConstant) {
4020 // hand off to the non-spec-constant path
4021 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4022 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004023 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004024 nextConst, false);
4025 }
4026
4027 // We now know we have a specialization constant to build
4028
qining4f4bb812016-04-03 23:55:17 -04004029 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
4030 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4031 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4032 std::vector<spv::Id> dimConstId;
4033 for (int dim = 0; dim < 3; ++dim) {
4034 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4035 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4036 if (specConst)
4037 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4038 }
4039 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4040 }
4041
4042 // An AST node labelled as specialization constant should be a symbol node.
4043 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4044 if (auto* sn = node.getAsSymbolNode()) {
4045 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004046 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4047 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4048 // will set the builder into spec constant op instruction generating mode.
4049 sub_tree->traverse(this);
4050 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004051 } else if (auto* const_union_array = &sn->getConstArray()){
4052 int nextConst = 0;
4053 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004054 }
4055 }
qining4f4bb812016-04-03 23:55:17 -04004056
4057 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4058 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004059 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004060 exit(1);
4061 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004062}
4063
John Kessenich140f3df2015-06-26 16:58:36 -06004064// Use 'consts' as the flattened glslang source of scalar constants to recursively
4065// build the aggregate SPIR-V constant.
4066//
4067// If there are not enough elements present in 'consts', 0 will be substituted;
4068// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4069//
qining08408382016-03-21 09:51:37 -04004070spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004071{
4072 // vector of constants for SPIR-V
4073 std::vector<spv::Id> spvConsts;
4074
4075 // Type is used for struct and array constants
4076 spv::Id typeId = convertGlslangToSpvType(glslangType);
4077
4078 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004079 glslang::TType elementType(glslangType, 0);
4080 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004081 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004082 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004083 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004084 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004085 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004086 } else if (glslangType.getStruct()) {
4087 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4088 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004089 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004090 } else if (glslangType.isVector()) {
4091 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4092 bool zero = nextConst >= consts.size();
4093 switch (glslangType.getBasicType()) {
4094 case glslang::EbtInt:
4095 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4096 break;
4097 case glslang::EbtUint:
4098 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4099 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004100 case glslang::EbtInt64:
4101 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4102 break;
4103 case glslang::EbtUint64:
4104 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4105 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004106 case glslang::EbtFloat:
4107 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4108 break;
4109 case glslang::EbtDouble:
4110 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4111 break;
4112 case glslang::EbtBool:
4113 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4114 break;
4115 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004116 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118 }
4119 ++nextConst;
4120 }
4121 } else {
4122 // we have a non-aggregate (scalar) constant
4123 bool zero = nextConst >= consts.size();
4124 spv::Id scalar = 0;
4125 switch (glslangType.getBasicType()) {
4126 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004127 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004128 break;
4129 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004130 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004131 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004132 case glslang::EbtInt64:
4133 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4134 break;
4135 case glslang::EbtUint64:
4136 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4137 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004138 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004139 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004142 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004145 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004146 break;
4147 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004148 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150 }
4151 ++nextConst;
4152 return scalar;
4153 }
4154
4155 return builder.makeCompositeConstant(typeId, spvConsts);
4156}
4157
John Kessenich7c1aa102015-10-15 13:29:11 -06004158// Return true if the node is a constant or symbol whose reading has no
4159// non-trivial observable cost or effect.
4160bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4161{
4162 // don't know what this is
4163 if (node == nullptr)
4164 return false;
4165
4166 // a constant is safe
4167 if (node->getAsConstantUnion() != nullptr)
4168 return true;
4169
4170 // not a symbol means non-trivial
4171 if (node->getAsSymbolNode() == nullptr)
4172 return false;
4173
4174 // a symbol, depends on what's being read
4175 switch (node->getType().getQualifier().storage) {
4176 case glslang::EvqTemporary:
4177 case glslang::EvqGlobal:
4178 case glslang::EvqIn:
4179 case glslang::EvqInOut:
4180 case glslang::EvqConst:
4181 case glslang::EvqConstReadOnly:
4182 case glslang::EvqUniform:
4183 return true;
4184 default:
4185 return false;
4186 }
qining25262b32016-05-06 17:25:16 -04004187}
John Kessenich7c1aa102015-10-15 13:29:11 -06004188
4189// A node is trivial if it is a single operation with no side effects.
4190// Error on the side of saying non-trivial.
4191// Return true if trivial.
4192bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4193{
4194 if (node == nullptr)
4195 return false;
4196
4197 // symbols and constants are trivial
4198 if (isTrivialLeaf(node))
4199 return true;
4200
4201 // otherwise, it needs to be a simple operation or one or two leaf nodes
4202
4203 // not a simple operation
4204 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4205 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4206 if (binaryNode == nullptr && unaryNode == nullptr)
4207 return false;
4208
4209 // not on leaf nodes
4210 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4211 return false;
4212
4213 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4214 return false;
4215 }
4216
4217 switch (node->getAsOperator()->getOp()) {
4218 case glslang::EOpLogicalNot:
4219 case glslang::EOpConvIntToBool:
4220 case glslang::EOpConvUintToBool:
4221 case glslang::EOpConvFloatToBool:
4222 case glslang::EOpConvDoubleToBool:
4223 case glslang::EOpEqual:
4224 case glslang::EOpNotEqual:
4225 case glslang::EOpLessThan:
4226 case glslang::EOpGreaterThan:
4227 case glslang::EOpLessThanEqual:
4228 case glslang::EOpGreaterThanEqual:
4229 case glslang::EOpIndexDirect:
4230 case glslang::EOpIndexDirectStruct:
4231 case glslang::EOpLogicalXor:
4232 case glslang::EOpAny:
4233 case glslang::EOpAll:
4234 return true;
4235 default:
4236 return false;
4237 }
4238}
4239
4240// Emit short-circuiting code, where 'right' is never evaluated unless
4241// the left side is true (for &&) or false (for ||).
4242spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4243{
4244 spv::Id boolTypeId = builder.makeBoolType();
4245
4246 // emit left operand
4247 builder.clearAccessChain();
4248 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004249 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004250
4251 // Operands to accumulate OpPhi operands
4252 std::vector<spv::Id> phiOperands;
4253 // accumulate left operand's phi information
4254 phiOperands.push_back(leftId);
4255 phiOperands.push_back(builder.getBuildPoint()->getId());
4256
4257 // Make the two kinds of operation symmetric with a "!"
4258 // || => emit "if (! left) result = right"
4259 // && => emit "if ( left) result = right"
4260 //
4261 // TODO: this runtime "not" for || could be avoided by adding functionality
4262 // to 'builder' to have an "else" without an "then"
4263 if (op == glslang::EOpLogicalOr)
4264 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4265
4266 // make an "if" based on the left value
4267 spv::Builder::If ifBuilder(leftId, builder);
4268
4269 // emit right operand as the "then" part of the "if"
4270 builder.clearAccessChain();
4271 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004272 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004273
4274 // accumulate left operand's phi information
4275 phiOperands.push_back(rightId);
4276 phiOperands.push_back(builder.getBuildPoint()->getId());
4277
4278 // finish the "if"
4279 ifBuilder.makeEndIf();
4280
4281 // phi together the two results
4282 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4283}
4284
John Kessenich140f3df2015-06-26 16:58:36 -06004285}; // end anonymous namespace
4286
4287namespace glslang {
4288
John Kessenich68d78fd2015-07-12 19:28:10 -06004289void GetSpirvVersion(std::string& version)
4290{
John Kessenich9e55f632015-07-15 10:03:39 -06004291 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004292 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004293 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004294 version = buf;
4295}
4296
John Kessenich140f3df2015-06-26 16:58:36 -06004297// Write SPIR-V out to a binary file
4298void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4299{
4300 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004301 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004302 for (int i = 0; i < (int)spirv.size(); ++i) {
4303 unsigned int word = spirv[i];
4304 out.write((const char*)&word, 4);
4305 }
4306 out.close();
4307}
4308
4309//
4310// Set up the glslang traversal
4311//
4312void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4313{
Lei Zhang17535f72016-05-04 15:55:59 -04004314 spv::SpvBuildLogger logger;
4315 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004316}
4317
Lei Zhang17535f72016-05-04 15:55:59 -04004318void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004319{
John Kessenich140f3df2015-06-26 16:58:36 -06004320 TIntermNode* root = intermediate.getTreeRoot();
4321
4322 if (root == 0)
4323 return;
4324
4325 glslang::GetThreadPoolAllocator().push();
4326
Lei Zhang17535f72016-05-04 15:55:59 -04004327 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004328
4329 root->traverse(&it);
4330
4331 it.dumpSpv(spirv);
4332
4333 glslang::GetThreadPoolAllocator().pop();
4334}
4335
4336}; // end namespace glslang