blob: 6c9068fc503cac55b5fb57c7f95b32d848447398 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
45 #include "GLSL.std.450.h"
46}
John Kessenich140f3df2015-06-26 16:58:36 -060047
48// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020049#include "../glslang/MachineIndependent/localintermediate.h"
50#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060052
John Kessenich140f3df2015-06-26 16:58:36 -060053#include <fstream>
Lei Zhang17535f72016-05-04 15:55:59 -040054#include <list>
55#include <map>
56#include <stack>
57#include <string>
58#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060059
60namespace {
61
John Kessenich55e7d112015-11-15 21:33:39 -070062// For low-order part of the generator's magic number. Bump up
63// when there is a change in the style (e.g., if SSA form changes,
64// or a different instruction sequence to do something gets used).
65const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060066
qining4c912612016-04-01 10:35:16 -040067namespace {
68class SpecConstantOpModeGuard {
69public:
70 SpecConstantOpModeGuard(spv::Builder* builder)
71 : builder_(builder) {
72 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040073 }
74 ~SpecConstantOpModeGuard() {
75 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
76 : builder_->setToNormalCodeGenMode();
77 }
qining40887662016-04-03 22:20:42 -040078 void turnOnSpecConstantOpMode() {
79 builder_->setToSpecConstCodeGenMode();
80 }
qining4c912612016-04-01 10:35:16 -040081
82private:
83 spv::Builder* builder_;
84 bool previous_flag_;
85};
86}
87
John Kessenich140f3df2015-06-26 16:58:36 -060088//
89// The main holder of information for translating glslang to SPIR-V.
90//
91// Derives from the AST walking base class.
92//
93class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
94public:
Lei Zhang17535f72016-05-04 15:55:59 -040095 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060096 virtual ~TGlslangToSpvTraverser();
97
98 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
99 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
100 void visitConstantUnion(glslang::TIntermConstantUnion*);
101 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
102 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
103 void visitSymbol(glslang::TIntermSymbol* symbol);
104 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
105 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
106 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
107
John Kessenich7ba63412015-12-20 17:37:07 -0700108 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110protected:
Rex Xubbceed72016-05-21 09:40:44 +0800111 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700113 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
115 spv::Id getSampledType(const glslang::TSampler&);
116 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700117 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600118 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
119 glslang::TLayoutPacking, const glslang::TQualifier&);
120 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
121 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700122 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700123 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800124 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700125 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700126 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
127 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
128 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100129 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600130
131 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
132 void makeFunctions(const glslang::TIntermSequence&);
133 void makeGlobalInitializers(const glslang::TIntermSequence&);
134 void visitFunctions(const glslang::TIntermSequence&);
135 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800136 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600137 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
138 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600139 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
140
qining25262b32016-05-06 17:25:16 -0400141 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
142 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
143 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
144 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800145 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600146 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800147 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich91cef522016-05-05 16:45:40 -0600148 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600149 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 spv::Id createNoArgOperation(glslang::TOperator op);
151 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
152 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700153 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700155 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400156 spv::Id createSpvConstant(const glslang::TIntermTyped&);
157 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600158 bool isTrivialLeaf(const glslang::TIntermTyped* node);
159 bool isTrivial(const glslang::TIntermTyped* node);
160 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600161
162 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700163 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600164 int sequenceDepth;
165
Lei Zhang17535f72016-05-04 15:55:59 -0400166 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400167
John Kessenich140f3df2015-06-26 16:58:36 -0600168 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
169 spv::Builder builder;
170 bool inMain;
171 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700172 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700173 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600174 const glslang::TIntermediate* glslangIntermediate;
175 spv::Id stdBuiltins;
176
John Kessenich2f273362015-07-18 22:34:27 -0600177 std::unordered_map<int, spv::Id> symbolValues;
178 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
179 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700180 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600181 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600182 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600183};
184
185//
186// Helper functions for translating glslang representations to SPIR-V enumerants.
187//
188
189// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700190spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600191{
John Kessenich66e2faf2016-03-12 18:34:36 -0700192 switch (source) {
193 case glslang::EShSourceGlsl:
194 switch (profile) {
195 case ENoProfile:
196 case ECoreProfile:
197 case ECompatibilityProfile:
198 return spv::SourceLanguageGLSL;
199 case EEsProfile:
200 return spv::SourceLanguageESSL;
201 default:
202 return spv::SourceLanguageUnknown;
203 }
204 case glslang::EShSourceHlsl:
205 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600206 default:
207 return spv::SourceLanguageUnknown;
208 }
209}
210
211// Translate glslang language (stage) to SPIR-V execution model.
212spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
213{
214 switch (stage) {
215 case EShLangVertex: return spv::ExecutionModelVertex;
216 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
217 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
218 case EShLangGeometry: return spv::ExecutionModelGeometry;
219 case EShLangFragment: return spv::ExecutionModelFragment;
220 case EShLangCompute: return spv::ExecutionModelGLCompute;
221 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600223 return spv::ExecutionModelFragment;
224 }
225}
226
227// Translate glslang type to SPIR-V storage class.
228spv::StorageClass TranslateStorageClass(const glslang::TType& type)
229{
230 if (type.getQualifier().isPipeInput())
231 return spv::StorageClassInput;
232 else if (type.getQualifier().isPipeOutput())
233 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700234 else if (type.getBasicType() == glslang::EbtSampler)
235 return spv::StorageClassUniformConstant;
236 else if (type.getBasicType() == glslang::EbtAtomicUint)
237 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700239 if (type.getQualifier().layoutPushConstant)
240 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 if (type.getBasicType() == glslang::EbtBlock)
242 return spv::StorageClassUniform;
243 else
244 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600245 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600246 } else {
247 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700248 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
249 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600250 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
251 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400252 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700253 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600254 return spv::StorageClassFunction;
255 }
256 }
257}
258
259// Translate glslang sampler type to SPIR-V dimensionality.
260spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
261{
262 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::Esd1D: return spv::Dim1D;
264 case glslang::Esd2D: return spv::Dim2D;
265 case glslang::Esd3D: return spv::Dim3D;
266 case glslang::EsdCube: return spv::DimCube;
267 case glslang::EsdRect: return spv::DimRect;
268 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700269 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700271 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600272 return spv::Dim2D;
273 }
274}
275
276// Translate glslang type to SPIR-V precision decorations.
277spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
278{
279 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700280 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600281 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 default:
283 return spv::NoPrecision;
284 }
285}
286
287// Translate glslang type to SPIR-V block decorations.
288spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
289{
290 if (type.getBasicType() == glslang::EbtBlock) {
291 switch (type.getQualifier().storage) {
292 case glslang::EvqUniform: return spv::DecorationBlock;
293 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
294 case glslang::EvqVaryingIn: return spv::DecorationBlock;
295 case glslang::EvqVaryingOut: return spv::DecorationBlock;
296 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600298 break;
299 }
300 }
301
302 return (spv::Decoration)spv::BadValue;
303}
304
Rex Xu1da878f2016-02-21 20:59:01 +0800305// Translate glslang type to SPIR-V memory decorations.
306void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
307{
308 if (qualifier.coherent)
309 memory.push_back(spv::DecorationCoherent);
310 if (qualifier.volatil)
311 memory.push_back(spv::DecorationVolatile);
312 if (qualifier.restrict)
313 memory.push_back(spv::DecorationRestrict);
314 if (qualifier.readonly)
315 memory.push_back(spv::DecorationNonWritable);
316 if (qualifier.writeonly)
317 memory.push_back(spv::DecorationNonReadable);
318}
319
John Kessenich140f3df2015-06-26 16:58:36 -0600320// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700321spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600322{
323 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700324 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600325 case glslang::ElmRowMajor:
326 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700329 default:
330 // opaque layouts don't need a majorness
331 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600332 }
333 } else {
334 switch (type.getBasicType()) {
335 default:
336 return (spv::Decoration)spv::BadValue;
337 break;
338 case glslang::EbtBlock:
339 switch (type.getQualifier().storage) {
340 case glslang::EvqUniform:
341 case glslang::EvqBuffer:
342 switch (type.getQualifier().layoutPacking) {
343 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
345 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600346 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 }
348 case glslang::EvqVaryingIn:
349 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700350 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600351 return (spv::Decoration)spv::BadValue;
352 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700353 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return (spv::Decoration)spv::BadValue;
355 }
356 }
357 }
358}
359
360// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700361// Returns spv::Decoration(spv::BadValue) when no decoration
362// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800363spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600364{
Rex Xubbceed72016-05-21 09:40:44 +0800365 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700366 // Smooth decoration doesn't exist in SPIR-V 1.0
367 return (spv::Decoration)spv::BadValue;
Rex Xubbceed72016-05-21 09:40:44 +0800368 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700369 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700370 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600371 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800372 else
373 return (spv::Decoration)spv::BadValue;
374}
375
376// Translate glslang type to SPIR-V auxiliary storage decorations.
377// Returns spv::Decoration(spv::BadValue) when no decoration
378// should be applied.
379spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
380{
381 if (qualifier.patch)
382 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700383 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600384 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700385 else if (qualifier.sample) {
386 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700388 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return (spv::Decoration)spv::BadValue;
390}
391
John Kessenich92187592016-02-01 13:45:25 -0700392// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700393spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600394{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationInvariant;
397 else
398 return (spv::Decoration)spv::BadValue;
399}
400
qining9220dbb2016-05-04 17:34:38 -0400401// If glslang type is noContraction, return SPIR-V NoContraction decoration.
402spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
403{
404 if (qualifier.noContraction)
405 return spv::DecorationNoContraction;
406 else
407 return (spv::Decoration)spv::BadValue;
408}
409
David Netoa901ffe2016-06-08 14:11:40 +0100410// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
411// associated capabilities when required. For some built-in variables, a capability
412// is generated only when using the variable in an executable instruction, but not when
413// just declaring a struct member variable with it. This is true for PointSize,
414// ClipDistance, and CullDistance.
415spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600416{
417 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700418 case glslang::EbvPointSize:
David Netoa901ffe2016-06-08 14:11:40 +0100419 // Defer adding the capability until the built-in is actually used.
420 if (!memberDeclaration) {
421 switch (glslangIntermediate->getStage()) {
422 case EShLangGeometry:
423 builder.addCapability(spv::CapabilityGeometryPointSize);
424 break;
425 case EShLangTessControl:
426 case EShLangTessEvaluation:
427 builder.addCapability(spv::CapabilityTessellationPointSize);
428 break;
429 default:
430 break;
431 }
John Kessenich92187592016-02-01 13:45:25 -0700432 }
433 return spv::BuiltInPointSize;
434
John Kessenichebb50532016-05-16 19:22:05 -0600435 // These *Distance capabilities logically belong here, but if the member is declared and
436 // then never used, consumers of SPIR-V prefer the capability not be declared.
437 // They are now generated when used, rather than here when declared.
438 // Potentially, the specification should be more clear what the minimum
439 // use needed is to trigger the capability.
440 //
John Kessenich92187592016-02-01 13:45:25 -0700441 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100442 if (!memberDeclaration)
443 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700444 return spv::BuiltInClipDistance;
445
446 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100447 if (!memberDeclaration)
448 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700449 return spv::BuiltInCullDistance;
450
451 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500452 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInViewportIndex;
454
John Kessenich5e801132016-02-15 11:09:46 -0700455 case glslang::EbvSampleId:
456 builder.addCapability(spv::CapabilitySampleRateShading);
457 return spv::BuiltInSampleId;
458
459 case glslang::EbvSamplePosition:
460 builder.addCapability(spv::CapabilitySampleRateShading);
461 return spv::BuiltInSamplePosition;
462
463 case glslang::EbvSampleMask:
464 builder.addCapability(spv::CapabilitySampleRateShading);
465 return spv::BuiltInSampleMask;
466
John Kessenich140f3df2015-06-26 16:58:36 -0600467 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600468 case glslang::EbvVertexId: return spv::BuiltInVertexId;
469 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700470 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
471 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600472 case glslang::EbvBaseVertex:
473 case glslang::EbvBaseInstance:
474 case glslang::EbvDrawId:
475 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600476 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600477 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600478 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
479 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
480 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600481 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
482 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
483 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
484 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
485 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
486 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
487 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600488 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
489 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
490 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
491 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
492 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
493 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
494 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
495 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800496 case glslang::EbvSubGroupSize:
497 case glslang::EbvSubGroupInvocation:
498 case glslang::EbvSubGroupEqMask:
499 case glslang::EbvSubGroupGeMask:
500 case glslang::EbvSubGroupGtMask:
501 case glslang::EbvSubGroupLeMask:
502 case glslang::EbvSubGroupLtMask:
503 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600504 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800505 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600506 default: return (spv::BuiltIn)spv::BadValue;
507 }
508}
509
Rex Xufc618912015-09-09 16:42:49 +0800510// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700511spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800512{
513 assert(type.getBasicType() == glslang::EbtSampler);
514
John Kessenich5d0fa972016-02-15 11:57:00 -0700515 // Check for capabilities
516 switch (type.getQualifier().layoutFormat) {
517 case glslang::ElfRg32f:
518 case glslang::ElfRg16f:
519 case glslang::ElfR11fG11fB10f:
520 case glslang::ElfR16f:
521 case glslang::ElfRgba16:
522 case glslang::ElfRgb10A2:
523 case glslang::ElfRg16:
524 case glslang::ElfRg8:
525 case glslang::ElfR16:
526 case glslang::ElfR8:
527 case glslang::ElfRgba16Snorm:
528 case glslang::ElfRg16Snorm:
529 case glslang::ElfRg8Snorm:
530 case glslang::ElfR16Snorm:
531 case glslang::ElfR8Snorm:
532
533 case glslang::ElfRg32i:
534 case glslang::ElfRg16i:
535 case glslang::ElfRg8i:
536 case glslang::ElfR16i:
537 case glslang::ElfR8i:
538
539 case glslang::ElfRgb10a2ui:
540 case glslang::ElfRg32ui:
541 case glslang::ElfRg16ui:
542 case glslang::ElfRg8ui:
543 case glslang::ElfR16ui:
544 case glslang::ElfR8ui:
545 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
546 break;
547
548 default:
549 break;
550 }
551
552 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800553 switch (type.getQualifier().layoutFormat) {
554 case glslang::ElfNone: return spv::ImageFormatUnknown;
555 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
556 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
557 case glslang::ElfR32f: return spv::ImageFormatR32f;
558 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
559 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
560 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
561 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
562 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
563 case glslang::ElfR16f: return spv::ImageFormatR16f;
564 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
565 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
566 case glslang::ElfRg16: return spv::ImageFormatRg16;
567 case glslang::ElfRg8: return spv::ImageFormatRg8;
568 case glslang::ElfR16: return spv::ImageFormatR16;
569 case glslang::ElfR8: return spv::ImageFormatR8;
570 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
571 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
572 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
573 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
574 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
575 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
576 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
577 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
578 case glslang::ElfR32i: return spv::ImageFormatR32i;
579 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
580 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
581 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
582 case glslang::ElfR16i: return spv::ImageFormatR16i;
583 case glslang::ElfR8i: return spv::ImageFormatR8i;
584 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
585 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
586 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
587 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
588 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
589 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
590 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
591 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
592 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
593 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
594 default: return (spv::ImageFormat)spv::BadValue;
595 }
596}
597
qining25262b32016-05-06 17:25:16 -0400598// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700599// descriptor set.
600bool IsDescriptorResource(const glslang::TType& type)
601{
John Kessenichf7497e22016-03-08 21:36:22 -0700602 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700603 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700604 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700605
606 // non block...
607 // basically samplerXXX/subpass/sampler/texture are all included
608 // if they are the global-scope-class, not the function parameter
609 // (or local, if they ever exist) class.
610 if (type.getBasicType() == glslang::EbtSampler)
611 return type.getQualifier().isUniformOrBuffer();
612
613 // None of the above.
614 return false;
615}
616
John Kesseniche0b6cad2015-12-24 10:30:13 -0700617void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
618{
619 if (child.layoutMatrix == glslang::ElmNone)
620 child.layoutMatrix = parent.layoutMatrix;
621
622 if (parent.invariant)
623 child.invariant = true;
624 if (parent.nopersp)
625 child.nopersp = true;
626 if (parent.flat)
627 child.flat = true;
628 if (parent.centroid)
629 child.centroid = true;
630 if (parent.patch)
631 child.patch = true;
632 if (parent.sample)
633 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800634 if (parent.coherent)
635 child.coherent = true;
636 if (parent.volatil)
637 child.volatil = true;
638 if (parent.restrict)
639 child.restrict = true;
640 if (parent.readonly)
641 child.readonly = true;
642 if (parent.writeonly)
643 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700644}
645
646bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
647{
John Kessenich7b9fa252016-01-21 18:56:57 -0700648 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700649 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600650 // - affect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700651 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600652 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700653}
654
John Kessenich140f3df2015-06-26 16:58:36 -0600655//
656// Implement the TGlslangToSpvTraverser class.
657//
658
Lei Zhang17535f72016-05-04 15:55:59 -0400659TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
660 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
661 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600662 inMain(false), mainTerminated(false), linkageOnly(false),
663 glslangIntermediate(glslangIntermediate)
664{
665 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
666
667 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700668 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600669 stdBuiltins = builder.import("GLSL.std.450");
670 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700671 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
672 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600673
674 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600675 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
676 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600677 builder.addSourceExtension(it->c_str());
678
679 // Add the top-level modes for this shader.
680
John Kessenich92187592016-02-01 13:45:25 -0700681 if (glslangIntermediate->getXfbMode()) {
682 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600683 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700684 }
John Kessenich140f3df2015-06-26 16:58:36 -0600685
686 unsigned int mode;
687 switch (glslangIntermediate->getStage()) {
688 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600689 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600690 break;
691
692 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600693 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600694 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
695 break;
696
697 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600698 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600699 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700700 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
701 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
702 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600703 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600704 }
705 if (mode != spv::BadValue)
706 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
707
John Kesseniche6903322015-10-13 16:29:02 -0600708 switch (glslangIntermediate->getVertexSpacing()) {
709 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
710 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
711 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
712 default: mode = spv::BadValue; break;
713 }
714 if (mode != spv::BadValue)
715 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
716
717 switch (glslangIntermediate->getVertexOrder()) {
718 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
719 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
720 default: mode = spv::BadValue; break;
721 }
722 if (mode != spv::BadValue)
723 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
724
725 if (glslangIntermediate->getPointMode())
726 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 break;
728
729 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600730 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600731 switch (glslangIntermediate->getInputPrimitive()) {
732 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
733 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
734 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700735 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600736 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
737 default: mode = spv::BadValue; break;
738 }
739 if (mode != spv::BadValue)
740 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600741
John Kessenich140f3df2015-06-26 16:58:36 -0600742 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
743
744 switch (glslangIntermediate->getOutputPrimitive()) {
745 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
746 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
747 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
748 default: mode = spv::BadValue; break;
749 }
750 if (mode != spv::BadValue)
751 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
752 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
753 break;
754
755 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600756 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600757 if (glslangIntermediate->getPixelCenterInteger())
758 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600759
John Kessenich140f3df2015-06-26 16:58:36 -0600760 if (glslangIntermediate->getOriginUpperLeft())
761 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600762 else
763 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600764
765 if (glslangIntermediate->getEarlyFragmentTests())
766 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
767
768 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600769 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
770 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
771 default: mode = spv::BadValue; break;
772 }
773 if (mode != spv::BadValue)
774 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
775
776 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
777 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600778 break;
779
780 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600781 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600782 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
783 glslangIntermediate->getLocalSize(1),
784 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600785 break;
786
787 default:
788 break;
789 }
790
791}
792
John Kessenich7ba63412015-12-20 17:37:07 -0700793// Finish everything and dump
794void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
795{
796 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100797 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
798 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700799
qiningda397332016-03-09 19:54:03 -0500800 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700801 builder.dump(out);
802}
803
John Kessenich140f3df2015-06-26 16:58:36 -0600804TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
805{
806 if (! mainTerminated) {
807 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
808 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600809 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600810 }
811}
812
813//
814// Implement the traversal functions.
815//
816// Return true from interior nodes to have the external traversal
817// continue on to children. Return false if children were
818// already processed.
819//
820
821//
qining25262b32016-05-06 17:25:16 -0400822// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600823// - uniform/input reads
824// - output writes
825// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
826// - something simple that degenerates into the last bullet
827//
828void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
829{
qining75d1d802016-04-06 14:42:01 -0400830 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
831 if (symbol->getType().getQualifier().isSpecConstant())
832 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834 // getSymbolId() will set up all the IO decorations on the first call.
835 // Formal function parameters were mapped during makeFunctions().
836 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700837
838 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
839 if (builder.isPointer(id)) {
840 spv::StorageClass sc = builder.getStorageClass(id);
841 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
842 iOSet.insert(id);
843 }
844
845 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700846 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600847 // Prepare to generate code for the access
848
849 // L-value chains will be computed left to right. We're on the symbol now,
850 // which is the left-most part of the access chain, so now is "clear" time,
851 // followed by setting the base.
852 builder.clearAccessChain();
853
854 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700855 // except for
856 // A) "const in" arguments to a function, which are an intermediate object.
857 // See comments in handleUserFunctionCall().
858 // B) Specialization constants (normal constant don't even come in as a variable),
859 // These are also pure R-values.
860 glslang::TQualifier qualifier = symbol->getQualifier();
861 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
862 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600863 builder.setAccessChainRValue(id);
864 else
865 builder.setAccessChainLValue(id);
866 }
867}
868
869bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
870{
qining40887662016-04-03 22:20:42 -0400871 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
872 if (node->getType().getQualifier().isSpecConstant())
873 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
874
John Kessenich140f3df2015-06-26 16:58:36 -0600875 // First, handle special cases
876 switch (node->getOp()) {
877 case glslang::EOpAssign:
878 case glslang::EOpAddAssign:
879 case glslang::EOpSubAssign:
880 case glslang::EOpMulAssign:
881 case glslang::EOpVectorTimesMatrixAssign:
882 case glslang::EOpVectorTimesScalarAssign:
883 case glslang::EOpMatrixTimesScalarAssign:
884 case glslang::EOpMatrixTimesMatrixAssign:
885 case glslang::EOpDivAssign:
886 case glslang::EOpModAssign:
887 case glslang::EOpAndAssign:
888 case glslang::EOpInclusiveOrAssign:
889 case glslang::EOpExclusiveOrAssign:
890 case glslang::EOpLeftShiftAssign:
891 case glslang::EOpRightShiftAssign:
892 // A bin-op assign "a += b" means the same thing as "a = a + b"
893 // where a is evaluated before b. For a simple assignment, GLSL
894 // says to evaluate the left before the right. So, always, left
895 // node then right node.
896 {
897 // get the left l-value, save it away
898 builder.clearAccessChain();
899 node->getLeft()->traverse(this);
900 spv::Builder::AccessChain lValue = builder.getAccessChain();
901
902 // evaluate the right
903 builder.clearAccessChain();
904 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700905 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600906
907 if (node->getOp() != glslang::EOpAssign) {
908 // the left is also an r-value
909 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700910 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600911
912 // do the operation
qining25262b32016-05-06 17:25:16 -0400913 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
914 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600915 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
916 node->getType().getBasicType());
917
918 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700919 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600920 }
921
922 // store the result
923 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800924 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600925
926 // assignments are expressions having an rValue after they are evaluated...
927 builder.clearAccessChain();
928 builder.setAccessChainRValue(rValue);
929 }
930 return false;
931 case glslang::EOpIndexDirect:
932 case glslang::EOpIndexDirectStruct:
933 {
934 // Get the left part of the access chain.
935 node->getLeft()->traverse(this);
936
937 // Add the next element in the chain
938
David Netoa901ffe2016-06-08 14:11:40 +0100939 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600940 if (! node->getLeft()->getType().isArray() &&
941 node->getLeft()->getType().isVector() &&
942 node->getOp() == glslang::EOpIndexDirect) {
943 // This is essentially a hard-coded vector swizzle of size 1,
944 // so short circuit the access-chain stuff with a swizzle.
945 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100946 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600947 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600948 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100949 int spvIndex = glslangIndex;
950 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
951 node->getOp() == glslang::EOpIndexDirectStruct)
952 {
953 // This may be, e.g., an anonymous block-member selection, which generally need
954 // index remapping due to hidden members in anonymous blocks.
955 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
956 assert(remapper.size() > 0);
957 spvIndex = remapper[glslangIndex];
958 }
John Kessenichebb50532016-05-16 19:22:05 -0600959
David Netoa901ffe2016-06-08 14:11:40 +0100960 // normal case for indexing array or structure or block
961 builder.accessChainPush(builder.makeIntConstant(spvIndex));
962
963 // Add capabilities here for accessing PointSize and clip/cull distance.
964 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600965 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100966 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600967 }
968 }
969 return false;
970 case glslang::EOpIndexIndirect:
971 {
972 // Structure or array or vector indirection.
973 // Will use native SPIR-V access-chain for struct and array indirection;
974 // matrices are arrays of vectors, so will also work for a matrix.
975 // Will use the access chain's 'component' for variable index into a vector.
976
977 // This adapter is building access chains left to right.
978 // Set up the access chain to the left.
979 node->getLeft()->traverse(this);
980
981 // save it so that computing the right side doesn't trash it
982 spv::Builder::AccessChain partial = builder.getAccessChain();
983
984 // compute the next index in the chain
985 builder.clearAccessChain();
986 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700987 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600988
989 // restore the saved access chain
990 builder.setAccessChain(partial);
991
992 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600993 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600994 else
John Kessenichfa668da2015-09-13 14:46:30 -0600995 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600996 }
997 return false;
998 case glslang::EOpVectorSwizzle:
999 {
1000 node->getLeft()->traverse(this);
1001 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
1002 std::vector<unsigned> swizzle;
1003 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1004 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -06001005 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001006 }
1007 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001008 case glslang::EOpLogicalOr:
1009 case glslang::EOpLogicalAnd:
1010 {
1011
1012 // These may require short circuiting, but can sometimes be done as straight
1013 // binary operations. The right operand must be short circuited if it has
1014 // side effects, and should probably be if it is complex.
1015 if (isTrivial(node->getRight()->getAsTyped()))
1016 break; // handle below as a normal binary operation
1017 // otherwise, we need to do dynamic short circuiting on the right operand
1018 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1019 builder.clearAccessChain();
1020 builder.setAccessChainRValue(result);
1021 }
1022 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001023 default:
1024 break;
1025 }
1026
1027 // Assume generic binary op...
1028
John Kessenich32cfd492016-02-02 12:37:46 -07001029 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001030 builder.clearAccessChain();
1031 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001032 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001033
John Kessenich32cfd492016-02-02 12:37:46 -07001034 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001035 builder.clearAccessChain();
1036 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001037 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001038
John Kessenich32cfd492016-02-02 12:37:46 -07001039 // get result
1040 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001041 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001042 convertGlslangToSpvType(node->getType()), left, right,
1043 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001044
John Kessenich50e57562015-12-21 21:21:11 -07001045 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001046 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001047 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001048 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001049 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001050 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001051 return false;
1052 }
John Kessenich140f3df2015-06-26 16:58:36 -06001053}
1054
1055bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1056{
qining40887662016-04-03 22:20:42 -04001057 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1058 if (node->getType().getQualifier().isSpecConstant())
1059 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1060
John Kessenichfc51d282015-08-19 13:34:18 -06001061 spv::Id result = spv::NoResult;
1062
1063 // try texturing first
1064 result = createImageTextureFunctionCall(node);
1065 if (result != spv::NoResult) {
1066 builder.clearAccessChain();
1067 builder.setAccessChainRValue(result);
1068
1069 return false; // done with this node
1070 }
1071
1072 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001073
1074 if (node->getOp() == glslang::EOpArrayLength) {
1075 // Quite special; won't want to evaluate the operand.
1076
1077 // Normal .length() would have been constant folded by the front-end.
1078 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001079 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001080 assert(node->getOperand()->getType().isRuntimeSizedArray());
1081 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1082 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001083 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1084 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001085
1086 builder.clearAccessChain();
1087 builder.setAccessChainRValue(length);
1088
1089 return false;
1090 }
1091
John Kessenichfc51d282015-08-19 13:34:18 -06001092 // Start by evaluating the operand
1093
John Kessenich140f3df2015-06-26 16:58:36 -06001094 builder.clearAccessChain();
1095 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001096
Rex Xufc618912015-09-09 16:42:49 +08001097 spv::Id operand = spv::NoResult;
1098
1099 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1100 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001101 node->getOp() == glslang::EOpAtomicCounter ||
1102 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001103 operand = builder.accessChainGetLValue(); // Special case l-value operands
1104 else
John Kessenich32cfd492016-02-02 12:37:46 -07001105 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001106
1107 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001108 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001109
1110 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001111 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001112 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001113
1114 // if not, then possibly an operation
1115 if (! result)
qining25262b32016-05-06 17:25:16 -04001116 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001117
1118 if (result) {
1119 builder.clearAccessChain();
1120 builder.setAccessChainRValue(result);
1121
1122 return false; // done with this node
1123 }
1124
1125 // it must be a special case, check...
1126 switch (node->getOp()) {
1127 case glslang::EOpPostIncrement:
1128 case glslang::EOpPostDecrement:
1129 case glslang::EOpPreIncrement:
1130 case glslang::EOpPreDecrement:
1131 {
1132 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001133 spv::Id one = 0;
1134 if (node->getBasicType() == glslang::EbtFloat)
1135 one = builder.makeFloatConstant(1.0F);
1136 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1137 one = builder.makeInt64Constant(1);
1138 else
1139 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001140 glslang::TOperator op;
1141 if (node->getOp() == glslang::EOpPreIncrement ||
1142 node->getOp() == glslang::EOpPostIncrement)
1143 op = glslang::EOpAdd;
1144 else
1145 op = glslang::EOpSub;
1146
qining25262b32016-05-06 17:25:16 -04001147 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1148 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001149 convertGlslangToSpvType(node->getType()), operand, one,
1150 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001151 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001152
1153 // The result of operation is always stored, but conditionally the
1154 // consumed result. The consumed result is always an r-value.
1155 builder.accessChainStore(result);
1156 builder.clearAccessChain();
1157 if (node->getOp() == glslang::EOpPreIncrement ||
1158 node->getOp() == glslang::EOpPreDecrement)
1159 builder.setAccessChainRValue(result);
1160 else
1161 builder.setAccessChainRValue(operand);
1162 }
1163
1164 return false;
1165
1166 case glslang::EOpEmitStreamVertex:
1167 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1168 return false;
1169 case glslang::EOpEndStreamPrimitive:
1170 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1171 return false;
1172
1173 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001174 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001175 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001176 }
John Kessenich140f3df2015-06-26 16:58:36 -06001177}
1178
1179bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1180{
qining27e04a02016-04-14 16:40:20 -04001181 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1182 if (node->getType().getQualifier().isSpecConstant())
1183 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1184
John Kessenichfc51d282015-08-19 13:34:18 -06001185 spv::Id result = spv::NoResult;
1186
1187 // try texturing
1188 result = createImageTextureFunctionCall(node);
1189 if (result != spv::NoResult) {
1190 builder.clearAccessChain();
1191 builder.setAccessChainRValue(result);
1192
1193 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001194 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001195 // "imageStore" is a special case, which has no result
1196 return false;
1197 }
John Kessenichfc51d282015-08-19 13:34:18 -06001198
John Kessenich140f3df2015-06-26 16:58:36 -06001199 glslang::TOperator binOp = glslang::EOpNull;
1200 bool reduceComparison = true;
1201 bool isMatrix = false;
1202 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001203 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001204
1205 assert(node->getOp());
1206
1207 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1208
1209 switch (node->getOp()) {
1210 case glslang::EOpSequence:
1211 {
1212 if (preVisit)
1213 ++sequenceDepth;
1214 else
1215 --sequenceDepth;
1216
1217 if (sequenceDepth == 1) {
1218 // If this is the parent node of all the functions, we want to see them
1219 // early, so all call points have actual SPIR-V functions to reference.
1220 // In all cases, still let the traverser visit the children for us.
1221 makeFunctions(node->getAsAggregate()->getSequence());
1222
1223 // Also, we want all globals initializers to go into the entry of main(), before
1224 // anything else gets there, so visit out of order, doing them all now.
1225 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1226
1227 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1228 // so do them manually.
1229 visitFunctions(node->getAsAggregate()->getSequence());
1230
1231 return false;
1232 }
1233
1234 return true;
1235 }
1236 case glslang::EOpLinkerObjects:
1237 {
1238 if (visit == glslang::EvPreVisit)
1239 linkageOnly = true;
1240 else
1241 linkageOnly = false;
1242
1243 return true;
1244 }
1245 case glslang::EOpComma:
1246 {
1247 // processing from left to right naturally leaves the right-most
1248 // lying around in the access chain
1249 glslang::TIntermSequence& glslangOperands = node->getSequence();
1250 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1251 glslangOperands[i]->traverse(this);
1252
1253 return false;
1254 }
1255 case glslang::EOpFunction:
1256 if (visit == glslang::EvPreVisit) {
1257 if (isShaderEntrypoint(node)) {
1258 inMain = true;
1259 builder.setBuildPoint(shaderEntry->getLastBlock());
1260 } else {
1261 handleFunctionEntry(node);
1262 }
1263 } else {
1264 if (inMain)
1265 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001266 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001267 inMain = false;
1268 }
1269
1270 return true;
1271 case glslang::EOpParameters:
1272 // Parameters will have been consumed by EOpFunction processing, but not
1273 // the body, so we still visited the function node's children, making this
1274 // child redundant.
1275 return false;
1276 case glslang::EOpFunctionCall:
1277 {
1278 if (node->isUserDefined())
1279 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001280 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1281 if (result) {
1282 builder.clearAccessChain();
1283 builder.setAccessChainRValue(result);
1284 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001285 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001286
1287 return false;
1288 }
1289 case glslang::EOpConstructMat2x2:
1290 case glslang::EOpConstructMat2x3:
1291 case glslang::EOpConstructMat2x4:
1292 case glslang::EOpConstructMat3x2:
1293 case glslang::EOpConstructMat3x3:
1294 case glslang::EOpConstructMat3x4:
1295 case glslang::EOpConstructMat4x2:
1296 case glslang::EOpConstructMat4x3:
1297 case glslang::EOpConstructMat4x4:
1298 case glslang::EOpConstructDMat2x2:
1299 case glslang::EOpConstructDMat2x3:
1300 case glslang::EOpConstructDMat2x4:
1301 case glslang::EOpConstructDMat3x2:
1302 case glslang::EOpConstructDMat3x3:
1303 case glslang::EOpConstructDMat3x4:
1304 case glslang::EOpConstructDMat4x2:
1305 case glslang::EOpConstructDMat4x3:
1306 case glslang::EOpConstructDMat4x4:
1307 isMatrix = true;
1308 // fall through
1309 case glslang::EOpConstructFloat:
1310 case glslang::EOpConstructVec2:
1311 case glslang::EOpConstructVec3:
1312 case glslang::EOpConstructVec4:
1313 case glslang::EOpConstructDouble:
1314 case glslang::EOpConstructDVec2:
1315 case glslang::EOpConstructDVec3:
1316 case glslang::EOpConstructDVec4:
1317 case glslang::EOpConstructBool:
1318 case glslang::EOpConstructBVec2:
1319 case glslang::EOpConstructBVec3:
1320 case glslang::EOpConstructBVec4:
1321 case glslang::EOpConstructInt:
1322 case glslang::EOpConstructIVec2:
1323 case glslang::EOpConstructIVec3:
1324 case glslang::EOpConstructIVec4:
1325 case glslang::EOpConstructUint:
1326 case glslang::EOpConstructUVec2:
1327 case glslang::EOpConstructUVec3:
1328 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001329 case glslang::EOpConstructInt64:
1330 case glslang::EOpConstructI64Vec2:
1331 case glslang::EOpConstructI64Vec3:
1332 case glslang::EOpConstructI64Vec4:
1333 case glslang::EOpConstructUint64:
1334 case glslang::EOpConstructU64Vec2:
1335 case glslang::EOpConstructU64Vec3:
1336 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001337 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001338 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001339 {
1340 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001341 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001342 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1343 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001344 if (node->getOp() == glslang::EOpConstructTextureSampler)
1345 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1346 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001347 std::vector<spv::Id> constituents;
1348 for (int c = 0; c < (int)arguments.size(); ++c)
1349 constituents.push_back(arguments[c]);
1350 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001351 } else if (isMatrix)
1352 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1353 else
1354 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 builder.clearAccessChain();
1357 builder.setAccessChainRValue(constructed);
1358
1359 return false;
1360 }
1361
1362 // These six are component-wise compares with component-wise results.
1363 // Forward on to createBinaryOperation(), requesting a vector result.
1364 case glslang::EOpLessThan:
1365 case glslang::EOpGreaterThan:
1366 case glslang::EOpLessThanEqual:
1367 case glslang::EOpGreaterThanEqual:
1368 case glslang::EOpVectorEqual:
1369 case glslang::EOpVectorNotEqual:
1370 {
1371 // Map the operation to a binary
1372 binOp = node->getOp();
1373 reduceComparison = false;
1374 switch (node->getOp()) {
1375 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1376 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1377 default: binOp = node->getOp(); break;
1378 }
1379
1380 break;
1381 }
1382 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001383 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001384 binOp = glslang::EOpMul;
1385 break;
1386 case glslang::EOpOuterProduct:
1387 // two vectors multiplied to make a matrix
1388 binOp = glslang::EOpOuterProduct;
1389 break;
1390 case glslang::EOpDot:
1391 {
qining25262b32016-05-06 17:25:16 -04001392 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001393 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001394 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001395 binOp = glslang::EOpMul;
1396 break;
1397 }
1398 case glslang::EOpMod:
1399 // when an aggregate, this is the floating-point mod built-in function,
1400 // which can be emitted by the one in createBinaryOperation()
1401 binOp = glslang::EOpMod;
1402 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001403 case glslang::EOpEmitVertex:
1404 case glslang::EOpEndPrimitive:
1405 case glslang::EOpBarrier:
1406 case glslang::EOpMemoryBarrier:
1407 case glslang::EOpMemoryBarrierAtomicCounter:
1408 case glslang::EOpMemoryBarrierBuffer:
1409 case glslang::EOpMemoryBarrierImage:
1410 case glslang::EOpMemoryBarrierShared:
1411 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001412 case glslang::EOpAllMemoryBarrierWithGroupSync:
1413 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1414 case glslang::EOpWorkgroupMemoryBarrier:
1415 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001416 noReturnValue = true;
1417 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1418 break;
1419
John Kessenich426394d2015-07-23 10:22:48 -06001420 case glslang::EOpAtomicAdd:
1421 case glslang::EOpAtomicMin:
1422 case glslang::EOpAtomicMax:
1423 case glslang::EOpAtomicAnd:
1424 case glslang::EOpAtomicOr:
1425 case glslang::EOpAtomicXor:
1426 case glslang::EOpAtomicExchange:
1427 case glslang::EOpAtomicCompSwap:
1428 atomic = true;
1429 break;
1430
John Kessenich140f3df2015-06-26 16:58:36 -06001431 default:
1432 break;
1433 }
1434
1435 //
1436 // See if it maps to a regular operation.
1437 //
John Kessenich140f3df2015-06-26 16:58:36 -06001438 if (binOp != glslang::EOpNull) {
1439 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1440 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1441 assert(left && right);
1442
1443 builder.clearAccessChain();
1444 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001445 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001446
1447 builder.clearAccessChain();
1448 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001449 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001450
qining25262b32016-05-06 17:25:16 -04001451 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1452 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001453 left->getType().getBasicType(), reduceComparison);
1454
1455 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001456 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001457 builder.clearAccessChain();
1458 builder.setAccessChainRValue(result);
1459
1460 return false;
1461 }
1462
John Kessenich426394d2015-07-23 10:22:48 -06001463 //
1464 // Create the list of operands.
1465 //
John Kessenich140f3df2015-06-26 16:58:36 -06001466 glslang::TIntermSequence& glslangOperands = node->getSequence();
1467 std::vector<spv::Id> operands;
1468 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1469 builder.clearAccessChain();
1470 glslangOperands[arg]->traverse(this);
1471
1472 // special case l-value operands; there are just a few
1473 bool lvalue = false;
1474 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001475 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001476 case glslang::EOpModf:
1477 if (arg == 1)
1478 lvalue = true;
1479 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001480 case glslang::EOpInterpolateAtSample:
1481 case glslang::EOpInterpolateAtOffset:
1482 if (arg == 0)
1483 lvalue = true;
1484 break;
Rex Xud4782c12015-09-06 16:30:11 +08001485 case glslang::EOpAtomicAdd:
1486 case glslang::EOpAtomicMin:
1487 case glslang::EOpAtomicMax:
1488 case glslang::EOpAtomicAnd:
1489 case glslang::EOpAtomicOr:
1490 case glslang::EOpAtomicXor:
1491 case glslang::EOpAtomicExchange:
1492 case glslang::EOpAtomicCompSwap:
1493 if (arg == 0)
1494 lvalue = true;
1495 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001496 case glslang::EOpAddCarry:
1497 case glslang::EOpSubBorrow:
1498 if (arg == 2)
1499 lvalue = true;
1500 break;
1501 case glslang::EOpUMulExtended:
1502 case glslang::EOpIMulExtended:
1503 if (arg >= 2)
1504 lvalue = true;
1505 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001506 default:
1507 break;
1508 }
1509 if (lvalue)
1510 operands.push_back(builder.accessChainGetLValue());
1511 else
John Kessenich32cfd492016-02-02 12:37:46 -07001512 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001513 }
John Kessenich426394d2015-07-23 10:22:48 -06001514
1515 if (atomic) {
1516 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001517 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001518 } else {
1519 // Pass through to generic operations.
1520 switch (glslangOperands.size()) {
1521 case 0:
1522 result = createNoArgOperation(node->getOp());
1523 break;
1524 case 1:
qining25262b32016-05-06 17:25:16 -04001525 result = createUnaryOperation(
1526 node->getOp(), precision,
1527 TranslateNoContractionDecoration(node->getType().getQualifier()),
1528 convertGlslangToSpvType(node->getType()), operands.front(),
1529 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001530 break;
1531 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001532 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001533 break;
1534 }
John Kessenich140f3df2015-06-26 16:58:36 -06001535 }
1536
1537 if (noReturnValue)
1538 return false;
1539
1540 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001541 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001542 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001543 } else {
1544 builder.clearAccessChain();
1545 builder.setAccessChainRValue(result);
1546 return false;
1547 }
1548}
1549
1550bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1551{
1552 // This path handles both if-then-else and ?:
1553 // The if-then-else has a node type of void, while
1554 // ?: has a non-void node type
1555 spv::Id result = 0;
1556 if (node->getBasicType() != glslang::EbtVoid) {
1557 // don't handle this as just on-the-fly temporaries, because there will be two names
1558 // and better to leave SSA to later passes
1559 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1560 }
1561
1562 // emit the condition before doing anything with selection
1563 node->getCondition()->traverse(this);
1564
1565 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001566 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001567
1568 if (node->getTrueBlock()) {
1569 // emit the "then" statement
1570 node->getTrueBlock()->traverse(this);
1571 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001572 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001573 }
1574
1575 if (node->getFalseBlock()) {
1576 ifBuilder.makeBeginElse();
1577 // emit the "else" statement
1578 node->getFalseBlock()->traverse(this);
1579 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001580 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001581 }
1582
1583 ifBuilder.makeEndIf();
1584
1585 if (result) {
1586 // GLSL only has r-values as the result of a :?, but
1587 // if we have an l-value, that can be more efficient if it will
1588 // become the base of a complex r-value expression, because the
1589 // next layer copies r-values into memory to use the access-chain mechanism
1590 builder.clearAccessChain();
1591 builder.setAccessChainLValue(result);
1592 }
1593
1594 return false;
1595}
1596
1597bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1598{
1599 // emit and get the condition before doing anything with switch
1600 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001601 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001602
1603 // browse the children to sort out code segments
1604 int defaultSegment = -1;
1605 std::vector<TIntermNode*> codeSegments;
1606 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1607 std::vector<int> caseValues;
1608 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1609 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1610 TIntermNode* child = *c;
1611 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001612 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001613 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001614 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001615 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1616 } else
1617 codeSegments.push_back(child);
1618 }
1619
qining25262b32016-05-06 17:25:16 -04001620 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001621 // statements between the last case and the end of the switch statement
1622 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1623 (int)codeSegments.size() == defaultSegment)
1624 codeSegments.push_back(nullptr);
1625
1626 // make the switch statement
1627 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001628 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001629
1630 // emit all the code in the segments
1631 breakForLoop.push(false);
1632 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1633 builder.nextSwitchSegment(segmentBlocks, s);
1634 if (codeSegments[s])
1635 codeSegments[s]->traverse(this);
1636 else
1637 builder.addSwitchBreak();
1638 }
1639 breakForLoop.pop();
1640
1641 builder.endSwitch(segmentBlocks);
1642
1643 return false;
1644}
1645
1646void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1647{
1648 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001649 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001650
1651 builder.clearAccessChain();
1652 builder.setAccessChainRValue(constant);
1653}
1654
1655bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1656{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001657 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001658 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001659 // Spec requires back edges to target header blocks, and every header block
1660 // must dominate its merge block. Make a header block first to ensure these
1661 // conditions are met. By definition, it will contain OpLoopMerge, followed
1662 // by a block-ending branch. But we don't want to put any other body/test
1663 // instructions in it, since the body/test may have arbitrary instructions,
1664 // including merges of its own.
1665 builder.setBuildPoint(&blocks.head);
1666 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001667 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001668 spv::Block& test = builder.makeNewBlock();
1669 builder.createBranch(&test);
1670
1671 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001672 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001673 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001674 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001675 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1676
1677 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001678 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001679 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001680 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001681 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001682 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001683
1684 builder.setBuildPoint(&blocks.continue_target);
1685 if (node->getTerminal())
1686 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001687 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001688 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001689 builder.createBranch(&blocks.body);
1690
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001691 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001692 builder.setBuildPoint(&blocks.body);
1693 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001694 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001695 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001696 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001697
1698 builder.setBuildPoint(&blocks.continue_target);
1699 if (node->getTerminal())
1700 node->getTerminal()->traverse(this);
1701 if (node->getTest()) {
1702 node->getTest()->traverse(this);
1703 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001704 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001705 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001706 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001707 // TODO: unless there was a break/return/discard instruction
1708 // somewhere in the body, this is an infinite loop, so we should
1709 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001710 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001711 }
John Kessenich140f3df2015-06-26 16:58:36 -06001712 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001713 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001714 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001715 return false;
1716}
1717
1718bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1719{
1720 if (node->getExpression())
1721 node->getExpression()->traverse(this);
1722
1723 switch (node->getFlowOp()) {
1724 case glslang::EOpKill:
1725 builder.makeDiscard();
1726 break;
1727 case glslang::EOpBreak:
1728 if (breakForLoop.top())
1729 builder.createLoopExit();
1730 else
1731 builder.addSwitchBreak();
1732 break;
1733 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001734 builder.createLoopContinue();
1735 break;
1736 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001737 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001738 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001739 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001740 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001741
1742 builder.clearAccessChain();
1743 break;
1744
1745 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001746 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001747 break;
1748 }
1749
1750 return false;
1751}
1752
1753spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1754{
qining25262b32016-05-06 17:25:16 -04001755 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001756 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001757 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001758 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001759 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001760 }
1761
1762 // Now, handle actual variables
1763 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1764 spv::Id spvType = convertGlslangToSpvType(node->getType());
1765
1766 const char* name = node->getName().c_str();
1767 if (glslang::IsAnonymous(name))
1768 name = "";
1769
1770 return builder.createVariable(storageClass, spvType, name);
1771}
1772
1773// Return type Id of the sampled type.
1774spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1775{
1776 switch (sampler.type) {
1777 case glslang::EbtFloat: return builder.makeFloatType(32);
1778 case glslang::EbtInt: return builder.makeIntType(32);
1779 case glslang::EbtUint: return builder.makeUintType(32);
1780 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001781 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001782 return builder.makeFloatType(32);
1783 }
1784}
1785
John Kessenich3ac051e2015-12-20 11:29:16 -07001786// Convert from a glslang type to an SPV type, by calling into a
1787// recursive version of this function. This establishes the inherited
1788// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001789spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1790{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001791 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001792}
1793
1794// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001795// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001796// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001797spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001798{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001799 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001800
1801 switch (type.getBasicType()) {
1802 case glslang::EbtVoid:
1803 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001804 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001805 break;
1806 case glslang::EbtFloat:
1807 spvType = builder.makeFloatType(32);
1808 break;
1809 case glslang::EbtDouble:
1810 spvType = builder.makeFloatType(64);
1811 break;
1812 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001813 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1814 // a 32-bit int where non-0 means true.
1815 if (explicitLayout != glslang::ElpNone)
1816 spvType = builder.makeUintType(32);
1817 else
1818 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001819 break;
1820 case glslang::EbtInt:
1821 spvType = builder.makeIntType(32);
1822 break;
1823 case glslang::EbtUint:
1824 spvType = builder.makeUintType(32);
1825 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001826 case glslang::EbtInt64:
1827 builder.addCapability(spv::CapabilityInt64);
1828 spvType = builder.makeIntType(64);
1829 break;
1830 case glslang::EbtUint64:
1831 builder.addCapability(spv::CapabilityInt64);
1832 spvType = builder.makeUintType(64);
1833 break;
John Kessenich426394d2015-07-23 10:22:48 -06001834 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001835 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 -06001836 spvType = builder.makeUintType(32);
1837 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001838 case glslang::EbtSampler:
1839 {
1840 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001841 if (sampler.sampler) {
1842 // pure sampler
1843 spvType = builder.makeSamplerType();
1844 } else {
1845 // an image is present, make its type
1846 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1847 sampler.image ? 2 : 1, TranslateImageFormat(type));
1848 if (sampler.combined) {
1849 // already has both image and sampler, make the combined type
1850 spvType = builder.makeSampledImageType(spvType);
1851 }
John Kessenich55e7d112015-11-15 21:33:39 -07001852 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001853 }
John Kessenich140f3df2015-06-26 16:58:36 -06001854 break;
1855 case glslang::EbtStruct:
1856 case glslang::EbtBlock:
1857 {
1858 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001859 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001860
1861 // Try to share structs for different layouts, but not yet for other
1862 // kinds of qualification (primarily not yet including interpolant qualification).
1863 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001864 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001865 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001866 break;
1867
1868 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001869 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001870 memberRemapper[glslangMembers].resize(glslangMembers->size());
1871 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001872 }
1873 break;
1874 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001875 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001876 break;
1877 }
1878
1879 if (type.isMatrix())
1880 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1881 else {
1882 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1883 if (type.getVectorSize() > 1)
1884 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1885 }
1886
1887 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001888 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1889
John Kessenichc9a80832015-09-12 12:17:44 -06001890 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001891 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001892 // We need to decorate array strides for types needing explicit layout, except blocks.
1893 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001894 // Use a dummy glslang type for querying internal strides of
1895 // arrays of arrays, but using just a one-dimensional array.
1896 glslang::TType simpleArrayType(type, 0); // deference type of the array
1897 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1898 simpleArrayType.getArraySizes().dereference();
1899
1900 // Will compute the higher-order strides here, rather than making a whole
1901 // pile of types and doing repetitive recursion on their contents.
1902 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1903 }
John Kessenichf8842e52016-01-04 19:22:56 -07001904
1905 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001906 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001907 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001908 if (stride > 0)
1909 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001910 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001911 }
1912 } else {
1913 // single-dimensional array, and don't yet have stride
1914
John Kessenichf8842e52016-01-04 19:22:56 -07001915 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001916 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1917 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001918 }
John Kessenich31ed4832015-09-09 17:51:38 -06001919
John Kessenichc9a80832015-09-12 12:17:44 -06001920 // Do the outer dimension, which might not be known for a runtime-sized array
1921 if (type.isRuntimeSizedArray()) {
1922 spvType = builder.makeRuntimeArray(spvType);
1923 } else {
1924 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001925 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001926 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001927 if (stride > 0)
1928 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001929 }
1930
1931 return spvType;
1932}
1933
John Kessenich6090df02016-06-30 21:18:02 -06001934
1935// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
1936// explicitLayout can be kept the same throughout the hierarchical recursive walk.
1937// Mutually recursive with convertGlslangToSpvType().
1938spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
1939 const glslang::TTypeList* glslangMembers,
1940 glslang::TLayoutPacking explicitLayout,
1941 const glslang::TQualifier& qualifier)
1942{
1943 // Create a vector of struct types for SPIR-V to consume
1944 std::vector<spv::Id> spvMembers;
1945 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1946 int locationOffset = 0; // for use across struct members, when they are called recursively
1947 for (int i = 0; i < (int)glslangMembers->size(); i++) {
1948 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
1949 if (glslangMember.hiddenMember()) {
1950 ++memberDelta;
1951 if (type.getBasicType() == glslang::EbtBlock)
1952 memberRemapper[glslangMembers][i] = -1;
1953 } else {
1954 if (type.getBasicType() == glslang::EbtBlock)
1955 memberRemapper[glslangMembers][i] = i - memberDelta;
1956 // modify just this child's view of the qualifier
1957 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
1958 InheritQualifiers(memberQualifier, qualifier);
1959
1960 // manually inherit location; it's more complex
1961 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
1962 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1963 if (qualifier.hasLocation())
1964 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
1965
1966 // recurse
1967 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
1968 }
1969 }
1970
1971 // Make the SPIR-V type
1972 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
1973 if (! HasNonLayoutQualifiers(qualifier))
1974 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
1975
1976 // Decorate it
1977 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
1978
1979 return spvType;
1980}
1981
1982void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
1983 const glslang::TTypeList* glslangMembers,
1984 glslang::TLayoutPacking explicitLayout,
1985 const glslang::TQualifier& qualifier,
1986 spv::Id spvType)
1987{
1988 // Name and decorate the non-hidden members
1989 int offset = -1;
1990 int locationOffset = 0; // for use within the members of this struct
1991 for (int i = 0; i < (int)glslangMembers->size(); i++) {
1992 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
1993 int member = i;
1994 if (type.getBasicType() == glslang::EbtBlock)
1995 member = memberRemapper[glslangMembers][i];
1996
1997 // modify just this child's view of the qualifier
1998 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
1999 InheritQualifiers(memberQualifier, qualifier);
2000
2001 // using -1 above to indicate a hidden member
2002 if (member >= 0) {
2003 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2004 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2005 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2006 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2007 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2008 if (type.getBasicType() == glslang::EbtBlock) {
2009 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2010 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2011 }
2012 }
2013 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2014
2015 if (qualifier.storage == glslang::EvqBuffer) {
2016 std::vector<spv::Decoration> memory;
2017 TranslateMemoryDecoration(memberQualifier, memory);
2018 for (unsigned int i = 0; i < memory.size(); ++i)
2019 addMemberDecoration(spvType, member, memory[i]);
2020 }
2021
2022 // compute location decoration; tricky based on whether inheritance is at play
2023 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2024 // probably move to the linker stage of the front end proper, and just have the
2025 // answer sitting already distributed throughout the individual member locations.
2026 int location = -1; // will only decorate if present or inherited
2027 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2028 // struct members should not have explicit locations
2029 assert(type.getBasicType() != glslang::EbtStruct);
2030 location = memberQualifier.layoutLocation;
2031 } else if (type.getBasicType() != glslang::EbtBlock) {
2032 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2033 // The members, and their nested types, must not themselves have Location decorations.
2034 } else if (qualifier.hasLocation()) // inheritance
2035 location = qualifier.layoutLocation + locationOffset;
2036 if (qualifier.hasLocation()) // track for upcoming inheritance
2037 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2038 if (location >= 0)
2039 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2040
2041 // component, XFB, others
2042 if (glslangMember.getQualifier().hasComponent())
2043 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2044 if (glslangMember.getQualifier().hasXfbOffset())
2045 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2046 else if (explicitLayout != glslang::ElpNone) {
2047 // figure out what to do with offset, which is accumulating
2048 int nextOffset;
2049 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2050 if (offset >= 0)
2051 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2052 offset = nextOffset;
2053 }
2054
2055 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2056 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2057
2058 // built-in variable decorations
2059 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2060 if (builtIn != spv::BadValue)
2061 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2062 }
2063 }
2064
2065 // Decorate the structure
2066 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2067 addDecoration(spvType, TranslateBlockDecoration(type));
2068 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2069 builder.addCapability(spv::CapabilityGeometryStreams);
2070 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2071 }
2072 if (glslangIntermediate->getXfbMode()) {
2073 builder.addCapability(spv::CapabilityTransformFeedback);
2074 if (type.getQualifier().hasXfbStride())
2075 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2076 if (type.getQualifier().hasXfbBuffer())
2077 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2078 }
2079}
2080
John Kessenich6c292d32016-02-15 20:58:50 -07002081// Turn the expression forming the array size into an id.
2082// This is not quite trivial, because of specialization constants.
2083// Sometimes, a raw constant is turned into an Id, and sometimes
2084// a specialization constant expression is.
2085spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2086{
2087 // First, see if this is sized with a node, meaning a specialization constant:
2088 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2089 if (specNode != nullptr) {
2090 builder.clearAccessChain();
2091 specNode->traverse(this);
2092 return accessChainLoad(specNode->getAsTyped()->getType());
2093 }
qining25262b32016-05-06 17:25:16 -04002094
John Kessenich6c292d32016-02-15 20:58:50 -07002095 // Otherwise, need a compile-time (front end) size, get it:
2096 int size = arraySizes.getDimSize(dim);
2097 assert(size > 0);
2098 return builder.makeUintConstant(size);
2099}
2100
John Kessenich103bef92016-02-08 21:38:15 -07002101// Wrap the builder's accessChainLoad to:
2102// - localize handling of RelaxedPrecision
2103// - use the SPIR-V inferred type instead of another conversion of the glslang type
2104// (avoids unnecessary work and possible type punning for structures)
2105// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002106spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2107{
John Kessenich103bef92016-02-08 21:38:15 -07002108 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2109 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2110
2111 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002112 if (type.getBasicType() == glslang::EbtBool) {
2113 if (builder.isScalarType(nominalTypeId)) {
2114 // Conversion for bool
2115 spv::Id boolType = builder.makeBoolType();
2116 if (nominalTypeId != boolType)
2117 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2118 } else if (builder.isVectorType(nominalTypeId)) {
2119 // Conversion for bvec
2120 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2121 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2122 if (nominalTypeId != bvecType)
2123 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2124 }
2125 }
John Kessenich103bef92016-02-08 21:38:15 -07002126
2127 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002128}
2129
Rex Xu27253232016-02-23 17:51:09 +08002130// Wrap the builder's accessChainStore to:
2131// - do conversion of concrete to abstract type
2132void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2133{
2134 // Need to convert to abstract types when necessary
2135 if (type.getBasicType() == glslang::EbtBool) {
2136 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2137
2138 if (builder.isScalarType(nominalTypeId)) {
2139 // Conversion for bool
2140 spv::Id boolType = builder.makeBoolType();
2141 if (nominalTypeId != boolType) {
2142 spv::Id zero = builder.makeUintConstant(0);
2143 spv::Id one = builder.makeUintConstant(1);
2144 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2145 }
2146 } else if (builder.isVectorType(nominalTypeId)) {
2147 // Conversion for bvec
2148 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2149 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2150 if (nominalTypeId != bvecType) {
2151 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2152 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2153 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2154 }
2155 }
2156 }
2157
2158 builder.accessChainStore(rvalue);
2159}
2160
John Kessenichf85e8062015-12-19 13:57:10 -07002161// Decide whether or not this type should be
2162// decorated with offsets and strides, and if so
2163// whether std140 or std430 rules should be applied.
2164glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002165{
John Kessenichf85e8062015-12-19 13:57:10 -07002166 // has to be a block
2167 if (type.getBasicType() != glslang::EbtBlock)
2168 return glslang::ElpNone;
2169
2170 // has to be a uniform or buffer block
2171 if (type.getQualifier().storage != glslang::EvqUniform &&
2172 type.getQualifier().storage != glslang::EvqBuffer)
2173 return glslang::ElpNone;
2174
2175 // return the layout to use
2176 switch (type.getQualifier().layoutPacking) {
2177 case glslang::ElpStd140:
2178 case glslang::ElpStd430:
2179 return type.getQualifier().layoutPacking;
2180 default:
2181 return glslang::ElpNone;
2182 }
John Kessenich31ed4832015-09-09 17:51:38 -06002183}
2184
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002185// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002186int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002187{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002188 int size;
John Kessenich49987892015-12-29 17:11:44 -07002189 int stride;
2190 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002191
2192 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002193}
2194
John Kessenich49987892015-12-29 17:11:44 -07002195// 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 -07002196// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002197int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002198{
John Kessenich49987892015-12-29 17:11:44 -07002199 glslang::TType elementType;
2200 elementType.shallowCopy(matrixType);
2201 elementType.clearArraySizes();
2202
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002203 int size;
John Kessenich49987892015-12-29 17:11:44 -07002204 int stride;
2205 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2206
2207 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002208}
2209
John Kessenich5e4b1242015-08-06 22:53:06 -06002210// Given a member type of a struct, realign the current offset for it, and compute
2211// the next (not yet aligned) offset for the next member, which will get aligned
2212// on the next call.
2213// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2214// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2215// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002216void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002217 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002218{
2219 // this will get a positive value when deemed necessary
2220 nextOffset = -1;
2221
John Kessenich5e4b1242015-08-06 22:53:06 -06002222 // override anything in currentOffset with user-set offset
2223 if (memberType.getQualifier().hasOffset())
2224 currentOffset = memberType.getQualifier().layoutOffset;
2225
2226 // It could be that current linker usage in glslang updated all the layoutOffset,
2227 // in which case the following code does not matter. But, that's not quite right
2228 // once cross-compilation unit GLSL validation is done, as the original user
2229 // settings are needed in layoutOffset, and then the following will come into play.
2230
John Kessenichf85e8062015-12-19 13:57:10 -07002231 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002232 if (! memberType.getQualifier().hasOffset())
2233 currentOffset = -1;
2234
2235 return;
2236 }
2237
John Kessenichf85e8062015-12-19 13:57:10 -07002238 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002239 if (currentOffset < 0)
2240 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002241
John Kessenich5e4b1242015-08-06 22:53:06 -06002242 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2243 // but possibly not yet correctly aligned.
2244
2245 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002246 int dummyStride;
2247 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002248 glslang::RoundToPow2(currentOffset, memberAlignment);
2249 nextOffset = currentOffset + memberSize;
2250}
2251
David Netoa901ffe2016-06-08 14:11:40 +01002252void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002253{
David Netoa901ffe2016-06-08 14:11:40 +01002254 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2255 switch (glslangBuiltIn)
2256 {
2257 case glslang::EbvClipDistance:
2258 case glslang::EbvCullDistance:
2259 case glslang::EbvPointSize:
2260 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2261 // Alternately, we could just call this for any glslang built-in, since the
2262 // capability already guards against duplicates.
2263 TranslateBuiltInDecoration(glslangBuiltIn, false);
2264 break;
2265 default:
2266 // Capabilities were already generated when the struct was declared.
2267 break;
2268 }
John Kessenichebb50532016-05-16 19:22:05 -06002269}
2270
John Kessenich140f3df2015-06-26 16:58:36 -06002271bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2272{
John Kessenich4d65ee32016-03-12 18:17:47 -07002273 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002274 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002275 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002276}
2277
2278// Make all the functions, skeletally, without actually visiting their bodies.
2279void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2280{
2281 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2282 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2283 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2284 continue;
2285
2286 // We're on a user function. Set up the basic interface for the function now,
2287 // so that it's available to call.
2288 // Translating the body will happen later.
2289 //
qining25262b32016-05-06 17:25:16 -04002290 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002291 // function. What it is an address of varies:
2292 //
2293 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2294 // so that write needs to be to a copy, hence the address of a copy works.
2295 //
2296 // - "const in" parameters can just be the r-value, as no writes need occur.
2297 //
2298 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2299 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2300
2301 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002302 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002303 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2304
2305 for (int p = 0; p < (int)parameters.size(); ++p) {
2306 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2307 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002308 if (paramType.isOpaque())
2309 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2310 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002311 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2312 else
2313 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002314 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002315 paramTypes.push_back(typeId);
2316 }
2317
2318 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002319 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2320 convertGlslangToSpvType(glslFunction->getType()),
2321 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002322
2323 // Track function to emit/call later
2324 functionMap[glslFunction->getName().c_str()] = function;
2325
2326 // Set the parameter id's
2327 for (int p = 0; p < (int)parameters.size(); ++p) {
2328 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2329 // give a name too
2330 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2331 }
2332 }
2333}
2334
2335// Process all the initializers, while skipping the functions and link objects
2336void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2337{
2338 builder.setBuildPoint(shaderEntry->getLastBlock());
2339 for (int i = 0; i < (int)initializers.size(); ++i) {
2340 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2341 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2342
2343 // We're on a top-level node that's not a function. Treat as an initializer, whose
2344 // code goes into the beginning of main.
2345 initializer->traverse(this);
2346 }
2347 }
2348}
2349
2350// Process all the functions, while skipping initializers.
2351void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2352{
2353 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2354 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2355 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2356 node->traverse(this);
2357 }
2358}
2359
2360void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2361{
qining25262b32016-05-06 17:25:16 -04002362 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002363 // that called makeFunctions().
2364 spv::Function* function = functionMap[node->getName().c_str()];
2365 spv::Block* functionBlock = function->getEntryBlock();
2366 builder.setBuildPoint(functionBlock);
2367}
2368
Rex Xu04db3f52015-09-16 11:44:02 +08002369void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002370{
Rex Xufc618912015-09-09 16:42:49 +08002371 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002372
2373 glslang::TSampler sampler = {};
2374 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002375 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002376 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2377 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2378 }
2379
John Kessenich140f3df2015-06-26 16:58:36 -06002380 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2381 builder.clearAccessChain();
2382 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002383
2384 // Special case l-value operands
2385 bool lvalue = false;
2386 switch (node.getOp()) {
2387 case glslang::EOpImageAtomicAdd:
2388 case glslang::EOpImageAtomicMin:
2389 case glslang::EOpImageAtomicMax:
2390 case glslang::EOpImageAtomicAnd:
2391 case glslang::EOpImageAtomicOr:
2392 case glslang::EOpImageAtomicXor:
2393 case glslang::EOpImageAtomicExchange:
2394 case glslang::EOpImageAtomicCompSwap:
2395 if (i == 0)
2396 lvalue = true;
2397 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002398 case glslang::EOpSparseImageLoad:
2399 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2400 lvalue = true;
2401 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002402 case glslang::EOpSparseTexture:
2403 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2404 lvalue = true;
2405 break;
2406 case glslang::EOpSparseTextureClamp:
2407 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2408 lvalue = true;
2409 break;
2410 case glslang::EOpSparseTextureLod:
2411 case glslang::EOpSparseTextureOffset:
2412 if (i == 3)
2413 lvalue = true;
2414 break;
2415 case glslang::EOpSparseTextureFetch:
2416 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2417 lvalue = true;
2418 break;
2419 case glslang::EOpSparseTextureFetchOffset:
2420 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2421 lvalue = true;
2422 break;
2423 case glslang::EOpSparseTextureLodOffset:
2424 case glslang::EOpSparseTextureGrad:
2425 case glslang::EOpSparseTextureOffsetClamp:
2426 if (i == 4)
2427 lvalue = true;
2428 break;
2429 case glslang::EOpSparseTextureGradOffset:
2430 case glslang::EOpSparseTextureGradClamp:
2431 if (i == 5)
2432 lvalue = true;
2433 break;
2434 case glslang::EOpSparseTextureGradOffsetClamp:
2435 if (i == 6)
2436 lvalue = true;
2437 break;
2438 case glslang::EOpSparseTextureGather:
2439 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2440 lvalue = true;
2441 break;
2442 case glslang::EOpSparseTextureGatherOffset:
2443 case glslang::EOpSparseTextureGatherOffsets:
2444 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2445 lvalue = true;
2446 break;
Rex Xufc618912015-09-09 16:42:49 +08002447 default:
2448 break;
2449 }
2450
Rex Xu6b86d492015-09-16 17:48:22 +08002451 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002452 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002453 else
John Kessenich32cfd492016-02-02 12:37:46 -07002454 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002455 }
2456}
2457
John Kessenichfc51d282015-08-19 13:34:18 -06002458void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002459{
John Kessenichfc51d282015-08-19 13:34:18 -06002460 builder.clearAccessChain();
2461 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002462 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002463}
John Kessenich140f3df2015-06-26 16:58:36 -06002464
John Kessenichfc51d282015-08-19 13:34:18 -06002465spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2466{
Rex Xufc618912015-09-09 16:42:49 +08002467 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002468 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002469 }
2470
John Kessenichfc51d282015-08-19 13:34:18 -06002471 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002472 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2473 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2474 std::vector<spv::Id> arguments;
2475 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002476 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002477 else
2478 translateArguments(*node->getAsUnaryNode(), arguments);
2479 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2480
2481 spv::Builder::TextureParameters params = { };
2482 params.sampler = arguments[0];
2483
Rex Xu04db3f52015-09-16 11:44:02 +08002484 glslang::TCrackedTextureOp cracked;
2485 node->crackTexture(sampler, cracked);
2486
John Kessenichfc51d282015-08-19 13:34:18 -06002487 // Check for queries
2488 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002489 // a sampled image needs to have the image extracted first
2490 if (builder.isSampledImage(params.sampler))
2491 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002492 switch (node->getOp()) {
2493 case glslang::EOpImageQuerySize:
2494 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002495 if (arguments.size() > 1) {
2496 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002497 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002498 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002499 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002500 case glslang::EOpImageQuerySamples:
2501 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002502 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002503 case glslang::EOpTextureQueryLod:
2504 params.coords = arguments[1];
2505 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2506 case glslang::EOpTextureQueryLevels:
2507 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002508 case glslang::EOpSparseTexelsResident:
2509 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002510 default:
2511 assert(0);
2512 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002513 }
John Kessenich140f3df2015-06-26 16:58:36 -06002514 }
2515
Rex Xufc618912015-09-09 16:42:49 +08002516 // Check for image functions other than queries
2517 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002518 std::vector<spv::Id> operands;
2519 auto opIt = arguments.begin();
2520 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002521
2522 // Handle subpass operations
2523 // TODO: GLSL should change to have the "MS" only on the type rather than the
2524 // built-in function.
2525 if (cracked.subpass) {
2526 // add on the (0,0) coordinate
2527 spv::Id zero = builder.makeIntConstant(0);
2528 std::vector<spv::Id> comps;
2529 comps.push_back(zero);
2530 comps.push_back(zero);
2531 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2532 if (sampler.ms) {
2533 operands.push_back(spv::ImageOperandsSampleMask);
2534 operands.push_back(*(opIt++));
2535 }
2536 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2537 }
2538
John Kessenich56bab042015-09-16 10:54:31 -06002539 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002540 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002541 if (sampler.ms) {
2542 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002543 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002544 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002545 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2546 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002547 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002548 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002549 if (sampler.ms) {
2550 operands.push_back(*(opIt + 1));
2551 operands.push_back(spv::ImageOperandsSampleMask);
2552 operands.push_back(*opIt);
2553 } else
2554 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002555 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002556 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2557 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002558 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002559 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2560 builder.addCapability(spv::CapabilitySparseResidency);
2561 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2562 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2563
2564 if (sampler.ms) {
2565 operands.push_back(spv::ImageOperandsSampleMask);
2566 operands.push_back(*opIt++);
2567 }
2568
2569 // Create the return type that was a special structure
2570 spv::Id texelOut = *opIt;
2571 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2572 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2573 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2574
2575 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2576
2577 // Decode the return type
2578 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2579 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002580 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002581 // Process image atomic operations
2582
2583 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2584 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002585 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002586
Rex Xufc618912015-09-09 16:42:49 +08002587 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002588 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002589
2590 std::vector<spv::Id> operands;
2591 operands.push_back(pointer);
2592 for (; opIt != arguments.end(); ++opIt)
2593 operands.push_back(*opIt);
2594
Rex Xu04db3f52015-09-16 11:44:02 +08002595 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002596 }
2597 }
2598
2599 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002600 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002601 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2602
John Kessenichfc51d282015-08-19 13:34:18 -06002603 // check for bias argument
2604 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002605 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002606 int nonBiasArgCount = 2;
2607 if (cracked.offset)
2608 ++nonBiasArgCount;
2609 if (cracked.grad)
2610 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002611 if (cracked.lodClamp)
2612 ++nonBiasArgCount;
2613 if (sparse)
2614 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002615
2616 if ((int)arguments.size() > nonBiasArgCount)
2617 bias = true;
2618 }
2619
John Kessenicha5c33d62016-06-02 23:45:21 -06002620 // See if the sampler param should really be just the SPV image part
2621 if (cracked.fetch) {
2622 // a fetch needs to have the image extracted first
2623 if (builder.isSampledImage(params.sampler))
2624 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2625 }
2626
John Kessenichfc51d282015-08-19 13:34:18 -06002627 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002628
John Kessenichfc51d282015-08-19 13:34:18 -06002629 params.coords = arguments[1];
2630 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002631 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002632
2633 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002634 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002635 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002636 ++extraArgs;
2637 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002638 params.Dref = arguments[2];
2639 ++extraArgs;
2640 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002641 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002642 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002643 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002644 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002645 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002646 dRefComp = builder.getNumComponents(params.coords) - 1;
2647 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002648 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2649 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002650
2651 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002652 if (cracked.lod) {
2653 params.lod = arguments[2];
2654 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002655 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2656 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2657 noImplicitLod = true;
2658 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002659
2660 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002661 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002662 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002663 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002664 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002665
2666 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002667 if (cracked.grad) {
2668 params.gradX = arguments[2 + extraArgs];
2669 params.gradY = arguments[3 + extraArgs];
2670 extraArgs += 2;
2671 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002672
2673 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002674 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002675 params.offset = arguments[2 + extraArgs];
2676 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002677 } else if (cracked.offsets) {
2678 params.offsets = arguments[2 + extraArgs];
2679 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002680 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002681
2682 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002683 if (cracked.lodClamp) {
2684 params.lodClamp = arguments[2 + extraArgs];
2685 ++extraArgs;
2686 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002687
2688 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002689 if (sparse) {
2690 params.texelOut = arguments[2 + extraArgs];
2691 ++extraArgs;
2692 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002693
2694 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002695 if (bias) {
2696 params.bias = arguments[2 + extraArgs];
2697 ++extraArgs;
2698 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002699
2700 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002701 if (cracked.gather && ! sampler.shadow) {
2702 // default component is 0, if missing, otherwise an argument
2703 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002704 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002705 ++extraArgs;
2706 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002707 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002708 }
2709 }
John Kessenichfc51d282015-08-19 13:34:18 -06002710
John Kessenich65336482016-06-16 14:06:26 -06002711 // projective component (might not to move)
2712 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2713 // are divided by the last component of P."
2714 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2715 // unused components will appear after all used components."
2716 if (cracked.proj) {
2717 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2718 int projTargetComp;
2719 switch (sampler.dim) {
2720 case glslang::Esd1D: projTargetComp = 1; break;
2721 case glslang::Esd2D: projTargetComp = 2; break;
2722 case glslang::EsdRect: projTargetComp = 2; break;
2723 default: projTargetComp = projSourceComp; break;
2724 }
2725 // copy the projective coordinate if we have to
2726 if (projTargetComp != projSourceComp) {
2727 spv::Id projComp = builder.createCompositeExtract(params.coords,
2728 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2729 projSourceComp);
2730 params.coords = builder.createCompositeInsert(projComp, params.coords,
2731 builder.getTypeId(params.coords), projTargetComp);
2732 }
2733 }
2734
John Kessenich019f08f2016-02-15 15:40:42 -07002735 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002736}
2737
2738spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2739{
2740 // Grab the function's pointer from the previously created function
2741 spv::Function* function = functionMap[node->getName().c_str()];
2742 if (! function)
2743 return 0;
2744
2745 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2746 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2747
2748 // See comments in makeFunctions() for details about the semantics for parameter passing.
2749 //
2750 // These imply we need a four step process:
2751 // 1. Evaluate the arguments
2752 // 2. Allocate and make copies of in, out, and inout arguments
2753 // 3. Make the call
2754 // 4. Copy back the results
2755
2756 // 1. Evaluate the arguments
2757 std::vector<spv::Builder::AccessChain> lValues;
2758 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002759 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002760 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002761 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002762 // build l-value
2763 builder.clearAccessChain();
2764 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002765 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002766 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2767 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002768 // save l-value
2769 lValues.push_back(builder.getAccessChain());
2770 } else {
2771 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002772 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002773 }
2774 }
2775
2776 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2777 // copy the original into that space.
2778 //
2779 // Also, build up the list of actual arguments to pass in for the call
2780 int lValueCount = 0;
2781 int rValueCount = 0;
2782 std::vector<spv::Id> spvArgs;
2783 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002784 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002785 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002786 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002787 builder.setAccessChain(lValues[lValueCount]);
2788 arg = builder.accessChainGetLValue();
2789 ++lValueCount;
2790 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002791 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002792 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2793 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2794 // need to copy the input into output space
2795 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002796 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002797 builder.createStore(copy, arg);
2798 }
2799 ++lValueCount;
2800 } else {
2801 arg = rValues[rValueCount];
2802 ++rValueCount;
2803 }
2804 spvArgs.push_back(arg);
2805 }
2806
2807 // 3. Make the call.
2808 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002809 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002810
2811 // 4. Copy back out an "out" arguments.
2812 lValueCount = 0;
2813 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2814 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2815 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2816 spv::Id copy = builder.createLoad(spvArgs[a]);
2817 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002818 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002819 }
2820 ++lValueCount;
2821 }
2822 }
2823
2824 return result;
2825}
2826
2827// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002828spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2829 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002830 spv::Id typeId, spv::Id left, spv::Id right,
2831 glslang::TBasicType typeProxy, bool reduceComparison)
2832{
Rex Xu8ff43de2016-04-22 16:51:45 +08002833 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002834 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002835 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002836
2837 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002838 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002839 bool comparison = false;
2840
2841 switch (op) {
2842 case glslang::EOpAdd:
2843 case glslang::EOpAddAssign:
2844 if (isFloat)
2845 binOp = spv::OpFAdd;
2846 else
2847 binOp = spv::OpIAdd;
2848 break;
2849 case glslang::EOpSub:
2850 case glslang::EOpSubAssign:
2851 if (isFloat)
2852 binOp = spv::OpFSub;
2853 else
2854 binOp = spv::OpISub;
2855 break;
2856 case glslang::EOpMul:
2857 case glslang::EOpMulAssign:
2858 if (isFloat)
2859 binOp = spv::OpFMul;
2860 else
2861 binOp = spv::OpIMul;
2862 break;
2863 case glslang::EOpVectorTimesScalar:
2864 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002865 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002866 if (builder.isVector(right))
2867 std::swap(left, right);
2868 assert(builder.isScalar(right));
2869 needMatchingVectors = false;
2870 binOp = spv::OpVectorTimesScalar;
2871 } else
2872 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002873 break;
2874 case glslang::EOpVectorTimesMatrix:
2875 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002876 binOp = spv::OpVectorTimesMatrix;
2877 break;
2878 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002879 binOp = spv::OpMatrixTimesVector;
2880 break;
2881 case glslang::EOpMatrixTimesScalar:
2882 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002883 binOp = spv::OpMatrixTimesScalar;
2884 break;
2885 case glslang::EOpMatrixTimesMatrix:
2886 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002887 binOp = spv::OpMatrixTimesMatrix;
2888 break;
2889 case glslang::EOpOuterProduct:
2890 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002891 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002892 break;
2893
2894 case glslang::EOpDiv:
2895 case glslang::EOpDivAssign:
2896 if (isFloat)
2897 binOp = spv::OpFDiv;
2898 else if (isUnsigned)
2899 binOp = spv::OpUDiv;
2900 else
2901 binOp = spv::OpSDiv;
2902 break;
2903 case glslang::EOpMod:
2904 case glslang::EOpModAssign:
2905 if (isFloat)
2906 binOp = spv::OpFMod;
2907 else if (isUnsigned)
2908 binOp = spv::OpUMod;
2909 else
2910 binOp = spv::OpSMod;
2911 break;
2912 case glslang::EOpRightShift:
2913 case glslang::EOpRightShiftAssign:
2914 if (isUnsigned)
2915 binOp = spv::OpShiftRightLogical;
2916 else
2917 binOp = spv::OpShiftRightArithmetic;
2918 break;
2919 case glslang::EOpLeftShift:
2920 case glslang::EOpLeftShiftAssign:
2921 binOp = spv::OpShiftLeftLogical;
2922 break;
2923 case glslang::EOpAnd:
2924 case glslang::EOpAndAssign:
2925 binOp = spv::OpBitwiseAnd;
2926 break;
2927 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002928 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002929 binOp = spv::OpLogicalAnd;
2930 break;
2931 case glslang::EOpInclusiveOr:
2932 case glslang::EOpInclusiveOrAssign:
2933 binOp = spv::OpBitwiseOr;
2934 break;
2935 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002936 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 binOp = spv::OpLogicalOr;
2938 break;
2939 case glslang::EOpExclusiveOr:
2940 case glslang::EOpExclusiveOrAssign:
2941 binOp = spv::OpBitwiseXor;
2942 break;
2943 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002944 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002946 break;
2947
2948 case glslang::EOpLessThan:
2949 case glslang::EOpGreaterThan:
2950 case glslang::EOpLessThanEqual:
2951 case glslang::EOpGreaterThanEqual:
2952 case glslang::EOpEqual:
2953 case glslang::EOpNotEqual:
2954 case glslang::EOpVectorEqual:
2955 case glslang::EOpVectorNotEqual:
2956 comparison = true;
2957 break;
2958 default:
2959 break;
2960 }
2961
John Kessenich7c1aa102015-10-15 13:29:11 -06002962 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002963 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002964 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002965 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002966 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002967
2968 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002969 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002970 builder.promoteScalar(precision, left, right);
2971
qining25262b32016-05-06 17:25:16 -04002972 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2973 addDecoration(result, noContraction);
2974 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002975 }
2976
2977 if (! comparison)
2978 return 0;
2979
John Kessenich7c1aa102015-10-15 13:29:11 -06002980 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002981
2982 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2983 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2984
John Kessenich22118352015-12-21 20:54:09 -07002985 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002986 }
2987
2988 switch (op) {
2989 case glslang::EOpLessThan:
2990 if (isFloat)
2991 binOp = spv::OpFOrdLessThan;
2992 else if (isUnsigned)
2993 binOp = spv::OpULessThan;
2994 else
2995 binOp = spv::OpSLessThan;
2996 break;
2997 case glslang::EOpGreaterThan:
2998 if (isFloat)
2999 binOp = spv::OpFOrdGreaterThan;
3000 else if (isUnsigned)
3001 binOp = spv::OpUGreaterThan;
3002 else
3003 binOp = spv::OpSGreaterThan;
3004 break;
3005 case glslang::EOpLessThanEqual:
3006 if (isFloat)
3007 binOp = spv::OpFOrdLessThanEqual;
3008 else if (isUnsigned)
3009 binOp = spv::OpULessThanEqual;
3010 else
3011 binOp = spv::OpSLessThanEqual;
3012 break;
3013 case glslang::EOpGreaterThanEqual:
3014 if (isFloat)
3015 binOp = spv::OpFOrdGreaterThanEqual;
3016 else if (isUnsigned)
3017 binOp = spv::OpUGreaterThanEqual;
3018 else
3019 binOp = spv::OpSGreaterThanEqual;
3020 break;
3021 case glslang::EOpEqual:
3022 case glslang::EOpVectorEqual:
3023 if (isFloat)
3024 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003025 else if (isBool)
3026 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003027 else
3028 binOp = spv::OpIEqual;
3029 break;
3030 case glslang::EOpNotEqual:
3031 case glslang::EOpVectorNotEqual:
3032 if (isFloat)
3033 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003034 else if (isBool)
3035 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 else
3037 binOp = spv::OpINotEqual;
3038 break;
3039 default:
3040 break;
3041 }
3042
qining25262b32016-05-06 17:25:16 -04003043 if (binOp != spv::OpNop) {
3044 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3045 addDecoration(result, noContraction);
3046 return builder.setPrecision(result, precision);
3047 }
John Kessenich140f3df2015-06-26 16:58:36 -06003048
3049 return 0;
3050}
3051
John Kessenich04bb8a02015-12-12 12:28:14 -07003052//
3053// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3054// These can be any of:
3055//
3056// matrix * scalar
3057// scalar * matrix
3058// matrix * matrix linear algebraic
3059// matrix * vector
3060// vector * matrix
3061// matrix * matrix componentwise
3062// matrix op matrix op in {+, -, /}
3063// matrix op scalar op in {+, -, /}
3064// scalar op matrix op in {+, -, /}
3065//
qining25262b32016-05-06 17:25:16 -04003066spv::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 -07003067{
3068 bool firstClass = true;
3069
3070 // First, handle first-class matrix operations (* and matrix/scalar)
3071 switch (op) {
3072 case spv::OpFDiv:
3073 if (builder.isMatrix(left) && builder.isScalar(right)) {
3074 // turn matrix / scalar into a multiply...
3075 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3076 op = spv::OpMatrixTimesScalar;
3077 } else
3078 firstClass = false;
3079 break;
3080 case spv::OpMatrixTimesScalar:
3081 if (builder.isMatrix(right))
3082 std::swap(left, right);
3083 assert(builder.isScalar(right));
3084 break;
3085 case spv::OpVectorTimesMatrix:
3086 assert(builder.isVector(left));
3087 assert(builder.isMatrix(right));
3088 break;
3089 case spv::OpMatrixTimesVector:
3090 assert(builder.isMatrix(left));
3091 assert(builder.isVector(right));
3092 break;
3093 case spv::OpMatrixTimesMatrix:
3094 assert(builder.isMatrix(left));
3095 assert(builder.isMatrix(right));
3096 break;
3097 default:
3098 firstClass = false;
3099 break;
3100 }
3101
qining25262b32016-05-06 17:25:16 -04003102 if (firstClass) {
3103 spv::Id result = builder.createBinOp(op, typeId, left, right);
3104 addDecoration(result, noContraction);
3105 return builder.setPrecision(result, precision);
3106 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003107
LoopDawg592860c2016-06-09 08:57:35 -06003108 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003109 // The result type of all of them is the same type as the (a) matrix operand.
3110 // The algorithm is to:
3111 // - break the matrix(es) into vectors
3112 // - smear any scalar to a vector
3113 // - do vector operations
3114 // - make a matrix out the vector results
3115 switch (op) {
3116 case spv::OpFAdd:
3117 case spv::OpFSub:
3118 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003119 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003120 case spv::OpFMul:
3121 {
3122 // one time set up...
3123 bool leftMat = builder.isMatrix(left);
3124 bool rightMat = builder.isMatrix(right);
3125 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3126 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3127 spv::Id scalarType = builder.getScalarTypeId(typeId);
3128 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3129 std::vector<spv::Id> results;
3130 spv::Id smearVec = spv::NoResult;
3131 if (builder.isScalar(left))
3132 smearVec = builder.smearScalar(precision, left, vecType);
3133 else if (builder.isScalar(right))
3134 smearVec = builder.smearScalar(precision, right, vecType);
3135
3136 // do each vector op
3137 for (unsigned int c = 0; c < numCols; ++c) {
3138 std::vector<unsigned int> indexes;
3139 indexes.push_back(c);
3140 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3141 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003142 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3143 addDecoration(result, noContraction);
3144 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003145 }
3146
3147 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003148 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003149 }
3150 default:
3151 assert(0);
3152 return spv::NoResult;
3153 }
3154}
3155
qining25262b32016-05-06 17:25:16 -04003156spv::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 -06003157{
3158 spv::Op unaryOp = spv::OpNop;
3159 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003160 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003161 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003162
3163 switch (op) {
3164 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003165 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003166 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003167 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003168 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003169 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003170 unaryOp = spv::OpSNegate;
3171 break;
3172
3173 case glslang::EOpLogicalNot:
3174 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003175 unaryOp = spv::OpLogicalNot;
3176 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003177 case glslang::EOpBitwiseNot:
3178 unaryOp = spv::OpNot;
3179 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003180
John Kessenich140f3df2015-06-26 16:58:36 -06003181 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003182 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003183 break;
3184 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003185 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003186 break;
3187 case glslang::EOpTranspose:
3188 unaryOp = spv::OpTranspose;
3189 break;
3190
3191 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003192 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003193 break;
3194 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003195 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003196 break;
3197 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003198 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003199 break;
3200 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003202 break;
3203 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003204 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003205 break;
3206 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003208 break;
3209 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003210 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003211 break;
3212 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003213 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003214 break;
3215
3216 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003217 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003218 break;
3219 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003220 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003221 break;
3222 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003223 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003224 break;
3225 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003226 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003227 break;
3228 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003229 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003230 break;
3231 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003232 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003233 break;
3234
3235 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003236 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003237 break;
3238 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003239 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003240 break;
3241
3242 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003243 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003244 break;
3245 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003246 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003247 break;
3248 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003249 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003250 break;
3251 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003252 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003253 break;
3254 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003255 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003256 break;
3257 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003258 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003259 break;
3260
3261 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003262 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003263 break;
3264 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003265 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003266 break;
3267 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003268 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003269 break;
3270 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003271 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003272 break;
3273 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003274 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003275 break;
3276 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003277 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003278 break;
3279
3280 case glslang::EOpIsNan:
3281 unaryOp = spv::OpIsNan;
3282 break;
3283 case glslang::EOpIsInf:
3284 unaryOp = spv::OpIsInf;
3285 break;
LoopDawg592860c2016-06-09 08:57:35 -06003286 case glslang::EOpIsFinite:
3287 unaryOp = spv::OpIsFinite;
3288 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003289
Rex Xucbc426e2015-12-15 16:03:10 +08003290 case glslang::EOpFloatBitsToInt:
3291 case glslang::EOpFloatBitsToUint:
3292 case glslang::EOpIntBitsToFloat:
3293 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003294 case glslang::EOpDoubleBitsToInt64:
3295 case glslang::EOpDoubleBitsToUint64:
3296 case glslang::EOpInt64BitsToDouble:
3297 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003298 unaryOp = spv::OpBitcast;
3299 break;
3300
John Kessenich140f3df2015-06-26 16:58:36 -06003301 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003302 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003303 break;
3304 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003305 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003306 break;
3307 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003308 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003309 break;
3310 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003311 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003312 break;
3313 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003314 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003315 break;
3316 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003317 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003319 case glslang::EOpPackSnorm4x8:
3320 libCall = spv::GLSLstd450PackSnorm4x8;
3321 break;
3322 case glslang::EOpUnpackSnorm4x8:
3323 libCall = spv::GLSLstd450UnpackSnorm4x8;
3324 break;
3325 case glslang::EOpPackUnorm4x8:
3326 libCall = spv::GLSLstd450PackUnorm4x8;
3327 break;
3328 case glslang::EOpUnpackUnorm4x8:
3329 libCall = spv::GLSLstd450UnpackUnorm4x8;
3330 break;
3331 case glslang::EOpPackDouble2x32:
3332 libCall = spv::GLSLstd450PackDouble2x32;
3333 break;
3334 case glslang::EOpUnpackDouble2x32:
3335 libCall = spv::GLSLstd450UnpackDouble2x32;
3336 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003337
Rex Xu8ff43de2016-04-22 16:51:45 +08003338 case glslang::EOpPackInt2x32:
3339 case glslang::EOpUnpackInt2x32:
3340 case glslang::EOpPackUint2x32:
3341 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003342 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003343 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3344 break;
3345
John Kessenich140f3df2015-06-26 16:58:36 -06003346 case glslang::EOpDPdx:
3347 unaryOp = spv::OpDPdx;
3348 break;
3349 case glslang::EOpDPdy:
3350 unaryOp = spv::OpDPdy;
3351 break;
3352 case glslang::EOpFwidth:
3353 unaryOp = spv::OpFwidth;
3354 break;
3355 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003356 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003357 unaryOp = spv::OpDPdxFine;
3358 break;
3359 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003360 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003361 unaryOp = spv::OpDPdyFine;
3362 break;
3363 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003364 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003365 unaryOp = spv::OpFwidthFine;
3366 break;
3367 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003368 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003369 unaryOp = spv::OpDPdxCoarse;
3370 break;
3371 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003372 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003373 unaryOp = spv::OpDPdyCoarse;
3374 break;
3375 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003376 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003377 unaryOp = spv::OpFwidthCoarse;
3378 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003379 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003380 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003381 libCall = spv::GLSLstd450InterpolateAtCentroid;
3382 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003383 case glslang::EOpAny:
3384 unaryOp = spv::OpAny;
3385 break;
3386 case glslang::EOpAll:
3387 unaryOp = spv::OpAll;
3388 break;
3389
3390 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003391 if (isFloat)
3392 libCall = spv::GLSLstd450FAbs;
3393 else
3394 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003395 break;
3396 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003397 if (isFloat)
3398 libCall = spv::GLSLstd450FSign;
3399 else
3400 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003401 break;
3402
John Kessenichfc51d282015-08-19 13:34:18 -06003403 case glslang::EOpAtomicCounterIncrement:
3404 case glslang::EOpAtomicCounterDecrement:
3405 case glslang::EOpAtomicCounter:
3406 {
3407 // Handle all of the atomics in one place, in createAtomicOperation()
3408 std::vector<spv::Id> operands;
3409 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003410 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003411 }
3412
John Kessenichfc51d282015-08-19 13:34:18 -06003413 case glslang::EOpBitFieldReverse:
3414 unaryOp = spv::OpBitReverse;
3415 break;
3416 case glslang::EOpBitCount:
3417 unaryOp = spv::OpBitCount;
3418 break;
3419 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003420 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003421 break;
3422 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003423 if (isUnsigned)
3424 libCall = spv::GLSLstd450FindUMsb;
3425 else
3426 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003427 break;
3428
Rex Xu574ab042016-04-14 16:53:07 +08003429 case glslang::EOpBallot:
3430 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003431 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003432 libCall = spv::GLSLstd450Bad;
3433 break;
3434
Rex Xu338b1852016-05-05 20:38:33 +08003435 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003436 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003437 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003438 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003439
John Kessenich140f3df2015-06-26 16:58:36 -06003440 default:
3441 return 0;
3442 }
3443
3444 spv::Id id;
3445 if (libCall >= 0) {
3446 std::vector<spv::Id> args;
3447 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003448 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003449 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003450 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003451 }
John Kessenich140f3df2015-06-26 16:58:36 -06003452
qining25262b32016-05-06 17:25:16 -04003453 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003454 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003455}
3456
John Kessenich7a53f762016-01-20 11:19:27 -07003457// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003458spv::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 -07003459{
3460 // Handle unary operations vector by vector.
3461 // The result type is the same type as the original type.
3462 // The algorithm is to:
3463 // - break the matrix into vectors
3464 // - apply the operation to each vector
3465 // - make a matrix out the vector results
3466
3467 // get the types sorted out
3468 int numCols = builder.getNumColumns(operand);
3469 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003470 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3471 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003472 std::vector<spv::Id> results;
3473
3474 // do each vector op
3475 for (int c = 0; c < numCols; ++c) {
3476 std::vector<unsigned int> indexes;
3477 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003478 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3479 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3480 addDecoration(destVec, noContraction);
3481 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003482 }
3483
3484 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003485 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003486}
3487
Rex Xu73e3ce72016-04-27 18:48:17 +08003488spv::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 -06003489{
3490 spv::Op convOp = spv::OpNop;
3491 spv::Id zero = 0;
3492 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003493 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003494
3495 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3496
3497 switch (op) {
3498 case glslang::EOpConvIntToBool:
3499 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003500 case glslang::EOpConvInt64ToBool:
3501 case glslang::EOpConvUint64ToBool:
3502 zero = (op == glslang::EOpConvInt64ToBool ||
3503 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003504 zero = makeSmearedConstant(zero, vectorSize);
3505 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3506
3507 case glslang::EOpConvFloatToBool:
3508 zero = builder.makeFloatConstant(0.0F);
3509 zero = makeSmearedConstant(zero, vectorSize);
3510 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3511
3512 case glslang::EOpConvDoubleToBool:
3513 zero = builder.makeDoubleConstant(0.0);
3514 zero = makeSmearedConstant(zero, vectorSize);
3515 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3516
3517 case glslang::EOpConvBoolToFloat:
3518 convOp = spv::OpSelect;
3519 zero = builder.makeFloatConstant(0.0);
3520 one = builder.makeFloatConstant(1.0);
3521 break;
3522 case glslang::EOpConvBoolToDouble:
3523 convOp = spv::OpSelect;
3524 zero = builder.makeDoubleConstant(0.0);
3525 one = builder.makeDoubleConstant(1.0);
3526 break;
3527 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003528 case glslang::EOpConvBoolToInt64:
3529 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3530 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003531 convOp = spv::OpSelect;
3532 break;
3533 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003534 case glslang::EOpConvBoolToUint64:
3535 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3536 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003537 convOp = spv::OpSelect;
3538 break;
3539
3540 case glslang::EOpConvIntToFloat:
3541 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003542 case glslang::EOpConvInt64ToFloat:
3543 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003544 convOp = spv::OpConvertSToF;
3545 break;
3546
3547 case glslang::EOpConvUintToFloat:
3548 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003549 case glslang::EOpConvUint64ToFloat:
3550 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003551 convOp = spv::OpConvertUToF;
3552 break;
3553
3554 case glslang::EOpConvDoubleToFloat:
3555 case glslang::EOpConvFloatToDouble:
3556 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003557 if (builder.isMatrixType(destType))
3558 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003559 break;
3560
3561 case glslang::EOpConvFloatToInt:
3562 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003563 case glslang::EOpConvFloatToInt64:
3564 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003565 convOp = spv::OpConvertFToS;
3566 break;
3567
3568 case glslang::EOpConvUintToInt:
3569 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003570 case glslang::EOpConvUint64ToInt64:
3571 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003572 if (builder.isInSpecConstCodeGenMode()) {
3573 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003574 zero = (op == glslang::EOpConvUintToInt64 ||
3575 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003576 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003577 // Use OpIAdd, instead of OpBitcast to do the conversion when
3578 // generating for OpSpecConstantOp instruction.
3579 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3580 }
3581 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003582 convOp = spv::OpBitcast;
3583 break;
3584
3585 case glslang::EOpConvFloatToUint:
3586 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003587 case glslang::EOpConvFloatToUint64:
3588 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003589 convOp = spv::OpConvertFToU;
3590 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003591
3592 case glslang::EOpConvIntToInt64:
3593 case glslang::EOpConvInt64ToInt:
3594 convOp = spv::OpSConvert;
3595 break;
3596
3597 case glslang::EOpConvUintToUint64:
3598 case glslang::EOpConvUint64ToUint:
3599 convOp = spv::OpUConvert;
3600 break;
3601
3602 case glslang::EOpConvIntToUint64:
3603 case glslang::EOpConvInt64ToUint:
3604 case glslang::EOpConvUint64ToInt:
3605 case glslang::EOpConvUintToInt64:
3606 // OpSConvert/OpUConvert + OpBitCast
3607 switch (op) {
3608 case glslang::EOpConvIntToUint64:
3609 convOp = spv::OpSConvert;
3610 type = builder.makeIntType(64);
3611 break;
3612 case glslang::EOpConvInt64ToUint:
3613 convOp = spv::OpSConvert;
3614 type = builder.makeIntType(32);
3615 break;
3616 case glslang::EOpConvUint64ToInt:
3617 convOp = spv::OpUConvert;
3618 type = builder.makeUintType(32);
3619 break;
3620 case glslang::EOpConvUintToInt64:
3621 convOp = spv::OpUConvert;
3622 type = builder.makeUintType(64);
3623 break;
3624 default:
3625 assert(0);
3626 break;
3627 }
3628
3629 if (vectorSize > 0)
3630 type = builder.makeVectorType(type, vectorSize);
3631
3632 operand = builder.createUnaryOp(convOp, type, operand);
3633
3634 if (builder.isInSpecConstCodeGenMode()) {
3635 // Build zero scalar or vector for OpIAdd.
3636 zero = (op == glslang::EOpConvIntToUint64 ||
3637 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3638 zero = makeSmearedConstant(zero, vectorSize);
3639 // Use OpIAdd, instead of OpBitcast to do the conversion when
3640 // generating for OpSpecConstantOp instruction.
3641 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3642 }
3643 // For normal run-time conversion instruction, use OpBitcast.
3644 convOp = spv::OpBitcast;
3645 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003646 default:
3647 break;
3648 }
3649
3650 spv::Id result = 0;
3651 if (convOp == spv::OpNop)
3652 return result;
3653
3654 if (convOp == spv::OpSelect) {
3655 zero = makeSmearedConstant(zero, vectorSize);
3656 one = makeSmearedConstant(one, vectorSize);
3657 result = builder.createTriOp(convOp, destType, operand, one, zero);
3658 } else
3659 result = builder.createUnaryOp(convOp, destType, operand);
3660
John Kessenich32cfd492016-02-02 12:37:46 -07003661 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003662}
3663
3664spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3665{
3666 if (vectorSize == 0)
3667 return constant;
3668
3669 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3670 std::vector<spv::Id> components;
3671 for (int c = 0; c < vectorSize; ++c)
3672 components.push_back(constant);
3673 return builder.makeCompositeConstant(vectorTypeId, components);
3674}
3675
John Kessenich426394d2015-07-23 10:22:48 -06003676// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003677spv::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 -06003678{
3679 spv::Op opCode = spv::OpNop;
3680
3681 switch (op) {
3682 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003683 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003684 opCode = spv::OpAtomicIAdd;
3685 break;
3686 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003687 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003688 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003689 break;
3690 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003691 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003692 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003693 break;
3694 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003695 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003696 opCode = spv::OpAtomicAnd;
3697 break;
3698 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003699 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003700 opCode = spv::OpAtomicOr;
3701 break;
3702 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003703 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003704 opCode = spv::OpAtomicXor;
3705 break;
3706 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003707 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003708 opCode = spv::OpAtomicExchange;
3709 break;
3710 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003711 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003712 opCode = spv::OpAtomicCompareExchange;
3713 break;
3714 case glslang::EOpAtomicCounterIncrement:
3715 opCode = spv::OpAtomicIIncrement;
3716 break;
3717 case glslang::EOpAtomicCounterDecrement:
3718 opCode = spv::OpAtomicIDecrement;
3719 break;
3720 case glslang::EOpAtomicCounter:
3721 opCode = spv::OpAtomicLoad;
3722 break;
3723 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003724 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003725 break;
3726 }
3727
3728 // Sort out the operands
3729 // - mapping from glslang -> SPV
3730 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003731 // - compare-exchange swaps the value and comparator
3732 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003733 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3734 auto opIt = operands.begin(); // walk the glslang operands
3735 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003736 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3737 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3738 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003739 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3740 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003741 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003742 spvAtomicOperands.push_back(*(opIt + 1));
3743 spvAtomicOperands.push_back(*opIt);
3744 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003745 }
John Kessenich426394d2015-07-23 10:22:48 -06003746
John Kessenich3e60a6f2015-09-14 22:45:16 -06003747 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003748 for (; opIt != operands.end(); ++opIt)
3749 spvAtomicOperands.push_back(*opIt);
3750
3751 return builder.createOp(opCode, typeId, spvAtomicOperands);
3752}
3753
John Kessenich91cef522016-05-05 16:45:40 -06003754// Create group invocation operations.
3755spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3756{
3757 builder.addCapability(spv::CapabilityGroups);
3758
3759 std::vector<spv::Id> operands;
3760 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3761 operands.push_back(operand);
3762
3763 switch (op) {
3764 case glslang::EOpAnyInvocation:
3765 case glslang::EOpAllInvocations:
3766 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3767
3768 case glslang::EOpAllInvocationsEqual:
3769 {
3770 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3771 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3772
3773 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3774 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3775 }
3776 default:
3777 logger->missingFunctionality("invocation operation");
3778 return spv::NoResult;
3779 }
3780}
3781
John Kessenich5e4b1242015-08-06 22:53:06 -06003782spv::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 -06003783{
Rex Xu8ff43de2016-04-22 16:51:45 +08003784 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003785 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3786
John Kessenich140f3df2015-06-26 16:58:36 -06003787 spv::Op opCode = spv::OpNop;
3788 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003789 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003790 spv::Id typeId0 = 0;
3791 if (consumedOperands > 0)
3792 typeId0 = builder.getTypeId(operands[0]);
3793 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003794
3795 switch (op) {
3796 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 if (isFloat)
3798 libCall = spv::GLSLstd450FMin;
3799 else if (isUnsigned)
3800 libCall = spv::GLSLstd450UMin;
3801 else
3802 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003803 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003804 break;
3805 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003806 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003807 break;
3808 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 if (isFloat)
3810 libCall = spv::GLSLstd450FMax;
3811 else if (isUnsigned)
3812 libCall = spv::GLSLstd450UMax;
3813 else
3814 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003815 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
3817 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003818 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820 case glslang::EOpDot:
3821 opCode = spv::OpDot;
3822 break;
3823 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003824 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003825 break;
3826
3827 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003828 if (isFloat)
3829 libCall = spv::GLSLstd450FClamp;
3830 else if (isUnsigned)
3831 libCall = spv::GLSLstd450UClamp;
3832 else
3833 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003834 builder.promoteScalar(precision, operands.front(), operands[1]);
3835 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003836 break;
3837 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003838 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3839 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003840 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003841 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003842 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003843 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003844 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003845 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003846 break;
3847 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003848 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003849 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003850 break;
3851 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003852 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003853 builder.promoteScalar(precision, operands[0], operands[2]);
3854 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 break;
3856
3857 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003858 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003859 break;
3860 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003861 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003862 break;
3863 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003864 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003865 break;
3866 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003867 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003868 break;
3869 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003870 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003871 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003872 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003873 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003874 libCall = spv::GLSLstd450InterpolateAtSample;
3875 break;
3876 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003877 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003878 libCall = spv::GLSLstd450InterpolateAtOffset;
3879 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003880 case glslang::EOpAddCarry:
3881 opCode = spv::OpIAddCarry;
3882 typeId = builder.makeStructResultType(typeId0, typeId0);
3883 consumedOperands = 2;
3884 break;
3885 case glslang::EOpSubBorrow:
3886 opCode = spv::OpISubBorrow;
3887 typeId = builder.makeStructResultType(typeId0, typeId0);
3888 consumedOperands = 2;
3889 break;
3890 case glslang::EOpUMulExtended:
3891 opCode = spv::OpUMulExtended;
3892 typeId = builder.makeStructResultType(typeId0, typeId0);
3893 consumedOperands = 2;
3894 break;
3895 case glslang::EOpIMulExtended:
3896 opCode = spv::OpSMulExtended;
3897 typeId = builder.makeStructResultType(typeId0, typeId0);
3898 consumedOperands = 2;
3899 break;
3900 case glslang::EOpBitfieldExtract:
3901 if (isUnsigned)
3902 opCode = spv::OpBitFieldUExtract;
3903 else
3904 opCode = spv::OpBitFieldSExtract;
3905 break;
3906 case glslang::EOpBitfieldInsert:
3907 opCode = spv::OpBitFieldInsert;
3908 break;
3909
3910 case glslang::EOpFma:
3911 libCall = spv::GLSLstd450Fma;
3912 break;
3913 case glslang::EOpFrexp:
3914 libCall = spv::GLSLstd450FrexpStruct;
3915 if (builder.getNumComponents(operands[0]) == 1)
3916 frexpIntType = builder.makeIntegerType(32, true);
3917 else
3918 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3919 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3920 consumedOperands = 1;
3921 break;
3922 case glslang::EOpLdexp:
3923 libCall = spv::GLSLstd450Ldexp;
3924 break;
3925
Rex Xu574ab042016-04-14 16:53:07 +08003926 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003927 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003928 libCall = spv::GLSLstd450Bad;
3929 break;
3930
John Kessenich140f3df2015-06-26 16:58:36 -06003931 default:
3932 return 0;
3933 }
3934
3935 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003936 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003937 // Use an extended instruction from the standard library.
3938 // Construct the call arguments, without modifying the original operands vector.
3939 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3940 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003941 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003942 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003943 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003944 case 0:
3945 // should all be handled by visitAggregate and createNoArgOperation
3946 assert(0);
3947 return 0;
3948 case 1:
3949 // should all be handled by createUnaryOperation
3950 assert(0);
3951 return 0;
3952 case 2:
3953 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3954 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003955 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003956 // anything 3 or over doesn't have l-value operands, so all should be consumed
3957 assert(consumedOperands == operands.size());
3958 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003959 break;
3960 }
3961 }
3962
John Kessenich55e7d112015-11-15 21:33:39 -07003963 // Decode the return types that were structures
3964 switch (op) {
3965 case glslang::EOpAddCarry:
3966 case glslang::EOpSubBorrow:
3967 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3968 id = builder.createCompositeExtract(id, typeId0, 0);
3969 break;
3970 case glslang::EOpUMulExtended:
3971 case glslang::EOpIMulExtended:
3972 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3973 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3974 break;
3975 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003976 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003977 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3978 id = builder.createCompositeExtract(id, typeId0, 0);
3979 break;
3980 default:
3981 break;
3982 }
3983
John Kessenich32cfd492016-02-02 12:37:46 -07003984 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003985}
3986
3987// Intrinsics with no arguments, no return value, and no precision.
3988spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3989{
3990 // TODO: get the barrier operands correct
3991
3992 switch (op) {
3993 case glslang::EOpEmitVertex:
3994 builder.createNoResultOp(spv::OpEmitVertex);
3995 return 0;
3996 case glslang::EOpEndPrimitive:
3997 builder.createNoResultOp(spv::OpEndPrimitive);
3998 return 0;
3999 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004000 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004001 return 0;
4002 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004003 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004004 return 0;
4005 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004006 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004007 return 0;
4008 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004009 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004010 return 0;
4011 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004012 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004013 return 0;
4014 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004015 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004016 return 0;
4017 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004018 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004019 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004020 case glslang::EOpAllMemoryBarrierWithGroupSync:
4021 // Control barrier with non-"None" semantic is also a memory barrier.
4022 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4023 return 0;
4024 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4025 // Control barrier with non-"None" semantic is also a memory barrier.
4026 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4027 return 0;
4028 case glslang::EOpWorkgroupMemoryBarrier:
4029 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4030 return 0;
4031 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4032 // Control barrier with non-"None" semantic is also a memory barrier.
4033 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4034 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004035 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004036 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004037 return 0;
4038 }
4039}
4040
4041spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4042{
John Kessenich2f273362015-07-18 22:34:27 -06004043 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004044 spv::Id id;
4045 if (symbolValues.end() != iter) {
4046 id = iter->second;
4047 return id;
4048 }
4049
4050 // it was not found, create it
4051 id = createSpvVariable(symbol);
4052 symbolValues[symbol->getId()] = id;
4053
Rex Xuc884b4a2016-06-29 15:03:44 +08004054 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004055 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004056 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004057 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004058 if (symbol->getType().getQualifier().hasSpecConstantId())
4059 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004060 if (symbol->getQualifier().hasIndex())
4061 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4062 if (symbol->getQualifier().hasComponent())
4063 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4064 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004065 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004066 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004068 if (symbol->getQualifier().hasXfbBuffer())
4069 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4070 if (symbol->getQualifier().hasXfbOffset())
4071 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4072 }
4073 }
4074
scygan2c864272016-05-18 18:09:17 +02004075 if (symbol->getQualifier().hasLocation())
4076 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004077 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004078 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004079 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004080 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004081 }
John Kessenich140f3df2015-06-26 16:58:36 -06004082 if (symbol->getQualifier().hasSet())
4083 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004084 else if (IsDescriptorResource(symbol->getType())) {
4085 // default to 0
4086 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4087 }
John Kessenich140f3df2015-06-26 16:58:36 -06004088 if (symbol->getQualifier().hasBinding())
4089 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004090 if (symbol->getQualifier().hasAttachment())
4091 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004092 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004093 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004094 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004095 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004096 if (symbol->getQualifier().hasXfbBuffer())
4097 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4098 }
4099
Rex Xu1da878f2016-02-21 20:59:01 +08004100 if (symbol->getType().isImage()) {
4101 std::vector<spv::Decoration> memory;
4102 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4103 for (unsigned int i = 0; i < memory.size(); ++i)
4104 addDecoration(id, memory[i]);
4105 }
4106
John Kessenich140f3df2015-06-26 16:58:36 -06004107 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004108 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06004109 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07004110 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004111
John Kessenich140f3df2015-06-26 16:58:36 -06004112 return id;
4113}
4114
John Kessenich55e7d112015-11-15 21:33:39 -07004115// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004116void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4117{
4118 if (dec != spv::BadValue)
4119 builder.addDecoration(id, dec);
4120}
4121
John Kessenich55e7d112015-11-15 21:33:39 -07004122// If 'dec' is valid, add a one-operand decoration to an object
4123void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4124{
4125 if (dec != spv::BadValue)
4126 builder.addDecoration(id, dec, value);
4127}
4128
4129// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004130void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4131{
4132 if (dec != spv::BadValue)
4133 builder.addMemberDecoration(id, (unsigned)member, dec);
4134}
4135
John Kessenich92187592016-02-01 13:45:25 -07004136// If 'dec' is valid, add a one-operand decoration to a struct member
4137void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4138{
4139 if (dec != spv::BadValue)
4140 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4141}
4142
John Kessenich55e7d112015-11-15 21:33:39 -07004143// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004144// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004145//
4146// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4147//
4148// Recursively walk the nodes. The nodes form a tree whose leaves are
4149// regular constants, which themselves are trees that createSpvConstant()
4150// recursively walks. So, this function walks the "top" of the tree:
4151// - emit specialization constant-building instructions for specConstant
4152// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004153spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004154{
John Kessenich7cc0e282016-03-20 00:46:02 -06004155 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004156
qining4f4bb812016-04-03 23:55:17 -04004157 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004158 if (! node.getQualifier().specConstant) {
4159 // hand off to the non-spec-constant path
4160 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4161 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004162 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004163 nextConst, false);
4164 }
4165
4166 // We now know we have a specialization constant to build
4167
John Kessenichd94c0032016-05-30 19:29:40 -06004168 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004169 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4170 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4171 std::vector<spv::Id> dimConstId;
4172 for (int dim = 0; dim < 3; ++dim) {
4173 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4174 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4175 if (specConst)
4176 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4177 }
4178 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4179 }
4180
4181 // An AST node labelled as specialization constant should be a symbol node.
4182 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4183 if (auto* sn = node.getAsSymbolNode()) {
4184 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004185 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4186 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4187 // will set the builder into spec constant op instruction generating mode.
4188 sub_tree->traverse(this);
4189 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004190 } else if (auto* const_union_array = &sn->getConstArray()){
4191 int nextConst = 0;
4192 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004193 }
4194 }
qining4f4bb812016-04-03 23:55:17 -04004195
4196 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4197 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004198 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004199 exit(1);
4200 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004201}
4202
John Kessenich140f3df2015-06-26 16:58:36 -06004203// Use 'consts' as the flattened glslang source of scalar constants to recursively
4204// build the aggregate SPIR-V constant.
4205//
4206// If there are not enough elements present in 'consts', 0 will be substituted;
4207// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4208//
qining08408382016-03-21 09:51:37 -04004209spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004210{
4211 // vector of constants for SPIR-V
4212 std::vector<spv::Id> spvConsts;
4213
4214 // Type is used for struct and array constants
4215 spv::Id typeId = convertGlslangToSpvType(glslangType);
4216
4217 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004218 glslang::TType elementType(glslangType, 0);
4219 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004220 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004221 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004222 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004223 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004224 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004225 } else if (glslangType.getStruct()) {
4226 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4227 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004228 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004229 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004230 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4231 bool zero = nextConst >= consts.size();
4232 switch (glslangType.getBasicType()) {
4233 case glslang::EbtInt:
4234 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4235 break;
4236 case glslang::EbtUint:
4237 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4238 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004239 case glslang::EbtInt64:
4240 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4241 break;
4242 case glslang::EbtUint64:
4243 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4244 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004245 case glslang::EbtFloat:
4246 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4247 break;
4248 case glslang::EbtDouble:
4249 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4250 break;
4251 case glslang::EbtBool:
4252 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4253 break;
4254 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004255 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004256 break;
4257 }
4258 ++nextConst;
4259 }
4260 } else {
4261 // we have a non-aggregate (scalar) constant
4262 bool zero = nextConst >= consts.size();
4263 spv::Id scalar = 0;
4264 switch (glslangType.getBasicType()) {
4265 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004266 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004267 break;
4268 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004269 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004270 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004271 case glslang::EbtInt64:
4272 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4273 break;
4274 case glslang::EbtUint64:
4275 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4276 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004277 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004278 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004279 break;
4280 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004281 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004282 break;
4283 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004284 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004285 break;
4286 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004287 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004288 break;
4289 }
4290 ++nextConst;
4291 return scalar;
4292 }
4293
4294 return builder.makeCompositeConstant(typeId, spvConsts);
4295}
4296
John Kessenich7c1aa102015-10-15 13:29:11 -06004297// Return true if the node is a constant or symbol whose reading has no
4298// non-trivial observable cost or effect.
4299bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4300{
4301 // don't know what this is
4302 if (node == nullptr)
4303 return false;
4304
4305 // a constant is safe
4306 if (node->getAsConstantUnion() != nullptr)
4307 return true;
4308
4309 // not a symbol means non-trivial
4310 if (node->getAsSymbolNode() == nullptr)
4311 return false;
4312
4313 // a symbol, depends on what's being read
4314 switch (node->getType().getQualifier().storage) {
4315 case glslang::EvqTemporary:
4316 case glslang::EvqGlobal:
4317 case glslang::EvqIn:
4318 case glslang::EvqInOut:
4319 case glslang::EvqConst:
4320 case glslang::EvqConstReadOnly:
4321 case glslang::EvqUniform:
4322 return true;
4323 default:
4324 return false;
4325 }
qining25262b32016-05-06 17:25:16 -04004326}
John Kessenich7c1aa102015-10-15 13:29:11 -06004327
4328// A node is trivial if it is a single operation with no side effects.
4329// Error on the side of saying non-trivial.
4330// Return true if trivial.
4331bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4332{
4333 if (node == nullptr)
4334 return false;
4335
4336 // symbols and constants are trivial
4337 if (isTrivialLeaf(node))
4338 return true;
4339
4340 // otherwise, it needs to be a simple operation or one or two leaf nodes
4341
4342 // not a simple operation
4343 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4344 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4345 if (binaryNode == nullptr && unaryNode == nullptr)
4346 return false;
4347
4348 // not on leaf nodes
4349 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4350 return false;
4351
4352 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4353 return false;
4354 }
4355
4356 switch (node->getAsOperator()->getOp()) {
4357 case glslang::EOpLogicalNot:
4358 case glslang::EOpConvIntToBool:
4359 case glslang::EOpConvUintToBool:
4360 case glslang::EOpConvFloatToBool:
4361 case glslang::EOpConvDoubleToBool:
4362 case glslang::EOpEqual:
4363 case glslang::EOpNotEqual:
4364 case glslang::EOpLessThan:
4365 case glslang::EOpGreaterThan:
4366 case glslang::EOpLessThanEqual:
4367 case glslang::EOpGreaterThanEqual:
4368 case glslang::EOpIndexDirect:
4369 case glslang::EOpIndexDirectStruct:
4370 case glslang::EOpLogicalXor:
4371 case glslang::EOpAny:
4372 case glslang::EOpAll:
4373 return true;
4374 default:
4375 return false;
4376 }
4377}
4378
4379// Emit short-circuiting code, where 'right' is never evaluated unless
4380// the left side is true (for &&) or false (for ||).
4381spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4382{
4383 spv::Id boolTypeId = builder.makeBoolType();
4384
4385 // emit left operand
4386 builder.clearAccessChain();
4387 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004388 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004389
4390 // Operands to accumulate OpPhi operands
4391 std::vector<spv::Id> phiOperands;
4392 // accumulate left operand's phi information
4393 phiOperands.push_back(leftId);
4394 phiOperands.push_back(builder.getBuildPoint()->getId());
4395
4396 // Make the two kinds of operation symmetric with a "!"
4397 // || => emit "if (! left) result = right"
4398 // && => emit "if ( left) result = right"
4399 //
4400 // TODO: this runtime "not" for || could be avoided by adding functionality
4401 // to 'builder' to have an "else" without an "then"
4402 if (op == glslang::EOpLogicalOr)
4403 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4404
4405 // make an "if" based on the left value
4406 spv::Builder::If ifBuilder(leftId, builder);
4407
4408 // emit right operand as the "then" part of the "if"
4409 builder.clearAccessChain();
4410 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004411 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004412
4413 // accumulate left operand's phi information
4414 phiOperands.push_back(rightId);
4415 phiOperands.push_back(builder.getBuildPoint()->getId());
4416
4417 // finish the "if"
4418 ifBuilder.makeEndIf();
4419
4420 // phi together the two results
4421 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4422}
4423
John Kessenich140f3df2015-06-26 16:58:36 -06004424}; // end anonymous namespace
4425
4426namespace glslang {
4427
John Kessenich68d78fd2015-07-12 19:28:10 -06004428void GetSpirvVersion(std::string& version)
4429{
John Kessenich9e55f632015-07-15 10:03:39 -06004430 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004431 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004432 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004433 version = buf;
4434}
4435
John Kessenich140f3df2015-06-26 16:58:36 -06004436// Write SPIR-V out to a binary file
4437void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4438{
4439 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004440 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004441 for (int i = 0; i < (int)spirv.size(); ++i) {
4442 unsigned int word = spirv[i];
4443 out.write((const char*)&word, 4);
4444 }
4445 out.close();
4446}
4447
4448//
4449// Set up the glslang traversal
4450//
4451void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4452{
Lei Zhang17535f72016-05-04 15:55:59 -04004453 spv::SpvBuildLogger logger;
4454 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004455}
4456
Lei Zhang17535f72016-05-04 15:55:59 -04004457void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004458{
John Kessenich140f3df2015-06-26 16:58:36 -06004459 TIntermNode* root = intermediate.getTreeRoot();
4460
4461 if (root == 0)
4462 return;
4463
4464 glslang::GetThreadPoolAllocator().push();
4465
Lei Zhang17535f72016-05-04 15:55:59 -04004466 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004467
4468 root->traverse(&it);
4469
4470 it.dumpSpv(spirv);
4471
4472 glslang::GetThreadPoolAllocator().pop();
4473}
4474
4475}; // end namespace glslang