blob: 0ca7d6dd3957719b7f77fa7588cf42247b516ba9 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
45 #include "GLSL.std.450.h"
46}
John Kessenich140f3df2015-06-26 16:58:36 -060047
48// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020049#include "../glslang/MachineIndependent/localintermediate.h"
50#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050052#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
John Kessenich140f3df2015-06-26 16:58:36 -060054#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050055#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040056#include <list>
57#include <map>
58#include <stack>
59#include <string>
60#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060061
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
88}
89
John Kessenich140f3df2015-06-26 16:58:36 -060090//
91// The main holder of information for translating glslang to SPIR-V.
92//
93// Derives from the AST walking base class.
94//
95class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
96public:
Lei Zhang17535f72016-05-04 15:55:59 -040097 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060098 virtual ~TGlslangToSpvTraverser();
99
100 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
101 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
102 void visitConstantUnion(glslang::TIntermConstantUnion*);
103 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
104 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
105 void visitSymbol(glslang::TIntermSymbol* symbol);
106 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
107 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
108 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
109
John Kessenich7ba63412015-12-20 17:37:07 -0700110 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112protected:
Rex Xubbceed72016-05-21 09:40:44 +0800113 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenichebb50532016-05-16 19:22:05 -0600114 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool member);
John Kessenich5d0fa972016-02-15 11:57:00 -0700115 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600116 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
117 spv::Id getSampledType(const glslang::TSampler&);
118 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700119 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700120 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700121 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800122 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700123 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700124 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
125 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
126 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenichebb50532016-05-16 19:22:05 -0600127 void declareClipCullCapability(const glslang::TTypeList& members, int member);
John Kessenich140f3df2015-06-26 16:58:36 -0600128
129 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
130 void makeFunctions(const glslang::TIntermSequence&);
131 void makeGlobalInitializers(const glslang::TIntermSequence&);
132 void visitFunctions(const glslang::TIntermSequence&);
133 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800134 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600135 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
136 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600137 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
138
qining25262b32016-05-06 17:25:16 -0400139 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);
140 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
141 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
142 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 +0800143 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 -0600144 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800145 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 -0600146 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600147 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 -0600148 spv::Id createNoArgOperation(glslang::TOperator op);
149 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
150 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700151 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600152 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700153 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400154 spv::Id createSpvConstant(const glslang::TIntermTyped&);
155 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600156 bool isTrivialLeaf(const glslang::TIntermTyped* node);
157 bool isTrivial(const glslang::TIntermTyped* node);
158 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600159
160 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700161 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600162 int sequenceDepth;
163
Lei Zhang17535f72016-05-04 15:55:59 -0400164 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400165
John Kessenich140f3df2015-06-26 16:58:36 -0600166 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
167 spv::Builder builder;
168 bool inMain;
169 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700170 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 -0700171 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600172 const glslang::TIntermediate* glslangIntermediate;
173 spv::Id stdBuiltins;
174
John Kessenich2f273362015-07-18 22:34:27 -0600175 std::unordered_map<int, spv::Id> symbolValues;
176 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
177 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700178 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600179 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 -0600180 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600181};
182
183//
184// Helper functions for translating glslang representations to SPIR-V enumerants.
185//
186
187// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700188spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600189{
John Kessenich66e2faf2016-03-12 18:34:36 -0700190 switch (source) {
191 case glslang::EShSourceGlsl:
192 switch (profile) {
193 case ENoProfile:
194 case ECoreProfile:
195 case ECompatibilityProfile:
196 return spv::SourceLanguageGLSL;
197 case EEsProfile:
198 return spv::SourceLanguageESSL;
199 default:
200 return spv::SourceLanguageUnknown;
201 }
202 case glslang::EShSourceHlsl:
203 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600204 default:
205 return spv::SourceLanguageUnknown;
206 }
207}
208
209// Translate glslang language (stage) to SPIR-V execution model.
210spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
211{
212 switch (stage) {
213 case EShLangVertex: return spv::ExecutionModelVertex;
214 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
215 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
216 case EShLangGeometry: return spv::ExecutionModelGeometry;
217 case EShLangFragment: return spv::ExecutionModelFragment;
218 case EShLangCompute: return spv::ExecutionModelGLCompute;
219 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700220 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600221 return spv::ExecutionModelFragment;
222 }
223}
224
225// Translate glslang type to SPIR-V storage class.
226spv::StorageClass TranslateStorageClass(const glslang::TType& type)
227{
228 if (type.getQualifier().isPipeInput())
229 return spv::StorageClassInput;
230 else if (type.getQualifier().isPipeOutput())
231 return spv::StorageClassOutput;
232 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700233 if (type.getQualifier().layoutPushConstant)
234 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 if (type.getBasicType() == glslang::EbtBlock)
236 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800237 else if (type.getBasicType() == glslang::EbtAtomicUint)
238 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 else
240 return spv::StorageClassUniformConstant;
241 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
242 } else {
243 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700244 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
245 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
247 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400248 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700249 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600250 return spv::StorageClassFunction;
251 }
252 }
253}
254
255// Translate glslang sampler type to SPIR-V dimensionality.
256spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
257{
258 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700259 case glslang::Esd1D: return spv::Dim1D;
260 case glslang::Esd2D: return spv::Dim2D;
261 case glslang::Esd3D: return spv::Dim3D;
262 case glslang::EsdCube: return spv::DimCube;
263 case glslang::EsdRect: return spv::DimRect;
264 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700265 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600268 return spv::Dim2D;
269 }
270}
271
272// Translate glslang type to SPIR-V precision decorations.
273spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
274{
275 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700276 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600277 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 default:
279 return spv::NoPrecision;
280 }
281}
282
283// Translate glslang type to SPIR-V block decorations.
284spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
289 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
298 return (spv::Decoration)spv::BadValue;
299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
327 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
332 return (spv::Decoration)spv::BadValue;
333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600342 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600347 return (spv::Decoration)spv::BadValue;
348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600350 return (spv::Decoration)spv::BadValue;
351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700357// Returns spv::Decoration(spv::BadValue) when no decoration
358// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800359spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
Rex Xubbceed72016-05-21 09:40:44 +0800361 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
363 return (spv::Decoration)spv::BadValue;
Rex Xubbceed72016-05-21 09:40:44 +0800364 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800368 else
369 return (spv::Decoration)spv::BadValue;
370}
371
372// Translate glslang type to SPIR-V auxiliary storage decorations.
373// Returns spv::Decoration(spv::BadValue) when no decoration
374// should be applied.
375spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
376{
377 if (qualifier.patch)
378 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700381 else if (qualifier.sample) {
382 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700384 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600385 return (spv::Decoration)spv::BadValue;
386}
387
John Kessenich92187592016-02-01 13:45:25 -0700388// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700389spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700391 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600392 return spv::DecorationInvariant;
393 else
394 return (spv::Decoration)spv::BadValue;
395}
396
qining9220dbb2016-05-04 17:34:38 -0400397// If glslang type is noContraction, return SPIR-V NoContraction decoration.
398spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
399{
400 if (qualifier.noContraction)
401 return spv::DecorationNoContraction;
402 else
403 return (spv::Decoration)spv::BadValue;
404}
405
John Kessenich140f3df2015-06-26 16:58:36 -0600406// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenichebb50532016-05-16 19:22:05 -0600407spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool member)
John Kessenich140f3df2015-06-26 16:58:36 -0600408{
409 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700410 case glslang::EbvPointSize:
411 switch (glslangIntermediate->getStage()) {
412 case EShLangGeometry:
413 builder.addCapability(spv::CapabilityGeometryPointSize);
414 break;
415 case EShLangTessControl:
416 case EShLangTessEvaluation:
417 builder.addCapability(spv::CapabilityTessellationPointSize);
418 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100419 default:
420 break;
John Kessenich92187592016-02-01 13:45:25 -0700421 }
422 return spv::BuiltInPointSize;
423
John Kessenichebb50532016-05-16 19:22:05 -0600424 // These *Distance capabilities logically belong here, but if the member is declared and
425 // then never used, consumers of SPIR-V prefer the capability not be declared.
426 // They are now generated when used, rather than here when declared.
427 // Potentially, the specification should be more clear what the minimum
428 // use needed is to trigger the capability.
429 //
John Kessenich92187592016-02-01 13:45:25 -0700430 case glslang::EbvClipDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600431 if (! member)
432 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700433 return spv::BuiltInClipDistance;
434
435 case glslang::EbvCullDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600436 if (! member)
437 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700438 return spv::BuiltInCullDistance;
439
440 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500441 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700442 return spv::BuiltInViewportIndex;
443
John Kessenich5e801132016-02-15 11:09:46 -0700444 case glslang::EbvSampleId:
445 builder.addCapability(spv::CapabilitySampleRateShading);
446 return spv::BuiltInSampleId;
447
448 case glslang::EbvSamplePosition:
449 builder.addCapability(spv::CapabilitySampleRateShading);
450 return spv::BuiltInSamplePosition;
451
452 case glslang::EbvSampleMask:
453 builder.addCapability(spv::CapabilitySampleRateShading);
454 return spv::BuiltInSampleMask;
455
John Kessenich140f3df2015-06-26 16:58:36 -0600456 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600457 case glslang::EbvVertexId: return spv::BuiltInVertexId;
458 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700459 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
460 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600461 case glslang::EbvBaseVertex:
462 case glslang::EbvBaseInstance:
463 case glslang::EbvDrawId:
464 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600465 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600466 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600467 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
468 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
469 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600470 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
471 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
472 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
473 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
474 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
475 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
476 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600477 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
478 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
479 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
480 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
481 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
482 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
483 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
484 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800485 case glslang::EbvSubGroupSize:
486 case glslang::EbvSubGroupInvocation:
487 case glslang::EbvSubGroupEqMask:
488 case glslang::EbvSubGroupGeMask:
489 case glslang::EbvSubGroupGtMask:
490 case glslang::EbvSubGroupLeMask:
491 case glslang::EbvSubGroupLtMask:
492 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600493 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800494 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600495 default: return (spv::BuiltIn)spv::BadValue;
496 }
497}
498
Rex Xufc618912015-09-09 16:42:49 +0800499// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700500spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800501{
502 assert(type.getBasicType() == glslang::EbtSampler);
503
John Kessenich5d0fa972016-02-15 11:57:00 -0700504 // Check for capabilities
505 switch (type.getQualifier().layoutFormat) {
506 case glslang::ElfRg32f:
507 case glslang::ElfRg16f:
508 case glslang::ElfR11fG11fB10f:
509 case glslang::ElfR16f:
510 case glslang::ElfRgba16:
511 case glslang::ElfRgb10A2:
512 case glslang::ElfRg16:
513 case glslang::ElfRg8:
514 case glslang::ElfR16:
515 case glslang::ElfR8:
516 case glslang::ElfRgba16Snorm:
517 case glslang::ElfRg16Snorm:
518 case glslang::ElfRg8Snorm:
519 case glslang::ElfR16Snorm:
520 case glslang::ElfR8Snorm:
521
522 case glslang::ElfRg32i:
523 case glslang::ElfRg16i:
524 case glslang::ElfRg8i:
525 case glslang::ElfR16i:
526 case glslang::ElfR8i:
527
528 case glslang::ElfRgb10a2ui:
529 case glslang::ElfRg32ui:
530 case glslang::ElfRg16ui:
531 case glslang::ElfRg8ui:
532 case glslang::ElfR16ui:
533 case glslang::ElfR8ui:
534 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
535 break;
536
537 default:
538 break;
539 }
540
541 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800542 switch (type.getQualifier().layoutFormat) {
543 case glslang::ElfNone: return spv::ImageFormatUnknown;
544 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
545 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
546 case glslang::ElfR32f: return spv::ImageFormatR32f;
547 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
548 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
549 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
550 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
551 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
552 case glslang::ElfR16f: return spv::ImageFormatR16f;
553 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
554 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
555 case glslang::ElfRg16: return spv::ImageFormatRg16;
556 case glslang::ElfRg8: return spv::ImageFormatRg8;
557 case glslang::ElfR16: return spv::ImageFormatR16;
558 case glslang::ElfR8: return spv::ImageFormatR8;
559 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
560 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
561 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
562 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
563 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
564 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
565 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
566 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
567 case glslang::ElfR32i: return spv::ImageFormatR32i;
568 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
569 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
570 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
571 case glslang::ElfR16i: return spv::ImageFormatR16i;
572 case glslang::ElfR8i: return spv::ImageFormatR8i;
573 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
574 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
575 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
576 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
577 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
578 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
579 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
580 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
581 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
582 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
583 default: return (spv::ImageFormat)spv::BadValue;
584 }
585}
586
qining25262b32016-05-06 17:25:16 -0400587// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700588// descriptor set.
589bool IsDescriptorResource(const glslang::TType& type)
590{
John Kessenichf7497e22016-03-08 21:36:22 -0700591 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700592 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700593 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700594
595 // non block...
596 // basically samplerXXX/subpass/sampler/texture are all included
597 // if they are the global-scope-class, not the function parameter
598 // (or local, if they ever exist) class.
599 if (type.getBasicType() == glslang::EbtSampler)
600 return type.getQualifier().isUniformOrBuffer();
601
602 // None of the above.
603 return false;
604}
605
John Kesseniche0b6cad2015-12-24 10:30:13 -0700606void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
607{
608 if (child.layoutMatrix == glslang::ElmNone)
609 child.layoutMatrix = parent.layoutMatrix;
610
611 if (parent.invariant)
612 child.invariant = true;
613 if (parent.nopersp)
614 child.nopersp = true;
615 if (parent.flat)
616 child.flat = true;
617 if (parent.centroid)
618 child.centroid = true;
619 if (parent.patch)
620 child.patch = true;
621 if (parent.sample)
622 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800623 if (parent.coherent)
624 child.coherent = true;
625 if (parent.volatil)
626 child.volatil = true;
627 if (parent.restrict)
628 child.restrict = true;
629 if (parent.readonly)
630 child.readonly = true;
631 if (parent.writeonly)
632 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700633}
634
635bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
636{
John Kessenich7b9fa252016-01-21 18:56:57 -0700637 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700638 // - struct members can inherit from a struct declaration
639 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
640 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400641 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700642}
643
John Kessenich140f3df2015-06-26 16:58:36 -0600644//
645// Implement the TGlslangToSpvTraverser class.
646//
647
Lei Zhang17535f72016-05-04 15:55:59 -0400648TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
649 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
650 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600651 inMain(false), mainTerminated(false), linkageOnly(false),
652 glslangIntermediate(glslangIntermediate)
653{
654 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
655
656 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700657 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600658 stdBuiltins = builder.import("GLSL.std.450");
659 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700660 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
661 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600662
663 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600664 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
665 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600666 builder.addSourceExtension(it->c_str());
667
668 // Add the top-level modes for this shader.
669
John Kessenich92187592016-02-01 13:45:25 -0700670 if (glslangIntermediate->getXfbMode()) {
671 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600672 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700673 }
John Kessenich140f3df2015-06-26 16:58:36 -0600674
675 unsigned int mode;
676 switch (glslangIntermediate->getStage()) {
677 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600678 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600679 break;
680
681 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600682 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600683 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
684 break;
685
686 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600687 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600688 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700689 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
690 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
691 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600692 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600693 }
694 if (mode != spv::BadValue)
695 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
696
John Kesseniche6903322015-10-13 16:29:02 -0600697 switch (glslangIntermediate->getVertexSpacing()) {
698 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
699 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
700 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
701 default: mode = spv::BadValue; break;
702 }
703 if (mode != spv::BadValue)
704 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
705
706 switch (glslangIntermediate->getVertexOrder()) {
707 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
708 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
709 default: mode = spv::BadValue; break;
710 }
711 if (mode != spv::BadValue)
712 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
713
714 if (glslangIntermediate->getPointMode())
715 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600716 break;
717
718 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600719 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600720 switch (glslangIntermediate->getInputPrimitive()) {
721 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
722 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
723 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700724 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600725 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
726 default: mode = spv::BadValue; break;
727 }
728 if (mode != spv::BadValue)
729 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600730
John Kessenich140f3df2015-06-26 16:58:36 -0600731 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
732
733 switch (glslangIntermediate->getOutputPrimitive()) {
734 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
735 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
736 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
737 default: mode = spv::BadValue; break;
738 }
739 if (mode != spv::BadValue)
740 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
741 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
742 break;
743
744 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600745 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600746 if (glslangIntermediate->getPixelCenterInteger())
747 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600748
John Kessenich140f3df2015-06-26 16:58:36 -0600749 if (glslangIntermediate->getOriginUpperLeft())
750 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600751 else
752 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600753
754 if (glslangIntermediate->getEarlyFragmentTests())
755 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
756
757 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600758 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
759 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
760 default: mode = spv::BadValue; break;
761 }
762 if (mode != spv::BadValue)
763 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
764
765 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
766 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600767 break;
768
769 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600770 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600771 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
772 glslangIntermediate->getLocalSize(1),
773 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600774 break;
775
776 default:
777 break;
778 }
779
780}
781
John Kessenich7ba63412015-12-20 17:37:07 -0700782// Finish everything and dump
783void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
784{
785 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100786 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
787 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700788
qiningda397332016-03-09 19:54:03 -0500789 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700790 builder.dump(out);
791}
792
John Kessenich140f3df2015-06-26 16:58:36 -0600793TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
794{
795 if (! mainTerminated) {
796 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
797 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600798 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600799 }
800}
801
802//
803// Implement the traversal functions.
804//
805// Return true from interior nodes to have the external traversal
806// continue on to children. Return false if children were
807// already processed.
808//
809
810//
qining25262b32016-05-06 17:25:16 -0400811// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600812// - uniform/input reads
813// - output writes
814// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
815// - something simple that degenerates into the last bullet
816//
817void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
818{
qining75d1d802016-04-06 14:42:01 -0400819 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
820 if (symbol->getType().getQualifier().isSpecConstant())
821 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
822
John Kessenich140f3df2015-06-26 16:58:36 -0600823 // getSymbolId() will set up all the IO decorations on the first call.
824 // Formal function parameters were mapped during makeFunctions().
825 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700826
827 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
828 if (builder.isPointer(id)) {
829 spv::StorageClass sc = builder.getStorageClass(id);
830 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
831 iOSet.insert(id);
832 }
833
834 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700835 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600836 // Prepare to generate code for the access
837
838 // L-value chains will be computed left to right. We're on the symbol now,
839 // which is the left-most part of the access chain, so now is "clear" time,
840 // followed by setting the base.
841 builder.clearAccessChain();
842
843 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700844 // except for
845 // A) "const in" arguments to a function, which are an intermediate object.
846 // See comments in handleUserFunctionCall().
847 // B) Specialization constants (normal constant don't even come in as a variable),
848 // These are also pure R-values.
849 glslang::TQualifier qualifier = symbol->getQualifier();
850 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
851 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600852 builder.setAccessChainRValue(id);
853 else
854 builder.setAccessChainLValue(id);
855 }
856}
857
858bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
859{
qining40887662016-04-03 22:20:42 -0400860 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
861 if (node->getType().getQualifier().isSpecConstant())
862 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
863
John Kessenich140f3df2015-06-26 16:58:36 -0600864 // First, handle special cases
865 switch (node->getOp()) {
866 case glslang::EOpAssign:
867 case glslang::EOpAddAssign:
868 case glslang::EOpSubAssign:
869 case glslang::EOpMulAssign:
870 case glslang::EOpVectorTimesMatrixAssign:
871 case glslang::EOpVectorTimesScalarAssign:
872 case glslang::EOpMatrixTimesScalarAssign:
873 case glslang::EOpMatrixTimesMatrixAssign:
874 case glslang::EOpDivAssign:
875 case glslang::EOpModAssign:
876 case glslang::EOpAndAssign:
877 case glslang::EOpInclusiveOrAssign:
878 case glslang::EOpExclusiveOrAssign:
879 case glslang::EOpLeftShiftAssign:
880 case glslang::EOpRightShiftAssign:
881 // A bin-op assign "a += b" means the same thing as "a = a + b"
882 // where a is evaluated before b. For a simple assignment, GLSL
883 // says to evaluate the left before the right. So, always, left
884 // node then right node.
885 {
886 // get the left l-value, save it away
887 builder.clearAccessChain();
888 node->getLeft()->traverse(this);
889 spv::Builder::AccessChain lValue = builder.getAccessChain();
890
891 // evaluate the right
892 builder.clearAccessChain();
893 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700894 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600895
896 if (node->getOp() != glslang::EOpAssign) {
897 // the left is also an r-value
898 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700899 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600900
901 // do the operation
qining25262b32016-05-06 17:25:16 -0400902 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
903 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600904 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
905 node->getType().getBasicType());
906
907 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700908 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600909 }
910
911 // store the result
912 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800913 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600914
915 // assignments are expressions having an rValue after they are evaluated...
916 builder.clearAccessChain();
917 builder.setAccessChainRValue(rValue);
918 }
919 return false;
920 case glslang::EOpIndexDirect:
921 case glslang::EOpIndexDirectStruct:
922 {
923 // Get the left part of the access chain.
924 node->getLeft()->traverse(this);
925
926 // Add the next element in the chain
927
John Kessenich55e7d112015-11-15 21:33:39 -0700928 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600929 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
930 // This may be, e.g., an anonymous block-member selection, which generally need
931 // index remapping due to hidden members in anonymous blocks.
932 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700933 assert(remapper.size() > 0);
934 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600935 }
936
937 if (! node->getLeft()->getType().isArray() &&
938 node->getLeft()->getType().isVector() &&
939 node->getOp() == glslang::EOpIndexDirect) {
940 // This is essentially a hard-coded vector swizzle of size 1,
941 // so short circuit the access-chain stuff with a swizzle.
942 std::vector<unsigned> swizzle;
943 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600944 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600945 } else {
946 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600947 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenichebb50532016-05-16 19:22:05 -0600948
949 // Add capabilities here for accessing clip/cull distance
950 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
951 declareClipCullCapability(*node->getLeft()->getType().getStruct(), index);
John Kessenich140f3df2015-06-26 16:58:36 -0600952 }
953 }
954 return false;
955 case glslang::EOpIndexIndirect:
956 {
957 // Structure or array or vector indirection.
958 // Will use native SPIR-V access-chain for struct and array indirection;
959 // matrices are arrays of vectors, so will also work for a matrix.
960 // Will use the access chain's 'component' for variable index into a vector.
961
962 // This adapter is building access chains left to right.
963 // Set up the access chain to the left.
964 node->getLeft()->traverse(this);
965
966 // save it so that computing the right side doesn't trash it
967 spv::Builder::AccessChain partial = builder.getAccessChain();
968
969 // compute the next index in the chain
970 builder.clearAccessChain();
971 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700972 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600973
974 // restore the saved access chain
975 builder.setAccessChain(partial);
976
977 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600978 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600979 else
John Kessenichfa668da2015-09-13 14:46:30 -0600980 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600981 }
982 return false;
983 case glslang::EOpVectorSwizzle:
984 {
985 node->getLeft()->traverse(this);
986 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
987 std::vector<unsigned> swizzle;
988 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
989 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600990 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600991 }
992 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600993 case glslang::EOpLogicalOr:
994 case glslang::EOpLogicalAnd:
995 {
996
997 // These may require short circuiting, but can sometimes be done as straight
998 // binary operations. The right operand must be short circuited if it has
999 // side effects, and should probably be if it is complex.
1000 if (isTrivial(node->getRight()->getAsTyped()))
1001 break; // handle below as a normal binary operation
1002 // otherwise, we need to do dynamic short circuiting on the right operand
1003 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1004 builder.clearAccessChain();
1005 builder.setAccessChainRValue(result);
1006 }
1007 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001008 default:
1009 break;
1010 }
1011
1012 // Assume generic binary op...
1013
John Kessenich32cfd492016-02-02 12:37:46 -07001014 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001015 builder.clearAccessChain();
1016 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001017 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001018
John Kessenich32cfd492016-02-02 12:37:46 -07001019 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001020 builder.clearAccessChain();
1021 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001022 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001023
John Kessenich32cfd492016-02-02 12:37:46 -07001024 // get result
1025 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001026 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001027 convertGlslangToSpvType(node->getType()), left, right,
1028 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001029
John Kessenich50e57562015-12-21 21:21:11 -07001030 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001031 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001032 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001033 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001034 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001035 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001036 return false;
1037 }
John Kessenich140f3df2015-06-26 16:58:36 -06001038}
1039
1040bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1041{
qining40887662016-04-03 22:20:42 -04001042 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1043 if (node->getType().getQualifier().isSpecConstant())
1044 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1045
John Kessenichfc51d282015-08-19 13:34:18 -06001046 spv::Id result = spv::NoResult;
1047
1048 // try texturing first
1049 result = createImageTextureFunctionCall(node);
1050 if (result != spv::NoResult) {
1051 builder.clearAccessChain();
1052 builder.setAccessChainRValue(result);
1053
1054 return false; // done with this node
1055 }
1056
1057 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001058
1059 if (node->getOp() == glslang::EOpArrayLength) {
1060 // Quite special; won't want to evaluate the operand.
1061
1062 // Normal .length() would have been constant folded by the front-end.
1063 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001064 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001065 assert(node->getOperand()->getType().isRuntimeSizedArray());
1066 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1067 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001068 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1069 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001070
1071 builder.clearAccessChain();
1072 builder.setAccessChainRValue(length);
1073
1074 return false;
1075 }
1076
John Kessenichfc51d282015-08-19 13:34:18 -06001077 // Start by evaluating the operand
1078
John Kessenich140f3df2015-06-26 16:58:36 -06001079 builder.clearAccessChain();
1080 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001081
Rex Xufc618912015-09-09 16:42:49 +08001082 spv::Id operand = spv::NoResult;
1083
1084 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1085 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001086 node->getOp() == glslang::EOpAtomicCounter ||
1087 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001088 operand = builder.accessChainGetLValue(); // Special case l-value operands
1089 else
John Kessenich32cfd492016-02-02 12:37:46 -07001090 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001091
1092 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001093 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001094
1095 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001096 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001097 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001098
1099 // if not, then possibly an operation
1100 if (! result)
qining25262b32016-05-06 17:25:16 -04001101 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001102
1103 if (result) {
1104 builder.clearAccessChain();
1105 builder.setAccessChainRValue(result);
1106
1107 return false; // done with this node
1108 }
1109
1110 // it must be a special case, check...
1111 switch (node->getOp()) {
1112 case glslang::EOpPostIncrement:
1113 case glslang::EOpPostDecrement:
1114 case glslang::EOpPreIncrement:
1115 case glslang::EOpPreDecrement:
1116 {
1117 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001118 spv::Id one = 0;
1119 if (node->getBasicType() == glslang::EbtFloat)
1120 one = builder.makeFloatConstant(1.0F);
1121 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1122 one = builder.makeInt64Constant(1);
1123 else
1124 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001125 glslang::TOperator op;
1126 if (node->getOp() == glslang::EOpPreIncrement ||
1127 node->getOp() == glslang::EOpPostIncrement)
1128 op = glslang::EOpAdd;
1129 else
1130 op = glslang::EOpSub;
1131
qining25262b32016-05-06 17:25:16 -04001132 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1133 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001134 convertGlslangToSpvType(node->getType()), operand, one,
1135 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001136 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001137
1138 // The result of operation is always stored, but conditionally the
1139 // consumed result. The consumed result is always an r-value.
1140 builder.accessChainStore(result);
1141 builder.clearAccessChain();
1142 if (node->getOp() == glslang::EOpPreIncrement ||
1143 node->getOp() == glslang::EOpPreDecrement)
1144 builder.setAccessChainRValue(result);
1145 else
1146 builder.setAccessChainRValue(operand);
1147 }
1148
1149 return false;
1150
1151 case glslang::EOpEmitStreamVertex:
1152 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1153 return false;
1154 case glslang::EOpEndStreamPrimitive:
1155 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1156 return false;
1157
1158 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001159 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001160 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001161 }
John Kessenich140f3df2015-06-26 16:58:36 -06001162}
1163
1164bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1165{
qining27e04a02016-04-14 16:40:20 -04001166 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1167 if (node->getType().getQualifier().isSpecConstant())
1168 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1169
John Kessenichfc51d282015-08-19 13:34:18 -06001170 spv::Id result = spv::NoResult;
1171
1172 // try texturing
1173 result = createImageTextureFunctionCall(node);
1174 if (result != spv::NoResult) {
1175 builder.clearAccessChain();
1176 builder.setAccessChainRValue(result);
1177
1178 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001179 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001180 // "imageStore" is a special case, which has no result
1181 return false;
1182 }
John Kessenichfc51d282015-08-19 13:34:18 -06001183
John Kessenich140f3df2015-06-26 16:58:36 -06001184 glslang::TOperator binOp = glslang::EOpNull;
1185 bool reduceComparison = true;
1186 bool isMatrix = false;
1187 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001188 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 assert(node->getOp());
1191
1192 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1193
1194 switch (node->getOp()) {
1195 case glslang::EOpSequence:
1196 {
1197 if (preVisit)
1198 ++sequenceDepth;
1199 else
1200 --sequenceDepth;
1201
1202 if (sequenceDepth == 1) {
1203 // If this is the parent node of all the functions, we want to see them
1204 // early, so all call points have actual SPIR-V functions to reference.
1205 // In all cases, still let the traverser visit the children for us.
1206 makeFunctions(node->getAsAggregate()->getSequence());
1207
1208 // Also, we want all globals initializers to go into the entry of main(), before
1209 // anything else gets there, so visit out of order, doing them all now.
1210 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1211
1212 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1213 // so do them manually.
1214 visitFunctions(node->getAsAggregate()->getSequence());
1215
1216 return false;
1217 }
1218
1219 return true;
1220 }
1221 case glslang::EOpLinkerObjects:
1222 {
1223 if (visit == glslang::EvPreVisit)
1224 linkageOnly = true;
1225 else
1226 linkageOnly = false;
1227
1228 return true;
1229 }
1230 case glslang::EOpComma:
1231 {
1232 // processing from left to right naturally leaves the right-most
1233 // lying around in the access chain
1234 glslang::TIntermSequence& glslangOperands = node->getSequence();
1235 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1236 glslangOperands[i]->traverse(this);
1237
1238 return false;
1239 }
1240 case glslang::EOpFunction:
1241 if (visit == glslang::EvPreVisit) {
1242 if (isShaderEntrypoint(node)) {
1243 inMain = true;
1244 builder.setBuildPoint(shaderEntry->getLastBlock());
1245 } else {
1246 handleFunctionEntry(node);
1247 }
1248 } else {
1249 if (inMain)
1250 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001251 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001252 inMain = false;
1253 }
1254
1255 return true;
1256 case glslang::EOpParameters:
1257 // Parameters will have been consumed by EOpFunction processing, but not
1258 // the body, so we still visited the function node's children, making this
1259 // child redundant.
1260 return false;
1261 case glslang::EOpFunctionCall:
1262 {
1263 if (node->isUserDefined())
1264 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001265 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1266 if (result) {
1267 builder.clearAccessChain();
1268 builder.setAccessChainRValue(result);
1269 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001270 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001271
1272 return false;
1273 }
1274 case glslang::EOpConstructMat2x2:
1275 case glslang::EOpConstructMat2x3:
1276 case glslang::EOpConstructMat2x4:
1277 case glslang::EOpConstructMat3x2:
1278 case glslang::EOpConstructMat3x3:
1279 case glslang::EOpConstructMat3x4:
1280 case glslang::EOpConstructMat4x2:
1281 case glslang::EOpConstructMat4x3:
1282 case glslang::EOpConstructMat4x4:
1283 case glslang::EOpConstructDMat2x2:
1284 case glslang::EOpConstructDMat2x3:
1285 case glslang::EOpConstructDMat2x4:
1286 case glslang::EOpConstructDMat3x2:
1287 case glslang::EOpConstructDMat3x3:
1288 case glslang::EOpConstructDMat3x4:
1289 case glslang::EOpConstructDMat4x2:
1290 case glslang::EOpConstructDMat4x3:
1291 case glslang::EOpConstructDMat4x4:
1292 isMatrix = true;
1293 // fall through
1294 case glslang::EOpConstructFloat:
1295 case glslang::EOpConstructVec2:
1296 case glslang::EOpConstructVec3:
1297 case glslang::EOpConstructVec4:
1298 case glslang::EOpConstructDouble:
1299 case glslang::EOpConstructDVec2:
1300 case glslang::EOpConstructDVec3:
1301 case glslang::EOpConstructDVec4:
1302 case glslang::EOpConstructBool:
1303 case glslang::EOpConstructBVec2:
1304 case glslang::EOpConstructBVec3:
1305 case glslang::EOpConstructBVec4:
1306 case glslang::EOpConstructInt:
1307 case glslang::EOpConstructIVec2:
1308 case glslang::EOpConstructIVec3:
1309 case glslang::EOpConstructIVec4:
1310 case glslang::EOpConstructUint:
1311 case glslang::EOpConstructUVec2:
1312 case glslang::EOpConstructUVec3:
1313 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001314 case glslang::EOpConstructInt64:
1315 case glslang::EOpConstructI64Vec2:
1316 case glslang::EOpConstructI64Vec3:
1317 case glslang::EOpConstructI64Vec4:
1318 case glslang::EOpConstructUint64:
1319 case glslang::EOpConstructU64Vec2:
1320 case glslang::EOpConstructU64Vec3:
1321 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001322 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001323 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001324 {
1325 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001326 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001327 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1328 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001329 if (node->getOp() == glslang::EOpConstructTextureSampler)
1330 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1331 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001332 std::vector<spv::Id> constituents;
1333 for (int c = 0; c < (int)arguments.size(); ++c)
1334 constituents.push_back(arguments[c]);
1335 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001336 } else if (isMatrix)
1337 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1338 else
1339 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001340
1341 builder.clearAccessChain();
1342 builder.setAccessChainRValue(constructed);
1343
1344 return false;
1345 }
1346
1347 // These six are component-wise compares with component-wise results.
1348 // Forward on to createBinaryOperation(), requesting a vector result.
1349 case glslang::EOpLessThan:
1350 case glslang::EOpGreaterThan:
1351 case glslang::EOpLessThanEqual:
1352 case glslang::EOpGreaterThanEqual:
1353 case glslang::EOpVectorEqual:
1354 case glslang::EOpVectorNotEqual:
1355 {
1356 // Map the operation to a binary
1357 binOp = node->getOp();
1358 reduceComparison = false;
1359 switch (node->getOp()) {
1360 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1361 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1362 default: binOp = node->getOp(); break;
1363 }
1364
1365 break;
1366 }
1367 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001368 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001369 binOp = glslang::EOpMul;
1370 break;
1371 case glslang::EOpOuterProduct:
1372 // two vectors multiplied to make a matrix
1373 binOp = glslang::EOpOuterProduct;
1374 break;
1375 case glslang::EOpDot:
1376 {
qining25262b32016-05-06 17:25:16 -04001377 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001378 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001379 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001380 binOp = glslang::EOpMul;
1381 break;
1382 }
1383 case glslang::EOpMod:
1384 // when an aggregate, this is the floating-point mod built-in function,
1385 // which can be emitted by the one in createBinaryOperation()
1386 binOp = glslang::EOpMod;
1387 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001388 case glslang::EOpEmitVertex:
1389 case glslang::EOpEndPrimitive:
1390 case glslang::EOpBarrier:
1391 case glslang::EOpMemoryBarrier:
1392 case glslang::EOpMemoryBarrierAtomicCounter:
1393 case glslang::EOpMemoryBarrierBuffer:
1394 case glslang::EOpMemoryBarrierImage:
1395 case glslang::EOpMemoryBarrierShared:
1396 case glslang::EOpGroupMemoryBarrier:
1397 noReturnValue = true;
1398 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1399 break;
1400
John Kessenich426394d2015-07-23 10:22:48 -06001401 case glslang::EOpAtomicAdd:
1402 case glslang::EOpAtomicMin:
1403 case glslang::EOpAtomicMax:
1404 case glslang::EOpAtomicAnd:
1405 case glslang::EOpAtomicOr:
1406 case glslang::EOpAtomicXor:
1407 case glslang::EOpAtomicExchange:
1408 case glslang::EOpAtomicCompSwap:
1409 atomic = true;
1410 break;
1411
John Kessenich140f3df2015-06-26 16:58:36 -06001412 default:
1413 break;
1414 }
1415
1416 //
1417 // See if it maps to a regular operation.
1418 //
John Kessenich140f3df2015-06-26 16:58:36 -06001419 if (binOp != glslang::EOpNull) {
1420 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1421 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1422 assert(left && right);
1423
1424 builder.clearAccessChain();
1425 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001426 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 builder.clearAccessChain();
1429 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001430 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001431
qining25262b32016-05-06 17:25:16 -04001432 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1433 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001434 left->getType().getBasicType(), reduceComparison);
1435
1436 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001437 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001438 builder.clearAccessChain();
1439 builder.setAccessChainRValue(result);
1440
1441 return false;
1442 }
1443
John Kessenich426394d2015-07-23 10:22:48 -06001444 //
1445 // Create the list of operands.
1446 //
John Kessenich140f3df2015-06-26 16:58:36 -06001447 glslang::TIntermSequence& glslangOperands = node->getSequence();
1448 std::vector<spv::Id> operands;
1449 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1450 builder.clearAccessChain();
1451 glslangOperands[arg]->traverse(this);
1452
1453 // special case l-value operands; there are just a few
1454 bool lvalue = false;
1455 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001456 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001457 case glslang::EOpModf:
1458 if (arg == 1)
1459 lvalue = true;
1460 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001461 case glslang::EOpInterpolateAtSample:
1462 case glslang::EOpInterpolateAtOffset:
1463 if (arg == 0)
1464 lvalue = true;
1465 break;
Rex Xud4782c12015-09-06 16:30:11 +08001466 case glslang::EOpAtomicAdd:
1467 case glslang::EOpAtomicMin:
1468 case glslang::EOpAtomicMax:
1469 case glslang::EOpAtomicAnd:
1470 case glslang::EOpAtomicOr:
1471 case glslang::EOpAtomicXor:
1472 case glslang::EOpAtomicExchange:
1473 case glslang::EOpAtomicCompSwap:
1474 if (arg == 0)
1475 lvalue = true;
1476 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001477 case glslang::EOpAddCarry:
1478 case glslang::EOpSubBorrow:
1479 if (arg == 2)
1480 lvalue = true;
1481 break;
1482 case glslang::EOpUMulExtended:
1483 case glslang::EOpIMulExtended:
1484 if (arg >= 2)
1485 lvalue = true;
1486 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001487 default:
1488 break;
1489 }
1490 if (lvalue)
1491 operands.push_back(builder.accessChainGetLValue());
1492 else
John Kessenich32cfd492016-02-02 12:37:46 -07001493 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001494 }
John Kessenich426394d2015-07-23 10:22:48 -06001495
1496 if (atomic) {
1497 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001498 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001499 } else {
1500 // Pass through to generic operations.
1501 switch (glslangOperands.size()) {
1502 case 0:
1503 result = createNoArgOperation(node->getOp());
1504 break;
1505 case 1:
qining25262b32016-05-06 17:25:16 -04001506 result = createUnaryOperation(
1507 node->getOp(), precision,
1508 TranslateNoContractionDecoration(node->getType().getQualifier()),
1509 convertGlslangToSpvType(node->getType()), operands.front(),
1510 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001511 break;
1512 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001513 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001514 break;
1515 }
John Kessenich140f3df2015-06-26 16:58:36 -06001516 }
1517
1518 if (noReturnValue)
1519 return false;
1520
1521 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001522 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001523 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001524 } else {
1525 builder.clearAccessChain();
1526 builder.setAccessChainRValue(result);
1527 return false;
1528 }
1529}
1530
1531bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1532{
1533 // This path handles both if-then-else and ?:
1534 // The if-then-else has a node type of void, while
1535 // ?: has a non-void node type
1536 spv::Id result = 0;
1537 if (node->getBasicType() != glslang::EbtVoid) {
1538 // don't handle this as just on-the-fly temporaries, because there will be two names
1539 // and better to leave SSA to later passes
1540 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1541 }
1542
1543 // emit the condition before doing anything with selection
1544 node->getCondition()->traverse(this);
1545
1546 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001547 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001548
1549 if (node->getTrueBlock()) {
1550 // emit the "then" statement
1551 node->getTrueBlock()->traverse(this);
1552 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001553 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001554 }
1555
1556 if (node->getFalseBlock()) {
1557 ifBuilder.makeBeginElse();
1558 // emit the "else" statement
1559 node->getFalseBlock()->traverse(this);
1560 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001561 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001562 }
1563
1564 ifBuilder.makeEndIf();
1565
1566 if (result) {
1567 // GLSL only has r-values as the result of a :?, but
1568 // if we have an l-value, that can be more efficient if it will
1569 // become the base of a complex r-value expression, because the
1570 // next layer copies r-values into memory to use the access-chain mechanism
1571 builder.clearAccessChain();
1572 builder.setAccessChainLValue(result);
1573 }
1574
1575 return false;
1576}
1577
1578bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1579{
1580 // emit and get the condition before doing anything with switch
1581 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001582 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001583
1584 // browse the children to sort out code segments
1585 int defaultSegment = -1;
1586 std::vector<TIntermNode*> codeSegments;
1587 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1588 std::vector<int> caseValues;
1589 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1590 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1591 TIntermNode* child = *c;
1592 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001593 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001594 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001595 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001596 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1597 } else
1598 codeSegments.push_back(child);
1599 }
1600
qining25262b32016-05-06 17:25:16 -04001601 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001602 // statements between the last case and the end of the switch statement
1603 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1604 (int)codeSegments.size() == defaultSegment)
1605 codeSegments.push_back(nullptr);
1606
1607 // make the switch statement
1608 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001609 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001610
1611 // emit all the code in the segments
1612 breakForLoop.push(false);
1613 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1614 builder.nextSwitchSegment(segmentBlocks, s);
1615 if (codeSegments[s])
1616 codeSegments[s]->traverse(this);
1617 else
1618 builder.addSwitchBreak();
1619 }
1620 breakForLoop.pop();
1621
1622 builder.endSwitch(segmentBlocks);
1623
1624 return false;
1625}
1626
1627void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1628{
1629 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001630 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001631
1632 builder.clearAccessChain();
1633 builder.setAccessChainRValue(constant);
1634}
1635
1636bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1637{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001638 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001639 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001640 // Spec requires back edges to target header blocks, and every header block
1641 // must dominate its merge block. Make a header block first to ensure these
1642 // conditions are met. By definition, it will contain OpLoopMerge, followed
1643 // by a block-ending branch. But we don't want to put any other body/test
1644 // instructions in it, since the body/test may have arbitrary instructions,
1645 // including merges of its own.
1646 builder.setBuildPoint(&blocks.head);
1647 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001648 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001649 spv::Block& test = builder.makeNewBlock();
1650 builder.createBranch(&test);
1651
1652 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001653 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001654 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001655 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001656 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1657
1658 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001659 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001660 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001661 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001662 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001663 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001664
1665 builder.setBuildPoint(&blocks.continue_target);
1666 if (node->getTerminal())
1667 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001668 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001669 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001670 builder.createBranch(&blocks.body);
1671
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001672 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001673 builder.setBuildPoint(&blocks.body);
1674 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001675 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001676 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001677 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001678
1679 builder.setBuildPoint(&blocks.continue_target);
1680 if (node->getTerminal())
1681 node->getTerminal()->traverse(this);
1682 if (node->getTest()) {
1683 node->getTest()->traverse(this);
1684 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001685 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001686 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001687 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001688 // TODO: unless there was a break/return/discard instruction
1689 // somewhere in the body, this is an infinite loop, so we should
1690 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001691 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001692 }
John Kessenich140f3df2015-06-26 16:58:36 -06001693 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001694 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001695 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001696 return false;
1697}
1698
1699bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1700{
1701 if (node->getExpression())
1702 node->getExpression()->traverse(this);
1703
1704 switch (node->getFlowOp()) {
1705 case glslang::EOpKill:
1706 builder.makeDiscard();
1707 break;
1708 case glslang::EOpBreak:
1709 if (breakForLoop.top())
1710 builder.createLoopExit();
1711 else
1712 builder.addSwitchBreak();
1713 break;
1714 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001715 builder.createLoopContinue();
1716 break;
1717 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001718 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001719 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001720 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001721 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001722
1723 builder.clearAccessChain();
1724 break;
1725
1726 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001727 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001728 break;
1729 }
1730
1731 return false;
1732}
1733
1734spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1735{
qining25262b32016-05-06 17:25:16 -04001736 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001737 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001738 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001739 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001740 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001741 }
1742
1743 // Now, handle actual variables
1744 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1745 spv::Id spvType = convertGlslangToSpvType(node->getType());
1746
1747 const char* name = node->getName().c_str();
1748 if (glslang::IsAnonymous(name))
1749 name = "";
1750
1751 return builder.createVariable(storageClass, spvType, name);
1752}
1753
1754// Return type Id of the sampled type.
1755spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1756{
1757 switch (sampler.type) {
1758 case glslang::EbtFloat: return builder.makeFloatType(32);
1759 case glslang::EbtInt: return builder.makeIntType(32);
1760 case glslang::EbtUint: return builder.makeUintType(32);
1761 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001762 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001763 return builder.makeFloatType(32);
1764 }
1765}
1766
John Kessenich3ac051e2015-12-20 11:29:16 -07001767// Convert from a glslang type to an SPV type, by calling into a
1768// recursive version of this function. This establishes the inherited
1769// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001770spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1771{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001772 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001773}
1774
1775// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001776// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001777spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001778{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001779 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001780
1781 switch (type.getBasicType()) {
1782 case glslang::EbtVoid:
1783 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001784 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001785 break;
1786 case glslang::EbtFloat:
1787 spvType = builder.makeFloatType(32);
1788 break;
1789 case glslang::EbtDouble:
1790 spvType = builder.makeFloatType(64);
1791 break;
1792 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001793 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1794 // a 32-bit int where non-0 means true.
1795 if (explicitLayout != glslang::ElpNone)
1796 spvType = builder.makeUintType(32);
1797 else
1798 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001799 break;
1800 case glslang::EbtInt:
1801 spvType = builder.makeIntType(32);
1802 break;
1803 case glslang::EbtUint:
1804 spvType = builder.makeUintType(32);
1805 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001806 case glslang::EbtInt64:
1807 builder.addCapability(spv::CapabilityInt64);
1808 spvType = builder.makeIntType(64);
1809 break;
1810 case glslang::EbtUint64:
1811 builder.addCapability(spv::CapabilityInt64);
1812 spvType = builder.makeUintType(64);
1813 break;
John Kessenich426394d2015-07-23 10:22:48 -06001814 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001815 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 -06001816 spvType = builder.makeUintType(32);
1817 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001818 case glslang::EbtSampler:
1819 {
1820 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001821 if (sampler.sampler) {
1822 // pure sampler
1823 spvType = builder.makeSamplerType();
1824 } else {
1825 // an image is present, make its type
1826 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1827 sampler.image ? 2 : 1, TranslateImageFormat(type));
1828 if (sampler.combined) {
1829 // already has both image and sampler, make the combined type
1830 spvType = builder.makeSampledImageType(spvType);
1831 }
John Kessenich55e7d112015-11-15 21:33:39 -07001832 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001833 }
John Kessenich140f3df2015-06-26 16:58:36 -06001834 break;
1835 case glslang::EbtStruct:
1836 case glslang::EbtBlock:
1837 {
1838 // If we've seen this struct type, return it
1839 const glslang::TTypeList* glslangStruct = type.getStruct();
1840 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001841
1842 // Try to share structs for different layouts, but not yet for other
1843 // kinds of qualification (primarily not yet including interpolant qualification).
1844 if (! HasNonLayoutQualifiers(qualifier))
1845 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1846 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001847 break;
1848
1849 // else, we haven't seen it...
1850
1851 // Create a vector of struct types for SPIR-V to consume
1852 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1853 if (type.getBasicType() == glslang::EbtBlock)
1854 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001855 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001856 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1857 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1858 if (glslangType.hiddenMember()) {
1859 ++memberDelta;
1860 if (type.getBasicType() == glslang::EbtBlock)
1861 memberRemapper[glslangStruct][i] = -1;
1862 } else {
1863 if (type.getBasicType() == glslang::EbtBlock)
1864 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001865 // modify just this child's view of the qualifier
1866 glslang::TQualifier subQualifier = glslangType.getQualifier();
1867 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001868
1869 // manually inherit location; it's more complex
1870 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1871 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1872 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001873 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001874
1875 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001876 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001877 }
1878 }
1879
1880 // Make the SPIR-V type
1881 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001882 if (! HasNonLayoutQualifiers(qualifier))
1883 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001884
1885 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001886 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001887 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001888 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1889 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1890 int member = i;
1891 if (type.getBasicType() == glslang::EbtBlock)
1892 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001893
John Kesseniche0b6cad2015-12-24 10:30:13 -07001894 // modify just this child's view of the qualifier
1895 glslang::TQualifier subQualifier = glslangType.getQualifier();
1896 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001897
John Kessenich140f3df2015-06-26 16:58:36 -06001898 // using -1 above to indicate a hidden member
1899 if (member >= 0) {
1900 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001901 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001902 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
Rex Xubbceed72016-05-21 09:40:44 +08001903 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001904 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
scygan8add1512016-05-06 16:54:54 +02001905 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
Rex Xubbceed72016-05-21 09:40:44 +08001906 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(subQualifier));
scygan8add1512016-05-06 16:54:54 +02001907 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001908 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001909
Rex Xu1da878f2016-02-21 20:59:01 +08001910 if (qualifier.storage == glslang::EvqBuffer) {
1911 std::vector<spv::Decoration> memory;
1912 TranslateMemoryDecoration(subQualifier, memory);
1913 for (unsigned int i = 0; i < memory.size(); ++i)
1914 addMemberDecoration(spvType, member, memory[i]);
1915 }
1916
John Kessenich09677482016-02-19 12:21:50 -07001917 // compute location decoration; tricky based on whether inheritance is at play
1918 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1919 // probably move to the linker stage of the front end proper, and just have the
1920 // answer sitting already distributed throughout the individual member locations.
1921 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001922 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001923 // struct members should not have explicit locations
1924 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001925 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001926 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001927 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1928 // The members, and their nested types, must not themselves have Location decorations.
1929 }
John Kessenich09677482016-02-19 12:21:50 -07001930 else if (qualifier.hasLocation()) // inheritance
1931 location = qualifier.layoutLocation + locationOffset;
1932 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001933 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001934 if (location >= 0)
1935 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1936
1937 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001938 if (glslangType.getQualifier().hasComponent())
1939 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1940 if (glslangType.getQualifier().hasXfbOffset())
1941 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001942 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001943 // figure out what to do with offset, which is accumulating
1944 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001945 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001946 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001947 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001948 offset = nextOffset;
1949 }
John Kessenich140f3df2015-06-26 16:58:36 -06001950
John Kessenichf85e8062015-12-19 13:57:10 -07001951 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001952 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001953
John Kessenich140f3df2015-06-26 16:58:36 -06001954 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001955 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001956 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001957 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001958 }
1959 }
1960
1961 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001962 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001963 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001964 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001965 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001966 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001967 }
John Kessenich140f3df2015-06-26 16:58:36 -06001968 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001969 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001970 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001971 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001972 if (type.getQualifier().hasXfbBuffer())
1973 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1974 }
1975 }
1976 break;
1977 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001978 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001979 break;
1980 }
1981
1982 if (type.isMatrix())
1983 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1984 else {
1985 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1986 if (type.getVectorSize() > 1)
1987 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1988 }
1989
1990 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001991 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1992
John Kessenichc9a80832015-09-12 12:17:44 -06001993 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001994 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001995 // We need to decorate array strides for types needing explicit layout, except blocks.
1996 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001997 // Use a dummy glslang type for querying internal strides of
1998 // arrays of arrays, but using just a one-dimensional array.
1999 glslang::TType simpleArrayType(type, 0); // deference type of the array
2000 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2001 simpleArrayType.getArraySizes().dereference();
2002
2003 // Will compute the higher-order strides here, rather than making a whole
2004 // pile of types and doing repetitive recursion on their contents.
2005 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2006 }
John Kessenichf8842e52016-01-04 19:22:56 -07002007
2008 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002009 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002010 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002011 if (stride > 0)
2012 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002013 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002014 }
2015 } else {
2016 // single-dimensional array, and don't yet have stride
2017
John Kessenichf8842e52016-01-04 19:22:56 -07002018 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002019 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2020 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002021 }
John Kessenich31ed4832015-09-09 17:51:38 -06002022
John Kessenichc9a80832015-09-12 12:17:44 -06002023 // Do the outer dimension, which might not be known for a runtime-sized array
2024 if (type.isRuntimeSizedArray()) {
2025 spvType = builder.makeRuntimeArray(spvType);
2026 } else {
2027 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002028 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002029 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002030 if (stride > 0)
2031 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002032 }
2033
2034 return spvType;
2035}
2036
John Kessenich6c292d32016-02-15 20:58:50 -07002037// Turn the expression forming the array size into an id.
2038// This is not quite trivial, because of specialization constants.
2039// Sometimes, a raw constant is turned into an Id, and sometimes
2040// a specialization constant expression is.
2041spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2042{
2043 // First, see if this is sized with a node, meaning a specialization constant:
2044 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2045 if (specNode != nullptr) {
2046 builder.clearAccessChain();
2047 specNode->traverse(this);
2048 return accessChainLoad(specNode->getAsTyped()->getType());
2049 }
qining25262b32016-05-06 17:25:16 -04002050
John Kessenich6c292d32016-02-15 20:58:50 -07002051 // Otherwise, need a compile-time (front end) size, get it:
2052 int size = arraySizes.getDimSize(dim);
2053 assert(size > 0);
2054 return builder.makeUintConstant(size);
2055}
2056
John Kessenich103bef92016-02-08 21:38:15 -07002057// Wrap the builder's accessChainLoad to:
2058// - localize handling of RelaxedPrecision
2059// - use the SPIR-V inferred type instead of another conversion of the glslang type
2060// (avoids unnecessary work and possible type punning for structures)
2061// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002062spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2063{
John Kessenich103bef92016-02-08 21:38:15 -07002064 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2065 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2066
2067 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002068 if (type.getBasicType() == glslang::EbtBool) {
2069 if (builder.isScalarType(nominalTypeId)) {
2070 // Conversion for bool
2071 spv::Id boolType = builder.makeBoolType();
2072 if (nominalTypeId != boolType)
2073 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2074 } else if (builder.isVectorType(nominalTypeId)) {
2075 // Conversion for bvec
2076 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2077 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2078 if (nominalTypeId != bvecType)
2079 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2080 }
2081 }
John Kessenich103bef92016-02-08 21:38:15 -07002082
2083 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002084}
2085
Rex Xu27253232016-02-23 17:51:09 +08002086// Wrap the builder's accessChainStore to:
2087// - do conversion of concrete to abstract type
2088void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2089{
2090 // Need to convert to abstract types when necessary
2091 if (type.getBasicType() == glslang::EbtBool) {
2092 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2093
2094 if (builder.isScalarType(nominalTypeId)) {
2095 // Conversion for bool
2096 spv::Id boolType = builder.makeBoolType();
2097 if (nominalTypeId != boolType) {
2098 spv::Id zero = builder.makeUintConstant(0);
2099 spv::Id one = builder.makeUintConstant(1);
2100 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2101 }
2102 } else if (builder.isVectorType(nominalTypeId)) {
2103 // Conversion for bvec
2104 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2105 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2106 if (nominalTypeId != bvecType) {
2107 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2108 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2109 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2110 }
2111 }
2112 }
2113
2114 builder.accessChainStore(rvalue);
2115}
2116
John Kessenichf85e8062015-12-19 13:57:10 -07002117// Decide whether or not this type should be
2118// decorated with offsets and strides, and if so
2119// whether std140 or std430 rules should be applied.
2120glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002121{
John Kessenichf85e8062015-12-19 13:57:10 -07002122 // has to be a block
2123 if (type.getBasicType() != glslang::EbtBlock)
2124 return glslang::ElpNone;
2125
2126 // has to be a uniform or buffer block
2127 if (type.getQualifier().storage != glslang::EvqUniform &&
2128 type.getQualifier().storage != glslang::EvqBuffer)
2129 return glslang::ElpNone;
2130
2131 // return the layout to use
2132 switch (type.getQualifier().layoutPacking) {
2133 case glslang::ElpStd140:
2134 case glslang::ElpStd430:
2135 return type.getQualifier().layoutPacking;
2136 default:
2137 return glslang::ElpNone;
2138 }
John Kessenich31ed4832015-09-09 17:51:38 -06002139}
2140
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002141// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002142int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002143{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002144 int size;
John Kessenich49987892015-12-29 17:11:44 -07002145 int stride;
2146 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002147
2148 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002149}
2150
John Kessenich49987892015-12-29 17:11:44 -07002151// 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 -07002152// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002153int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002154{
John Kessenich49987892015-12-29 17:11:44 -07002155 glslang::TType elementType;
2156 elementType.shallowCopy(matrixType);
2157 elementType.clearArraySizes();
2158
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002159 int size;
John Kessenich49987892015-12-29 17:11:44 -07002160 int stride;
2161 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2162
2163 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002164}
2165
John Kessenich5e4b1242015-08-06 22:53:06 -06002166// Given a member type of a struct, realign the current offset for it, and compute
2167// the next (not yet aligned) offset for the next member, which will get aligned
2168// on the next call.
2169// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2170// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2171// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002172void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002173 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002174{
2175 // this will get a positive value when deemed necessary
2176 nextOffset = -1;
2177
John Kessenich5e4b1242015-08-06 22:53:06 -06002178 // override anything in currentOffset with user-set offset
2179 if (memberType.getQualifier().hasOffset())
2180 currentOffset = memberType.getQualifier().layoutOffset;
2181
2182 // It could be that current linker usage in glslang updated all the layoutOffset,
2183 // in which case the following code does not matter. But, that's not quite right
2184 // once cross-compilation unit GLSL validation is done, as the original user
2185 // settings are needed in layoutOffset, and then the following will come into play.
2186
John Kessenichf85e8062015-12-19 13:57:10 -07002187 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002188 if (! memberType.getQualifier().hasOffset())
2189 currentOffset = -1;
2190
2191 return;
2192 }
2193
John Kessenichf85e8062015-12-19 13:57:10 -07002194 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002195 if (currentOffset < 0)
2196 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002197
John Kessenich5e4b1242015-08-06 22:53:06 -06002198 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2199 // but possibly not yet correctly aligned.
2200
2201 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002202 int dummyStride;
2203 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002204 glslang::RoundToPow2(currentOffset, memberAlignment);
2205 nextOffset = currentOffset + memberSize;
2206}
2207
John Kessenichebb50532016-05-16 19:22:05 -06002208void TGlslangToSpvTraverser::declareClipCullCapability(const glslang::TTypeList& members, int member)
2209{
2210 if (members[member].type->getQualifier().builtIn == glslang::EbvClipDistance)
2211 builder.addCapability(spv::CapabilityClipDistance);
2212 if (members[member].type->getQualifier().builtIn == glslang::EbvCullDistance)
2213 builder.addCapability(spv::CapabilityCullDistance);
2214}
2215
John Kessenich140f3df2015-06-26 16:58:36 -06002216bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2217{
John Kessenich4d65ee32016-03-12 18:17:47 -07002218 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002219 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002220 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002221}
2222
2223// Make all the functions, skeletally, without actually visiting their bodies.
2224void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2225{
2226 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2227 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2228 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2229 continue;
2230
2231 // We're on a user function. Set up the basic interface for the function now,
2232 // so that it's available to call.
2233 // Translating the body will happen later.
2234 //
qining25262b32016-05-06 17:25:16 -04002235 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002236 // function. What it is an address of varies:
2237 //
2238 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2239 // so that write needs to be to a copy, hence the address of a copy works.
2240 //
2241 // - "const in" parameters can just be the r-value, as no writes need occur.
2242 //
2243 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2244 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2245
2246 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002247 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002248 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2249
2250 for (int p = 0; p < (int)parameters.size(); ++p) {
2251 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2252 spv::Id typeId = convertGlslangToSpvType(paramType);
2253 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2254 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2255 else
2256 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002257 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002258 paramTypes.push_back(typeId);
2259 }
2260
2261 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002262 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2263 convertGlslangToSpvType(glslFunction->getType()),
2264 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002265
2266 // Track function to emit/call later
2267 functionMap[glslFunction->getName().c_str()] = function;
2268
2269 // Set the parameter id's
2270 for (int p = 0; p < (int)parameters.size(); ++p) {
2271 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2272 // give a name too
2273 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2274 }
2275 }
2276}
2277
2278// Process all the initializers, while skipping the functions and link objects
2279void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2280{
2281 builder.setBuildPoint(shaderEntry->getLastBlock());
2282 for (int i = 0; i < (int)initializers.size(); ++i) {
2283 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2284 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2285
2286 // We're on a top-level node that's not a function. Treat as an initializer, whose
2287 // code goes into the beginning of main.
2288 initializer->traverse(this);
2289 }
2290 }
2291}
2292
2293// Process all the functions, while skipping initializers.
2294void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2295{
2296 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2297 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2298 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2299 node->traverse(this);
2300 }
2301}
2302
2303void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2304{
qining25262b32016-05-06 17:25:16 -04002305 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002306 // that called makeFunctions().
2307 spv::Function* function = functionMap[node->getName().c_str()];
2308 spv::Block* functionBlock = function->getEntryBlock();
2309 builder.setBuildPoint(functionBlock);
2310}
2311
Rex Xu04db3f52015-09-16 11:44:02 +08002312void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002313{
Rex Xufc618912015-09-09 16:42:49 +08002314 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002315
2316 glslang::TSampler sampler = {};
2317 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002318 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002319 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2320 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2321 }
2322
John Kessenich140f3df2015-06-26 16:58:36 -06002323 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2324 builder.clearAccessChain();
2325 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002326
2327 // Special case l-value operands
2328 bool lvalue = false;
2329 switch (node.getOp()) {
2330 case glslang::EOpImageAtomicAdd:
2331 case glslang::EOpImageAtomicMin:
2332 case glslang::EOpImageAtomicMax:
2333 case glslang::EOpImageAtomicAnd:
2334 case glslang::EOpImageAtomicOr:
2335 case glslang::EOpImageAtomicXor:
2336 case glslang::EOpImageAtomicExchange:
2337 case glslang::EOpImageAtomicCompSwap:
2338 if (i == 0)
2339 lvalue = true;
2340 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002341 case glslang::EOpSparseImageLoad:
2342 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2343 lvalue = true;
2344 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002345 case glslang::EOpSparseTexture:
2346 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2347 lvalue = true;
2348 break;
2349 case glslang::EOpSparseTextureClamp:
2350 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2351 lvalue = true;
2352 break;
2353 case glslang::EOpSparseTextureLod:
2354 case glslang::EOpSparseTextureOffset:
2355 if (i == 3)
2356 lvalue = true;
2357 break;
2358 case glslang::EOpSparseTextureFetch:
2359 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2360 lvalue = true;
2361 break;
2362 case glslang::EOpSparseTextureFetchOffset:
2363 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2364 lvalue = true;
2365 break;
2366 case glslang::EOpSparseTextureLodOffset:
2367 case glslang::EOpSparseTextureGrad:
2368 case glslang::EOpSparseTextureOffsetClamp:
2369 if (i == 4)
2370 lvalue = true;
2371 break;
2372 case glslang::EOpSparseTextureGradOffset:
2373 case glslang::EOpSparseTextureGradClamp:
2374 if (i == 5)
2375 lvalue = true;
2376 break;
2377 case glslang::EOpSparseTextureGradOffsetClamp:
2378 if (i == 6)
2379 lvalue = true;
2380 break;
2381 case glslang::EOpSparseTextureGather:
2382 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2383 lvalue = true;
2384 break;
2385 case glslang::EOpSparseTextureGatherOffset:
2386 case glslang::EOpSparseTextureGatherOffsets:
2387 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2388 lvalue = true;
2389 break;
Rex Xufc618912015-09-09 16:42:49 +08002390 default:
2391 break;
2392 }
2393
Rex Xu6b86d492015-09-16 17:48:22 +08002394 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002395 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002396 else
John Kessenich32cfd492016-02-02 12:37:46 -07002397 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002398 }
2399}
2400
John Kessenichfc51d282015-08-19 13:34:18 -06002401void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002402{
John Kessenichfc51d282015-08-19 13:34:18 -06002403 builder.clearAccessChain();
2404 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002405 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002406}
John Kessenich140f3df2015-06-26 16:58:36 -06002407
John Kessenichfc51d282015-08-19 13:34:18 -06002408spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2409{
Rex Xufc618912015-09-09 16:42:49 +08002410 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002411 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002412 }
2413
John Kessenichfc51d282015-08-19 13:34:18 -06002414 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002415 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2416 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2417 std::vector<spv::Id> arguments;
2418 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002419 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002420 else
2421 translateArguments(*node->getAsUnaryNode(), arguments);
2422 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2423
2424 spv::Builder::TextureParameters params = { };
2425 params.sampler = arguments[0];
2426
Rex Xu04db3f52015-09-16 11:44:02 +08002427 glslang::TCrackedTextureOp cracked;
2428 node->crackTexture(sampler, cracked);
2429
John Kessenichfc51d282015-08-19 13:34:18 -06002430 // Check for queries
2431 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002432 // a sampled image needs to have the image extracted first
2433 if (builder.isSampledImage(params.sampler))
2434 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002435 switch (node->getOp()) {
2436 case glslang::EOpImageQuerySize:
2437 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002438 if (arguments.size() > 1) {
2439 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002440 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002441 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002442 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002443 case glslang::EOpImageQuerySamples:
2444 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002445 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002446 case glslang::EOpTextureQueryLod:
2447 params.coords = arguments[1];
2448 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2449 case glslang::EOpTextureQueryLevels:
2450 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002451 case glslang::EOpSparseTexelsResident:
2452 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002453 default:
2454 assert(0);
2455 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002456 }
John Kessenich140f3df2015-06-26 16:58:36 -06002457 }
2458
Rex Xufc618912015-09-09 16:42:49 +08002459 // Check for image functions other than queries
2460 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002461 std::vector<spv::Id> operands;
2462 auto opIt = arguments.begin();
2463 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002464
2465 // Handle subpass operations
2466 // TODO: GLSL should change to have the "MS" only on the type rather than the
2467 // built-in function.
2468 if (cracked.subpass) {
2469 // add on the (0,0) coordinate
2470 spv::Id zero = builder.makeIntConstant(0);
2471 std::vector<spv::Id> comps;
2472 comps.push_back(zero);
2473 comps.push_back(zero);
2474 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2475 if (sampler.ms) {
2476 operands.push_back(spv::ImageOperandsSampleMask);
2477 operands.push_back(*(opIt++));
2478 }
2479 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2480 }
2481
John Kessenich56bab042015-09-16 10:54:31 -06002482 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002483 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002484 if (sampler.ms) {
2485 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002486 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002487 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002488 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2489 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002490 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002491 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002492 if (sampler.ms) {
2493 operands.push_back(*(opIt + 1));
2494 operands.push_back(spv::ImageOperandsSampleMask);
2495 operands.push_back(*opIt);
2496 } else
2497 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002498 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002499 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2500 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002501 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002502 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2503 builder.addCapability(spv::CapabilitySparseResidency);
2504 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2505 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2506
2507 if (sampler.ms) {
2508 operands.push_back(spv::ImageOperandsSampleMask);
2509 operands.push_back(*opIt++);
2510 }
2511
2512 // Create the return type that was a special structure
2513 spv::Id texelOut = *opIt;
2514 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2515 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2516 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2517
2518 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2519
2520 // Decode the return type
2521 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2522 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002523 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002524 // Process image atomic operations
2525
2526 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2527 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002528 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002529
Rex Xufc618912015-09-09 16:42:49 +08002530 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002531 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002532
2533 std::vector<spv::Id> operands;
2534 operands.push_back(pointer);
2535 for (; opIt != arguments.end(); ++opIt)
2536 operands.push_back(*opIt);
2537
Rex Xu04db3f52015-09-16 11:44:02 +08002538 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002539 }
2540 }
2541
2542 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002543 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002544 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2545
John Kessenichfc51d282015-08-19 13:34:18 -06002546 // check for bias argument
2547 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002548 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002549 int nonBiasArgCount = 2;
2550 if (cracked.offset)
2551 ++nonBiasArgCount;
2552 if (cracked.grad)
2553 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002554 if (cracked.lodClamp)
2555 ++nonBiasArgCount;
2556 if (sparse)
2557 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002558
2559 if ((int)arguments.size() > nonBiasArgCount)
2560 bias = true;
2561 }
2562
John Kessenichfc51d282015-08-19 13:34:18 -06002563 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002564
John Kessenichfc51d282015-08-19 13:34:18 -06002565 params.coords = arguments[1];
2566 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002567 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002568
2569 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002570 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002571 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002572 ++extraArgs;
2573 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002574 params.Dref = arguments[2];
2575 ++extraArgs;
2576 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002577 std::vector<spv::Id> indexes;
2578 int comp;
2579 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002580 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002581 else
2582 comp = builder.getNumComponents(params.coords) - 1;
2583 indexes.push_back(comp);
2584 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2585 }
2586 if (cracked.lod) {
2587 params.lod = arguments[2];
2588 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002589 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2590 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2591 noImplicitLod = true;
2592 }
2593 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002594 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002595 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002596 }
2597 if (cracked.grad) {
2598 params.gradX = arguments[2 + extraArgs];
2599 params.gradY = arguments[3 + extraArgs];
2600 extraArgs += 2;
2601 }
John Kessenich55e7d112015-11-15 21:33:39 -07002602 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002603 params.offset = arguments[2 + extraArgs];
2604 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002605 } else if (cracked.offsets) {
2606 params.offsets = arguments[2 + extraArgs];
2607 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002608 }
Rex Xu48edadf2015-12-31 16:11:41 +08002609 if (cracked.lodClamp) {
2610 params.lodClamp = arguments[2 + extraArgs];
2611 ++extraArgs;
2612 }
2613 if (sparse) {
2614 params.texelOut = arguments[2 + extraArgs];
2615 ++extraArgs;
2616 }
John Kessenichfc51d282015-08-19 13:34:18 -06002617 if (bias) {
2618 params.bias = arguments[2 + extraArgs];
2619 ++extraArgs;
2620 }
John Kessenich55e7d112015-11-15 21:33:39 -07002621 if (cracked.gather && ! sampler.shadow) {
2622 // default component is 0, if missing, otherwise an argument
2623 if (2 + extraArgs < (int)arguments.size()) {
2624 params.comp = arguments[2 + extraArgs];
2625 ++extraArgs;
2626 } else {
2627 params.comp = builder.makeIntConstant(0);
2628 }
2629 }
John Kessenichfc51d282015-08-19 13:34:18 -06002630
John Kessenich019f08f2016-02-15 15:40:42 -07002631 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002632}
2633
2634spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2635{
2636 // Grab the function's pointer from the previously created function
2637 spv::Function* function = functionMap[node->getName().c_str()];
2638 if (! function)
2639 return 0;
2640
2641 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2642 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2643
2644 // See comments in makeFunctions() for details about the semantics for parameter passing.
2645 //
2646 // These imply we need a four step process:
2647 // 1. Evaluate the arguments
2648 // 2. Allocate and make copies of in, out, and inout arguments
2649 // 3. Make the call
2650 // 4. Copy back the results
2651
2652 // 1. Evaluate the arguments
2653 std::vector<spv::Builder::AccessChain> lValues;
2654 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002655 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002656 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002657 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002658 // build l-value
2659 builder.clearAccessChain();
2660 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002661 argTypes.push_back(&paramType);
2662 // keep outputs as and samplers l-values, evaluate input-only as r-values
2663 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.getBasicType() == glslang::EbtSampler) {
John Kessenich140f3df2015-06-26 16:58:36 -06002664 // save l-value
2665 lValues.push_back(builder.getAccessChain());
2666 } else {
2667 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002668 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002669 }
2670 }
2671
2672 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2673 // copy the original into that space.
2674 //
2675 // Also, build up the list of actual arguments to pass in for the call
2676 int lValueCount = 0;
2677 int rValueCount = 0;
2678 std::vector<spv::Id> spvArgs;
2679 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002680 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002681 spv::Id arg;
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002682 if (paramType.getBasicType() == glslang::EbtSampler) {
2683 builder.setAccessChain(lValues[lValueCount]);
2684 arg = builder.accessChainGetLValue();
2685 ++lValueCount;
2686 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002687 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002688 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2689 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2690 // need to copy the input into output space
2691 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002692 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002693 builder.createStore(copy, arg);
2694 }
2695 ++lValueCount;
2696 } else {
2697 arg = rValues[rValueCount];
2698 ++rValueCount;
2699 }
2700 spvArgs.push_back(arg);
2701 }
2702
2703 // 3. Make the call.
2704 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002705 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002706
2707 // 4. Copy back out an "out" arguments.
2708 lValueCount = 0;
2709 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2710 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2711 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2712 spv::Id copy = builder.createLoad(spvArgs[a]);
2713 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002714 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002715 }
2716 ++lValueCount;
2717 }
2718 }
2719
2720 return result;
2721}
2722
2723// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002724spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2725 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002726 spv::Id typeId, spv::Id left, spv::Id right,
2727 glslang::TBasicType typeProxy, bool reduceComparison)
2728{
Rex Xu8ff43de2016-04-22 16:51:45 +08002729 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002730 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002731 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002732
2733 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002734 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002735 bool comparison = false;
2736
2737 switch (op) {
2738 case glslang::EOpAdd:
2739 case glslang::EOpAddAssign:
2740 if (isFloat)
2741 binOp = spv::OpFAdd;
2742 else
2743 binOp = spv::OpIAdd;
2744 break;
2745 case glslang::EOpSub:
2746 case glslang::EOpSubAssign:
2747 if (isFloat)
2748 binOp = spv::OpFSub;
2749 else
2750 binOp = spv::OpISub;
2751 break;
2752 case glslang::EOpMul:
2753 case glslang::EOpMulAssign:
2754 if (isFloat)
2755 binOp = spv::OpFMul;
2756 else
2757 binOp = spv::OpIMul;
2758 break;
2759 case glslang::EOpVectorTimesScalar:
2760 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002761 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002762 if (builder.isVector(right))
2763 std::swap(left, right);
2764 assert(builder.isScalar(right));
2765 needMatchingVectors = false;
2766 binOp = spv::OpVectorTimesScalar;
2767 } else
2768 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002769 break;
2770 case glslang::EOpVectorTimesMatrix:
2771 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002772 binOp = spv::OpVectorTimesMatrix;
2773 break;
2774 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002775 binOp = spv::OpMatrixTimesVector;
2776 break;
2777 case glslang::EOpMatrixTimesScalar:
2778 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002779 binOp = spv::OpMatrixTimesScalar;
2780 break;
2781 case glslang::EOpMatrixTimesMatrix:
2782 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002783 binOp = spv::OpMatrixTimesMatrix;
2784 break;
2785 case glslang::EOpOuterProduct:
2786 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002787 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002788 break;
2789
2790 case glslang::EOpDiv:
2791 case glslang::EOpDivAssign:
2792 if (isFloat)
2793 binOp = spv::OpFDiv;
2794 else if (isUnsigned)
2795 binOp = spv::OpUDiv;
2796 else
2797 binOp = spv::OpSDiv;
2798 break;
2799 case glslang::EOpMod:
2800 case glslang::EOpModAssign:
2801 if (isFloat)
2802 binOp = spv::OpFMod;
2803 else if (isUnsigned)
2804 binOp = spv::OpUMod;
2805 else
2806 binOp = spv::OpSMod;
2807 break;
2808 case glslang::EOpRightShift:
2809 case glslang::EOpRightShiftAssign:
2810 if (isUnsigned)
2811 binOp = spv::OpShiftRightLogical;
2812 else
2813 binOp = spv::OpShiftRightArithmetic;
2814 break;
2815 case glslang::EOpLeftShift:
2816 case glslang::EOpLeftShiftAssign:
2817 binOp = spv::OpShiftLeftLogical;
2818 break;
2819 case glslang::EOpAnd:
2820 case glslang::EOpAndAssign:
2821 binOp = spv::OpBitwiseAnd;
2822 break;
2823 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002824 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002825 binOp = spv::OpLogicalAnd;
2826 break;
2827 case glslang::EOpInclusiveOr:
2828 case glslang::EOpInclusiveOrAssign:
2829 binOp = spv::OpBitwiseOr;
2830 break;
2831 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002832 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002833 binOp = spv::OpLogicalOr;
2834 break;
2835 case glslang::EOpExclusiveOr:
2836 case glslang::EOpExclusiveOrAssign:
2837 binOp = spv::OpBitwiseXor;
2838 break;
2839 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002840 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002841 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002842 break;
2843
2844 case glslang::EOpLessThan:
2845 case glslang::EOpGreaterThan:
2846 case glslang::EOpLessThanEqual:
2847 case glslang::EOpGreaterThanEqual:
2848 case glslang::EOpEqual:
2849 case glslang::EOpNotEqual:
2850 case glslang::EOpVectorEqual:
2851 case glslang::EOpVectorNotEqual:
2852 comparison = true;
2853 break;
2854 default:
2855 break;
2856 }
2857
John Kessenich7c1aa102015-10-15 13:29:11 -06002858 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002859 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002860 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002861 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002862 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002863
2864 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002865 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002866 builder.promoteScalar(precision, left, right);
2867
qining25262b32016-05-06 17:25:16 -04002868 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2869 addDecoration(result, noContraction);
2870 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002871 }
2872
2873 if (! comparison)
2874 return 0;
2875
John Kessenich7c1aa102015-10-15 13:29:11 -06002876 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002877
2878 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2879 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2880
John Kessenich22118352015-12-21 20:54:09 -07002881 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002882 }
2883
2884 switch (op) {
2885 case glslang::EOpLessThan:
2886 if (isFloat)
2887 binOp = spv::OpFOrdLessThan;
2888 else if (isUnsigned)
2889 binOp = spv::OpULessThan;
2890 else
2891 binOp = spv::OpSLessThan;
2892 break;
2893 case glslang::EOpGreaterThan:
2894 if (isFloat)
2895 binOp = spv::OpFOrdGreaterThan;
2896 else if (isUnsigned)
2897 binOp = spv::OpUGreaterThan;
2898 else
2899 binOp = spv::OpSGreaterThan;
2900 break;
2901 case glslang::EOpLessThanEqual:
2902 if (isFloat)
2903 binOp = spv::OpFOrdLessThanEqual;
2904 else if (isUnsigned)
2905 binOp = spv::OpULessThanEqual;
2906 else
2907 binOp = spv::OpSLessThanEqual;
2908 break;
2909 case glslang::EOpGreaterThanEqual:
2910 if (isFloat)
2911 binOp = spv::OpFOrdGreaterThanEqual;
2912 else if (isUnsigned)
2913 binOp = spv::OpUGreaterThanEqual;
2914 else
2915 binOp = spv::OpSGreaterThanEqual;
2916 break;
2917 case glslang::EOpEqual:
2918 case glslang::EOpVectorEqual:
2919 if (isFloat)
2920 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002921 else if (isBool)
2922 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002923 else
2924 binOp = spv::OpIEqual;
2925 break;
2926 case glslang::EOpNotEqual:
2927 case glslang::EOpVectorNotEqual:
2928 if (isFloat)
2929 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002930 else if (isBool)
2931 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002932 else
2933 binOp = spv::OpINotEqual;
2934 break;
2935 default:
2936 break;
2937 }
2938
qining25262b32016-05-06 17:25:16 -04002939 if (binOp != spv::OpNop) {
2940 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2941 addDecoration(result, noContraction);
2942 return builder.setPrecision(result, precision);
2943 }
John Kessenich140f3df2015-06-26 16:58:36 -06002944
2945 return 0;
2946}
2947
John Kessenich04bb8a02015-12-12 12:28:14 -07002948//
2949// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2950// These can be any of:
2951//
2952// matrix * scalar
2953// scalar * matrix
2954// matrix * matrix linear algebraic
2955// matrix * vector
2956// vector * matrix
2957// matrix * matrix componentwise
2958// matrix op matrix op in {+, -, /}
2959// matrix op scalar op in {+, -, /}
2960// scalar op matrix op in {+, -, /}
2961//
qining25262b32016-05-06 17:25:16 -04002962spv::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 -07002963{
2964 bool firstClass = true;
2965
2966 // First, handle first-class matrix operations (* and matrix/scalar)
2967 switch (op) {
2968 case spv::OpFDiv:
2969 if (builder.isMatrix(left) && builder.isScalar(right)) {
2970 // turn matrix / scalar into a multiply...
2971 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2972 op = spv::OpMatrixTimesScalar;
2973 } else
2974 firstClass = false;
2975 break;
2976 case spv::OpMatrixTimesScalar:
2977 if (builder.isMatrix(right))
2978 std::swap(left, right);
2979 assert(builder.isScalar(right));
2980 break;
2981 case spv::OpVectorTimesMatrix:
2982 assert(builder.isVector(left));
2983 assert(builder.isMatrix(right));
2984 break;
2985 case spv::OpMatrixTimesVector:
2986 assert(builder.isMatrix(left));
2987 assert(builder.isVector(right));
2988 break;
2989 case spv::OpMatrixTimesMatrix:
2990 assert(builder.isMatrix(left));
2991 assert(builder.isMatrix(right));
2992 break;
2993 default:
2994 firstClass = false;
2995 break;
2996 }
2997
qining25262b32016-05-06 17:25:16 -04002998 if (firstClass) {
2999 spv::Id result = builder.createBinOp(op, typeId, left, right);
3000 addDecoration(result, noContraction);
3001 return builder.setPrecision(result, precision);
3002 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003003
3004 // Handle component-wise +, -, *, and / for all combinations of type.
3005 // The result type of all of them is the same type as the (a) matrix operand.
3006 // The algorithm is to:
3007 // - break the matrix(es) into vectors
3008 // - smear any scalar to a vector
3009 // - do vector operations
3010 // - make a matrix out the vector results
3011 switch (op) {
3012 case spv::OpFAdd:
3013 case spv::OpFSub:
3014 case spv::OpFDiv:
3015 case spv::OpFMul:
3016 {
3017 // one time set up...
3018 bool leftMat = builder.isMatrix(left);
3019 bool rightMat = builder.isMatrix(right);
3020 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3021 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3022 spv::Id scalarType = builder.getScalarTypeId(typeId);
3023 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3024 std::vector<spv::Id> results;
3025 spv::Id smearVec = spv::NoResult;
3026 if (builder.isScalar(left))
3027 smearVec = builder.smearScalar(precision, left, vecType);
3028 else if (builder.isScalar(right))
3029 smearVec = builder.smearScalar(precision, right, vecType);
3030
3031 // do each vector op
3032 for (unsigned int c = 0; c < numCols; ++c) {
3033 std::vector<unsigned int> indexes;
3034 indexes.push_back(c);
3035 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3036 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003037 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3038 addDecoration(result, noContraction);
3039 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003040 }
3041
3042 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003043 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003044 }
3045 default:
3046 assert(0);
3047 return spv::NoResult;
3048 }
3049}
3050
qining25262b32016-05-06 17:25:16 -04003051spv::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 -06003052{
3053 spv::Op unaryOp = spv::OpNop;
3054 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003055 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003056 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003057
3058 switch (op) {
3059 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003060 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003061 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003062 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003063 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003064 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003065 unaryOp = spv::OpSNegate;
3066 break;
3067
3068 case glslang::EOpLogicalNot:
3069 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003070 unaryOp = spv::OpLogicalNot;
3071 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003072 case glslang::EOpBitwiseNot:
3073 unaryOp = spv::OpNot;
3074 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003075
John Kessenich140f3df2015-06-26 16:58:36 -06003076 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003077 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003078 break;
3079 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003080 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003081 break;
3082 case glslang::EOpTranspose:
3083 unaryOp = spv::OpTranspose;
3084 break;
3085
3086 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003087 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
3089 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003090 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003091 break;
3092 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003093 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003094 break;
3095 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003096 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003097 break;
3098 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003099 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003100 break;
3101 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003102 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003103 break;
3104 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003105 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003106 break;
3107 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003108 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003109 break;
3110
3111 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003112 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003113 break;
3114 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003115 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003116 break;
3117 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003118 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003119 break;
3120 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003121 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003122 break;
3123 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003124 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003125 break;
3126 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003127 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003128 break;
3129
3130 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003131 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003132 break;
3133 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003134 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003135 break;
3136
3137 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003138 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003139 break;
3140 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003141 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003142 break;
3143 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003144 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003145 break;
3146 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003147 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003148 break;
3149 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003150 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003151 break;
3152 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 break;
3155
3156 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003157 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003158 break;
3159 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003160 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003161 break;
3162 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003163 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003164 break;
3165 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003166 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003167 break;
3168 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003169 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003170 break;
3171 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003172 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003173 break;
3174
3175 case glslang::EOpIsNan:
3176 unaryOp = spv::OpIsNan;
3177 break;
3178 case glslang::EOpIsInf:
3179 unaryOp = spv::OpIsInf;
3180 break;
3181
Rex Xucbc426e2015-12-15 16:03:10 +08003182 case glslang::EOpFloatBitsToInt:
3183 case glslang::EOpFloatBitsToUint:
3184 case glslang::EOpIntBitsToFloat:
3185 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003186 case glslang::EOpDoubleBitsToInt64:
3187 case glslang::EOpDoubleBitsToUint64:
3188 case glslang::EOpInt64BitsToDouble:
3189 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003190 unaryOp = spv::OpBitcast;
3191 break;
3192
John Kessenich140f3df2015-06-26 16:58:36 -06003193 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003194 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003195 break;
3196 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003197 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003198 break;
3199 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003200 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003201 break;
3202 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003203 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003204 break;
3205 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003206 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003207 break;
3208 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003209 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003210 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003211 case glslang::EOpPackSnorm4x8:
3212 libCall = spv::GLSLstd450PackSnorm4x8;
3213 break;
3214 case glslang::EOpUnpackSnorm4x8:
3215 libCall = spv::GLSLstd450UnpackSnorm4x8;
3216 break;
3217 case glslang::EOpPackUnorm4x8:
3218 libCall = spv::GLSLstd450PackUnorm4x8;
3219 break;
3220 case glslang::EOpUnpackUnorm4x8:
3221 libCall = spv::GLSLstd450UnpackUnorm4x8;
3222 break;
3223 case glslang::EOpPackDouble2x32:
3224 libCall = spv::GLSLstd450PackDouble2x32;
3225 break;
3226 case glslang::EOpUnpackDouble2x32:
3227 libCall = spv::GLSLstd450UnpackDouble2x32;
3228 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003229
Rex Xu8ff43de2016-04-22 16:51:45 +08003230 case glslang::EOpPackInt2x32:
3231 case glslang::EOpUnpackInt2x32:
3232 case glslang::EOpPackUint2x32:
3233 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003234 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003235 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3236 break;
3237
John Kessenich140f3df2015-06-26 16:58:36 -06003238 case glslang::EOpDPdx:
3239 unaryOp = spv::OpDPdx;
3240 break;
3241 case glslang::EOpDPdy:
3242 unaryOp = spv::OpDPdy;
3243 break;
3244 case glslang::EOpFwidth:
3245 unaryOp = spv::OpFwidth;
3246 break;
3247 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003248 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 unaryOp = spv::OpDPdxFine;
3250 break;
3251 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003252 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003253 unaryOp = spv::OpDPdyFine;
3254 break;
3255 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003256 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003257 unaryOp = spv::OpFwidthFine;
3258 break;
3259 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003260 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003261 unaryOp = spv::OpDPdxCoarse;
3262 break;
3263 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003264 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003265 unaryOp = spv::OpDPdyCoarse;
3266 break;
3267 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003268 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003269 unaryOp = spv::OpFwidthCoarse;
3270 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003271 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003272 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003273 libCall = spv::GLSLstd450InterpolateAtCentroid;
3274 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003275 case glslang::EOpAny:
3276 unaryOp = spv::OpAny;
3277 break;
3278 case glslang::EOpAll:
3279 unaryOp = spv::OpAll;
3280 break;
3281
3282 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003283 if (isFloat)
3284 libCall = spv::GLSLstd450FAbs;
3285 else
3286 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003287 break;
3288 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003289 if (isFloat)
3290 libCall = spv::GLSLstd450FSign;
3291 else
3292 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003293 break;
3294
John Kessenichfc51d282015-08-19 13:34:18 -06003295 case glslang::EOpAtomicCounterIncrement:
3296 case glslang::EOpAtomicCounterDecrement:
3297 case glslang::EOpAtomicCounter:
3298 {
3299 // Handle all of the atomics in one place, in createAtomicOperation()
3300 std::vector<spv::Id> operands;
3301 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003302 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003303 }
3304
John Kessenichfc51d282015-08-19 13:34:18 -06003305 case glslang::EOpBitFieldReverse:
3306 unaryOp = spv::OpBitReverse;
3307 break;
3308 case glslang::EOpBitCount:
3309 unaryOp = spv::OpBitCount;
3310 break;
3311 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003312 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003313 break;
3314 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003315 if (isUnsigned)
3316 libCall = spv::GLSLstd450FindUMsb;
3317 else
3318 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003319 break;
3320
Rex Xu574ab042016-04-14 16:53:07 +08003321 case glslang::EOpBallot:
3322 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003323 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003324 libCall = spv::GLSLstd450Bad;
3325 break;
3326
Rex Xu338b1852016-05-05 20:38:33 +08003327 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003328 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003329 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003330 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003331
John Kessenich140f3df2015-06-26 16:58:36 -06003332 default:
3333 return 0;
3334 }
3335
3336 spv::Id id;
3337 if (libCall >= 0) {
3338 std::vector<spv::Id> args;
3339 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003340 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003341 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003342 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003343 }
John Kessenich140f3df2015-06-26 16:58:36 -06003344
qining25262b32016-05-06 17:25:16 -04003345 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003346 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003347}
3348
John Kessenich7a53f762016-01-20 11:19:27 -07003349// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003350spv::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 -07003351{
3352 // Handle unary operations vector by vector.
3353 // The result type is the same type as the original type.
3354 // The algorithm is to:
3355 // - break the matrix into vectors
3356 // - apply the operation to each vector
3357 // - make a matrix out the vector results
3358
3359 // get the types sorted out
3360 int numCols = builder.getNumColumns(operand);
3361 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003362 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3363 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003364 std::vector<spv::Id> results;
3365
3366 // do each vector op
3367 for (int c = 0; c < numCols; ++c) {
3368 std::vector<unsigned int> indexes;
3369 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003370 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3371 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3372 addDecoration(destVec, noContraction);
3373 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003374 }
3375
3376 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003377 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003378}
3379
Rex Xu73e3ce72016-04-27 18:48:17 +08003380spv::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 -06003381{
3382 spv::Op convOp = spv::OpNop;
3383 spv::Id zero = 0;
3384 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003385 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003386
3387 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3388
3389 switch (op) {
3390 case glslang::EOpConvIntToBool:
3391 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003392 case glslang::EOpConvInt64ToBool:
3393 case glslang::EOpConvUint64ToBool:
3394 zero = (op == glslang::EOpConvInt64ToBool ||
3395 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003396 zero = makeSmearedConstant(zero, vectorSize);
3397 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3398
3399 case glslang::EOpConvFloatToBool:
3400 zero = builder.makeFloatConstant(0.0F);
3401 zero = makeSmearedConstant(zero, vectorSize);
3402 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3403
3404 case glslang::EOpConvDoubleToBool:
3405 zero = builder.makeDoubleConstant(0.0);
3406 zero = makeSmearedConstant(zero, vectorSize);
3407 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3408
3409 case glslang::EOpConvBoolToFloat:
3410 convOp = spv::OpSelect;
3411 zero = builder.makeFloatConstant(0.0);
3412 one = builder.makeFloatConstant(1.0);
3413 break;
3414 case glslang::EOpConvBoolToDouble:
3415 convOp = spv::OpSelect;
3416 zero = builder.makeDoubleConstant(0.0);
3417 one = builder.makeDoubleConstant(1.0);
3418 break;
3419 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003420 case glslang::EOpConvBoolToInt64:
3421 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3422 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003423 convOp = spv::OpSelect;
3424 break;
3425 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003426 case glslang::EOpConvBoolToUint64:
3427 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3428 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003429 convOp = spv::OpSelect;
3430 break;
3431
3432 case glslang::EOpConvIntToFloat:
3433 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003434 case glslang::EOpConvInt64ToFloat:
3435 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003436 convOp = spv::OpConvertSToF;
3437 break;
3438
3439 case glslang::EOpConvUintToFloat:
3440 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003441 case glslang::EOpConvUint64ToFloat:
3442 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003443 convOp = spv::OpConvertUToF;
3444 break;
3445
3446 case glslang::EOpConvDoubleToFloat:
3447 case glslang::EOpConvFloatToDouble:
3448 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003449 if (builder.isMatrixType(destType))
3450 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452
3453 case glslang::EOpConvFloatToInt:
3454 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003455 case glslang::EOpConvFloatToInt64:
3456 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003457 convOp = spv::OpConvertFToS;
3458 break;
3459
3460 case glslang::EOpConvUintToInt:
3461 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003462 case glslang::EOpConvUint64ToInt64:
3463 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003464 if (builder.isInSpecConstCodeGenMode()) {
3465 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003466 zero = (op == glslang::EOpConvUintToInt64 ||
3467 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003468 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003469 // Use OpIAdd, instead of OpBitcast to do the conversion when
3470 // generating for OpSpecConstantOp instruction.
3471 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3472 }
3473 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003474 convOp = spv::OpBitcast;
3475 break;
3476
3477 case glslang::EOpConvFloatToUint:
3478 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003479 case glslang::EOpConvFloatToUint64:
3480 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003481 convOp = spv::OpConvertFToU;
3482 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003483
3484 case glslang::EOpConvIntToInt64:
3485 case glslang::EOpConvInt64ToInt:
3486 convOp = spv::OpSConvert;
3487 break;
3488
3489 case glslang::EOpConvUintToUint64:
3490 case glslang::EOpConvUint64ToUint:
3491 convOp = spv::OpUConvert;
3492 break;
3493
3494 case glslang::EOpConvIntToUint64:
3495 case glslang::EOpConvInt64ToUint:
3496 case glslang::EOpConvUint64ToInt:
3497 case glslang::EOpConvUintToInt64:
3498 // OpSConvert/OpUConvert + OpBitCast
3499 switch (op) {
3500 case glslang::EOpConvIntToUint64:
3501 convOp = spv::OpSConvert;
3502 type = builder.makeIntType(64);
3503 break;
3504 case glslang::EOpConvInt64ToUint:
3505 convOp = spv::OpSConvert;
3506 type = builder.makeIntType(32);
3507 break;
3508 case glslang::EOpConvUint64ToInt:
3509 convOp = spv::OpUConvert;
3510 type = builder.makeUintType(32);
3511 break;
3512 case glslang::EOpConvUintToInt64:
3513 convOp = spv::OpUConvert;
3514 type = builder.makeUintType(64);
3515 break;
3516 default:
3517 assert(0);
3518 break;
3519 }
3520
3521 if (vectorSize > 0)
3522 type = builder.makeVectorType(type, vectorSize);
3523
3524 operand = builder.createUnaryOp(convOp, type, operand);
3525
3526 if (builder.isInSpecConstCodeGenMode()) {
3527 // Build zero scalar or vector for OpIAdd.
3528 zero = (op == glslang::EOpConvIntToUint64 ||
3529 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3530 zero = makeSmearedConstant(zero, vectorSize);
3531 // Use OpIAdd, instead of OpBitcast to do the conversion when
3532 // generating for OpSpecConstantOp instruction.
3533 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3534 }
3535 // For normal run-time conversion instruction, use OpBitcast.
3536 convOp = spv::OpBitcast;
3537 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003538 default:
3539 break;
3540 }
3541
3542 spv::Id result = 0;
3543 if (convOp == spv::OpNop)
3544 return result;
3545
3546 if (convOp == spv::OpSelect) {
3547 zero = makeSmearedConstant(zero, vectorSize);
3548 one = makeSmearedConstant(one, vectorSize);
3549 result = builder.createTriOp(convOp, destType, operand, one, zero);
3550 } else
3551 result = builder.createUnaryOp(convOp, destType, operand);
3552
John Kessenich32cfd492016-02-02 12:37:46 -07003553 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003554}
3555
3556spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3557{
3558 if (vectorSize == 0)
3559 return constant;
3560
3561 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3562 std::vector<spv::Id> components;
3563 for (int c = 0; c < vectorSize; ++c)
3564 components.push_back(constant);
3565 return builder.makeCompositeConstant(vectorTypeId, components);
3566}
3567
John Kessenich426394d2015-07-23 10:22:48 -06003568// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003569spv::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 -06003570{
3571 spv::Op opCode = spv::OpNop;
3572
3573 switch (op) {
3574 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003575 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003576 opCode = spv::OpAtomicIAdd;
3577 break;
3578 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003579 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003580 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003581 break;
3582 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003583 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003584 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003585 break;
3586 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003587 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003588 opCode = spv::OpAtomicAnd;
3589 break;
3590 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003591 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003592 opCode = spv::OpAtomicOr;
3593 break;
3594 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003595 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003596 opCode = spv::OpAtomicXor;
3597 break;
3598 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003599 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003600 opCode = spv::OpAtomicExchange;
3601 break;
3602 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003603 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003604 opCode = spv::OpAtomicCompareExchange;
3605 break;
3606 case glslang::EOpAtomicCounterIncrement:
3607 opCode = spv::OpAtomicIIncrement;
3608 break;
3609 case glslang::EOpAtomicCounterDecrement:
3610 opCode = spv::OpAtomicIDecrement;
3611 break;
3612 case glslang::EOpAtomicCounter:
3613 opCode = spv::OpAtomicLoad;
3614 break;
3615 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003616 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003617 break;
3618 }
3619
3620 // Sort out the operands
3621 // - mapping from glslang -> SPV
3622 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003623 // - compare-exchange swaps the value and comparator
3624 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003625 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3626 auto opIt = operands.begin(); // walk the glslang operands
3627 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003628 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3629 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3630 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003631 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3632 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003633 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003634 spvAtomicOperands.push_back(*(opIt + 1));
3635 spvAtomicOperands.push_back(*opIt);
3636 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003637 }
John Kessenich426394d2015-07-23 10:22:48 -06003638
John Kessenich3e60a6f2015-09-14 22:45:16 -06003639 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003640 for (; opIt != operands.end(); ++opIt)
3641 spvAtomicOperands.push_back(*opIt);
3642
3643 return builder.createOp(opCode, typeId, spvAtomicOperands);
3644}
3645
John Kessenich91cef522016-05-05 16:45:40 -06003646// Create group invocation operations.
3647spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3648{
3649 builder.addCapability(spv::CapabilityGroups);
3650
3651 std::vector<spv::Id> operands;
3652 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3653 operands.push_back(operand);
3654
3655 switch (op) {
3656 case glslang::EOpAnyInvocation:
3657 case glslang::EOpAllInvocations:
3658 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3659
3660 case glslang::EOpAllInvocationsEqual:
3661 {
3662 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3663 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3664
3665 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3666 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3667 }
3668 default:
3669 logger->missingFunctionality("invocation operation");
3670 return spv::NoResult;
3671 }
3672}
3673
John Kessenich5e4b1242015-08-06 22:53:06 -06003674spv::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 -06003675{
Rex Xu8ff43de2016-04-22 16:51:45 +08003676 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003677 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3678
John Kessenich140f3df2015-06-26 16:58:36 -06003679 spv::Op opCode = spv::OpNop;
3680 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003681 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003682 spv::Id typeId0 = 0;
3683 if (consumedOperands > 0)
3684 typeId0 = builder.getTypeId(operands[0]);
3685 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003686
3687 switch (op) {
3688 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003689 if (isFloat)
3690 libCall = spv::GLSLstd450FMin;
3691 else if (isUnsigned)
3692 libCall = spv::GLSLstd450UMin;
3693 else
3694 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003695 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003696 break;
3697 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003698 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003701 if (isFloat)
3702 libCall = spv::GLSLstd450FMax;
3703 else if (isUnsigned)
3704 libCall = spv::GLSLstd450UMax;
3705 else
3706 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003707 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003708 break;
3709 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003710 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003711 break;
3712 case glslang::EOpDot:
3713 opCode = spv::OpDot;
3714 break;
3715 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003716 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
3718
3719 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003720 if (isFloat)
3721 libCall = spv::GLSLstd450FClamp;
3722 else if (isUnsigned)
3723 libCall = spv::GLSLstd450UClamp;
3724 else
3725 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003726 builder.promoteScalar(precision, operands.front(), operands[1]);
3727 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003728 break;
3729 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003730 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3731 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003732 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003733 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003734 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003735 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003736 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003737 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
3739 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003741 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003742 break;
3743 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003744 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003745 builder.promoteScalar(precision, operands[0], operands[2]);
3746 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
3748
3749 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003750 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003751 break;
3752 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003753 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003754 break;
3755 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003756 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003757 break;
3758 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003759 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003760 break;
3761 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003762 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003763 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003764 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003765 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003766 libCall = spv::GLSLstd450InterpolateAtSample;
3767 break;
3768 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003769 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003770 libCall = spv::GLSLstd450InterpolateAtOffset;
3771 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003772 case glslang::EOpAddCarry:
3773 opCode = spv::OpIAddCarry;
3774 typeId = builder.makeStructResultType(typeId0, typeId0);
3775 consumedOperands = 2;
3776 break;
3777 case glslang::EOpSubBorrow:
3778 opCode = spv::OpISubBorrow;
3779 typeId = builder.makeStructResultType(typeId0, typeId0);
3780 consumedOperands = 2;
3781 break;
3782 case glslang::EOpUMulExtended:
3783 opCode = spv::OpUMulExtended;
3784 typeId = builder.makeStructResultType(typeId0, typeId0);
3785 consumedOperands = 2;
3786 break;
3787 case glslang::EOpIMulExtended:
3788 opCode = spv::OpSMulExtended;
3789 typeId = builder.makeStructResultType(typeId0, typeId0);
3790 consumedOperands = 2;
3791 break;
3792 case glslang::EOpBitfieldExtract:
3793 if (isUnsigned)
3794 opCode = spv::OpBitFieldUExtract;
3795 else
3796 opCode = spv::OpBitFieldSExtract;
3797 break;
3798 case glslang::EOpBitfieldInsert:
3799 opCode = spv::OpBitFieldInsert;
3800 break;
3801
3802 case glslang::EOpFma:
3803 libCall = spv::GLSLstd450Fma;
3804 break;
3805 case glslang::EOpFrexp:
3806 libCall = spv::GLSLstd450FrexpStruct;
3807 if (builder.getNumComponents(operands[0]) == 1)
3808 frexpIntType = builder.makeIntegerType(32, true);
3809 else
3810 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3811 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3812 consumedOperands = 1;
3813 break;
3814 case glslang::EOpLdexp:
3815 libCall = spv::GLSLstd450Ldexp;
3816 break;
3817
Rex Xu574ab042016-04-14 16:53:07 +08003818 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003819 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003820 libCall = spv::GLSLstd450Bad;
3821 break;
3822
John Kessenich140f3df2015-06-26 16:58:36 -06003823 default:
3824 return 0;
3825 }
3826
3827 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003828 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003829 // Use an extended instruction from the standard library.
3830 // Construct the call arguments, without modifying the original operands vector.
3831 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3832 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003833 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003834 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003835 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003836 case 0:
3837 // should all be handled by visitAggregate and createNoArgOperation
3838 assert(0);
3839 return 0;
3840 case 1:
3841 // should all be handled by createUnaryOperation
3842 assert(0);
3843 return 0;
3844 case 2:
3845 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3846 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003847 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003848 // anything 3 or over doesn't have l-value operands, so all should be consumed
3849 assert(consumedOperands == operands.size());
3850 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003851 break;
3852 }
3853 }
3854
John Kessenich55e7d112015-11-15 21:33:39 -07003855 // Decode the return types that were structures
3856 switch (op) {
3857 case glslang::EOpAddCarry:
3858 case glslang::EOpSubBorrow:
3859 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3860 id = builder.createCompositeExtract(id, typeId0, 0);
3861 break;
3862 case glslang::EOpUMulExtended:
3863 case glslang::EOpIMulExtended:
3864 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3865 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3866 break;
3867 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003868 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003869 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3870 id = builder.createCompositeExtract(id, typeId0, 0);
3871 break;
3872 default:
3873 break;
3874 }
3875
John Kessenich32cfd492016-02-02 12:37:46 -07003876 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003877}
3878
3879// Intrinsics with no arguments, no return value, and no precision.
3880spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3881{
3882 // TODO: get the barrier operands correct
3883
3884 switch (op) {
3885 case glslang::EOpEmitVertex:
3886 builder.createNoResultOp(spv::OpEmitVertex);
3887 return 0;
3888 case glslang::EOpEndPrimitive:
3889 builder.createNoResultOp(spv::OpEndPrimitive);
3890 return 0;
3891 case glslang::EOpBarrier:
John Kessenich823fc652016-05-19 18:26:42 -06003892 if (glslangIntermediate->getProfile() != EEsProfile)
3893 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich5e4b1242015-08-06 22:53:06 -06003894 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003895 return 0;
3896 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003897 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003898 return 0;
3899 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003900 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003901 return 0;
3902 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003903 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003904 return 0;
3905 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003906 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003907 return 0;
3908 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003909 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003910 return 0;
3911 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003912 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003913 return 0;
3914 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003915 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003916 return 0;
3917 }
3918}
3919
3920spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3921{
John Kessenich2f273362015-07-18 22:34:27 -06003922 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003923 spv::Id id;
3924 if (symbolValues.end() != iter) {
3925 id = iter->second;
3926 return id;
3927 }
3928
3929 // it was not found, create it
3930 id = createSpvVariable(symbol);
3931 symbolValues[symbol->getId()] = id;
3932
3933 if (! symbol->getType().isStruct()) {
3934 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003935 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08003936 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003937 if (symbol->getType().getQualifier().hasSpecConstantId())
3938 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003939 if (symbol->getQualifier().hasIndex())
3940 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3941 if (symbol->getQualifier().hasComponent())
3942 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3943 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003944 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003945 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003946 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003947 if (symbol->getQualifier().hasXfbBuffer())
3948 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3949 if (symbol->getQualifier().hasXfbOffset())
3950 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3951 }
3952 }
3953
scygan2c864272016-05-18 18:09:17 +02003954 if (symbol->getQualifier().hasLocation())
3955 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07003956 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003957 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003958 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003959 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003960 }
John Kessenich140f3df2015-06-26 16:58:36 -06003961 if (symbol->getQualifier().hasSet())
3962 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003963 else if (IsDescriptorResource(symbol->getType())) {
3964 // default to 0
3965 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3966 }
John Kessenich140f3df2015-06-26 16:58:36 -06003967 if (symbol->getQualifier().hasBinding())
3968 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003969 if (symbol->getQualifier().hasAttachment())
3970 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003971 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003972 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003973 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003974 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003975 if (symbol->getQualifier().hasXfbBuffer())
3976 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3977 }
3978
Rex Xu1da878f2016-02-21 20:59:01 +08003979 if (symbol->getType().isImage()) {
3980 std::vector<spv::Decoration> memory;
3981 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3982 for (unsigned int i = 0; i < memory.size(); ++i)
3983 addDecoration(id, memory[i]);
3984 }
3985
John Kessenich140f3df2015-06-26 16:58:36 -06003986 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06003987 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06003988 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003989 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003990
John Kessenich140f3df2015-06-26 16:58:36 -06003991 return id;
3992}
3993
John Kessenich55e7d112015-11-15 21:33:39 -07003994// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003995void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3996{
3997 if (dec != spv::BadValue)
3998 builder.addDecoration(id, dec);
3999}
4000
John Kessenich55e7d112015-11-15 21:33:39 -07004001// If 'dec' is valid, add a one-operand decoration to an object
4002void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4003{
4004 if (dec != spv::BadValue)
4005 builder.addDecoration(id, dec, value);
4006}
4007
4008// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004009void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4010{
4011 if (dec != spv::BadValue)
4012 builder.addMemberDecoration(id, (unsigned)member, dec);
4013}
4014
John Kessenich92187592016-02-01 13:45:25 -07004015// If 'dec' is valid, add a one-operand decoration to a struct member
4016void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4017{
4018 if (dec != spv::BadValue)
4019 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4020}
4021
John Kessenich55e7d112015-11-15 21:33:39 -07004022// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004023// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004024//
4025// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4026//
4027// Recursively walk the nodes. The nodes form a tree whose leaves are
4028// regular constants, which themselves are trees that createSpvConstant()
4029// recursively walks. So, this function walks the "top" of the tree:
4030// - emit specialization constant-building instructions for specConstant
4031// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004032spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004033{
John Kessenich7cc0e282016-03-20 00:46:02 -06004034 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004035
qining4f4bb812016-04-03 23:55:17 -04004036 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004037 if (! node.getQualifier().specConstant) {
4038 // hand off to the non-spec-constant path
4039 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4040 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004041 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004042 nextConst, false);
4043 }
4044
4045 // We now know we have a specialization constant to build
4046
qining4f4bb812016-04-03 23:55:17 -04004047 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
4048 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4049 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4050 std::vector<spv::Id> dimConstId;
4051 for (int dim = 0; dim < 3; ++dim) {
4052 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4053 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4054 if (specConst)
4055 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4056 }
4057 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4058 }
4059
4060 // An AST node labelled as specialization constant should be a symbol node.
4061 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4062 if (auto* sn = node.getAsSymbolNode()) {
4063 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004064 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4065 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4066 // will set the builder into spec constant op instruction generating mode.
4067 sub_tree->traverse(this);
4068 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004069 } else if (auto* const_union_array = &sn->getConstArray()){
4070 int nextConst = 0;
4071 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004072 }
4073 }
qining4f4bb812016-04-03 23:55:17 -04004074
4075 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4076 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004077 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004078 exit(1);
4079 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004080}
4081
John Kessenich140f3df2015-06-26 16:58:36 -06004082// Use 'consts' as the flattened glslang source of scalar constants to recursively
4083// build the aggregate SPIR-V constant.
4084//
4085// If there are not enough elements present in 'consts', 0 will be substituted;
4086// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4087//
qining08408382016-03-21 09:51:37 -04004088spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004089{
4090 // vector of constants for SPIR-V
4091 std::vector<spv::Id> spvConsts;
4092
4093 // Type is used for struct and array constants
4094 spv::Id typeId = convertGlslangToSpvType(glslangType);
4095
4096 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004097 glslang::TType elementType(glslangType, 0);
4098 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004099 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004100 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004101 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004102 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004103 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004104 } else if (glslangType.getStruct()) {
4105 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4106 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004107 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004108 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004109 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4110 bool zero = nextConst >= consts.size();
4111 switch (glslangType.getBasicType()) {
4112 case glslang::EbtInt:
4113 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4114 break;
4115 case glslang::EbtUint:
4116 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4117 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004118 case glslang::EbtInt64:
4119 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4120 break;
4121 case glslang::EbtUint64:
4122 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4123 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 case glslang::EbtFloat:
4125 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4126 break;
4127 case glslang::EbtDouble:
4128 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4129 break;
4130 case glslang::EbtBool:
4131 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4132 break;
4133 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004134 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004135 break;
4136 }
4137 ++nextConst;
4138 }
4139 } else {
4140 // we have a non-aggregate (scalar) constant
4141 bool zero = nextConst >= consts.size();
4142 spv::Id scalar = 0;
4143 switch (glslangType.getBasicType()) {
4144 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004145 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004146 break;
4147 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004148 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004150 case glslang::EbtInt64:
4151 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4152 break;
4153 case glslang::EbtUint64:
4154 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4155 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004156 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004157 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004158 break;
4159 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004160 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004161 break;
4162 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004163 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004164 break;
4165 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004166 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004167 break;
4168 }
4169 ++nextConst;
4170 return scalar;
4171 }
4172
4173 return builder.makeCompositeConstant(typeId, spvConsts);
4174}
4175
John Kessenich7c1aa102015-10-15 13:29:11 -06004176// Return true if the node is a constant or symbol whose reading has no
4177// non-trivial observable cost or effect.
4178bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4179{
4180 // don't know what this is
4181 if (node == nullptr)
4182 return false;
4183
4184 // a constant is safe
4185 if (node->getAsConstantUnion() != nullptr)
4186 return true;
4187
4188 // not a symbol means non-trivial
4189 if (node->getAsSymbolNode() == nullptr)
4190 return false;
4191
4192 // a symbol, depends on what's being read
4193 switch (node->getType().getQualifier().storage) {
4194 case glslang::EvqTemporary:
4195 case glslang::EvqGlobal:
4196 case glslang::EvqIn:
4197 case glslang::EvqInOut:
4198 case glslang::EvqConst:
4199 case glslang::EvqConstReadOnly:
4200 case glslang::EvqUniform:
4201 return true;
4202 default:
4203 return false;
4204 }
qining25262b32016-05-06 17:25:16 -04004205}
John Kessenich7c1aa102015-10-15 13:29:11 -06004206
4207// A node is trivial if it is a single operation with no side effects.
4208// Error on the side of saying non-trivial.
4209// Return true if trivial.
4210bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4211{
4212 if (node == nullptr)
4213 return false;
4214
4215 // symbols and constants are trivial
4216 if (isTrivialLeaf(node))
4217 return true;
4218
4219 // otherwise, it needs to be a simple operation or one or two leaf nodes
4220
4221 // not a simple operation
4222 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4223 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4224 if (binaryNode == nullptr && unaryNode == nullptr)
4225 return false;
4226
4227 // not on leaf nodes
4228 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4229 return false;
4230
4231 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4232 return false;
4233 }
4234
4235 switch (node->getAsOperator()->getOp()) {
4236 case glslang::EOpLogicalNot:
4237 case glslang::EOpConvIntToBool:
4238 case glslang::EOpConvUintToBool:
4239 case glslang::EOpConvFloatToBool:
4240 case glslang::EOpConvDoubleToBool:
4241 case glslang::EOpEqual:
4242 case glslang::EOpNotEqual:
4243 case glslang::EOpLessThan:
4244 case glslang::EOpGreaterThan:
4245 case glslang::EOpLessThanEqual:
4246 case glslang::EOpGreaterThanEqual:
4247 case glslang::EOpIndexDirect:
4248 case glslang::EOpIndexDirectStruct:
4249 case glslang::EOpLogicalXor:
4250 case glslang::EOpAny:
4251 case glslang::EOpAll:
4252 return true;
4253 default:
4254 return false;
4255 }
4256}
4257
4258// Emit short-circuiting code, where 'right' is never evaluated unless
4259// the left side is true (for &&) or false (for ||).
4260spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4261{
4262 spv::Id boolTypeId = builder.makeBoolType();
4263
4264 // emit left operand
4265 builder.clearAccessChain();
4266 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004267 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004268
4269 // Operands to accumulate OpPhi operands
4270 std::vector<spv::Id> phiOperands;
4271 // accumulate left operand's phi information
4272 phiOperands.push_back(leftId);
4273 phiOperands.push_back(builder.getBuildPoint()->getId());
4274
4275 // Make the two kinds of operation symmetric with a "!"
4276 // || => emit "if (! left) result = right"
4277 // && => emit "if ( left) result = right"
4278 //
4279 // TODO: this runtime "not" for || could be avoided by adding functionality
4280 // to 'builder' to have an "else" without an "then"
4281 if (op == glslang::EOpLogicalOr)
4282 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4283
4284 // make an "if" based on the left value
4285 spv::Builder::If ifBuilder(leftId, builder);
4286
4287 // emit right operand as the "then" part of the "if"
4288 builder.clearAccessChain();
4289 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004290 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004291
4292 // accumulate left operand's phi information
4293 phiOperands.push_back(rightId);
4294 phiOperands.push_back(builder.getBuildPoint()->getId());
4295
4296 // finish the "if"
4297 ifBuilder.makeEndIf();
4298
4299 // phi together the two results
4300 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4301}
4302
John Kessenich140f3df2015-06-26 16:58:36 -06004303}; // end anonymous namespace
4304
4305namespace glslang {
4306
John Kessenich68d78fd2015-07-12 19:28:10 -06004307void GetSpirvVersion(std::string& version)
4308{
John Kessenich9e55f632015-07-15 10:03:39 -06004309 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004310 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004311 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004312 version = buf;
4313}
4314
John Kessenich140f3df2015-06-26 16:58:36 -06004315// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004316void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004317{
4318 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004319 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004320 for (int i = 0; i < (int)spirv.size(); ++i) {
4321 unsigned int word = spirv[i];
4322 out.write((const char*)&word, 4);
4323 }
4324 out.close();
4325}
4326
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004327// Write SPIR-V out to a text file with 32-bit hexadecimal words
4328void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4329{
4330 std::ofstream out;
4331 out.open(baseName, std::ios::binary | std::ios::out);
4332 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4333 const int WORDS_PER_LINE = 8;
4334 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4335 out << "\t";
4336 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4337 const unsigned int word = spirv[i + j];
4338 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4339 if (i + j + 1 < (int)spirv.size()) {
4340 out << ",";
4341 }
4342 }
4343 out << std::endl;
4344 }
4345 out.close();
4346}
4347
John Kessenich140f3df2015-06-26 16:58:36 -06004348//
4349// Set up the glslang traversal
4350//
4351void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4352{
Lei Zhang17535f72016-05-04 15:55:59 -04004353 spv::SpvBuildLogger logger;
4354 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004355}
4356
Lei Zhang17535f72016-05-04 15:55:59 -04004357void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004358{
John Kessenich140f3df2015-06-26 16:58:36 -06004359 TIntermNode* root = intermediate.getTreeRoot();
4360
4361 if (root == 0)
4362 return;
4363
4364 glslang::GetThreadPoolAllocator().push();
4365
Lei Zhang17535f72016-05-04 15:55:59 -04004366 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004367
4368 root->traverse(&it);
4369
4370 it.dumpSpv(spirv);
4371
4372 glslang::GetThreadPoolAllocator().pop();
4373}
4374
4375}; // end namespace glslang