blob: e08bff6566cece7be726d2e8d1eba66a5104d5e0 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
45 #include "GLSL.std.450.h"
46}
John Kessenich140f3df2015-06-26 16:58:36 -060047
48// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020049#include "../glslang/MachineIndependent/localintermediate.h"
50#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060051#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060052
John Kessenich140f3df2015-06-26 16:58:36 -060053#include <fstream>
Lei Zhang17535f72016-05-04 15:55:59 -040054#include <list>
55#include <map>
56#include <stack>
57#include <string>
58#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060059
60namespace {
61
John Kessenich55e7d112015-11-15 21:33:39 -070062// For low-order part of the generator's magic number. Bump up
63// when there is a change in the style (e.g., if SSA form changes,
64// or a different instruction sequence to do something gets used).
65const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060066
qining4c912612016-04-01 10:35:16 -040067namespace {
68class SpecConstantOpModeGuard {
69public:
70 SpecConstantOpModeGuard(spv::Builder* builder)
71 : builder_(builder) {
72 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040073 }
74 ~SpecConstantOpModeGuard() {
75 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
76 : builder_->setToNormalCodeGenMode();
77 }
qining40887662016-04-03 22:20:42 -040078 void turnOnSpecConstantOpMode() {
79 builder_->setToSpecConstCodeGenMode();
80 }
qining4c912612016-04-01 10:35:16 -040081
82private:
83 spv::Builder* builder_;
84 bool previous_flag_;
85};
86}
87
John Kessenich140f3df2015-06-26 16:58:36 -060088//
89// The main holder of information for translating glslang to SPIR-V.
90//
91// Derives from the AST walking base class.
92//
93class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
94public:
Lei Zhang17535f72016-05-04 15:55:59 -040095 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060096 virtual ~TGlslangToSpvTraverser();
97
98 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
99 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
100 void visitConstantUnion(glslang::TIntermConstantUnion*);
101 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
102 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
103 void visitSymbol(glslang::TIntermSymbol* symbol);
104 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
105 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
106 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
107
John Kessenich7ba63412015-12-20 17:37:07 -0700108 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110protected:
Rex Xubbceed72016-05-21 09:40:44 +0800111 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700113 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
115 spv::Id getSampledType(const glslang::TSampler&);
116 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700117 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700118 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700119 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800120 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700121 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700122 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
123 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
124 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100125 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
128 void makeFunctions(const glslang::TIntermSequence&);
129 void makeGlobalInitializers(const glslang::TIntermSequence&);
130 void visitFunctions(const glslang::TIntermSequence&);
131 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800132 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600133 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
134 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600135 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
136
qining25262b32016-05-06 17:25:16 -0400137 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
138 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
139 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
140 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800141 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800143 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich91cef522016-05-05 16:45:40 -0600144 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600154 bool isTrivialLeaf(const glslang::TIntermTyped* node);
155 bool isTrivial(const glslang::TIntermTyped* node);
156 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
158 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700159 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600160 int sequenceDepth;
161
Lei Zhang17535f72016-05-04 15:55:59 -0400162 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400163
John Kessenich140f3df2015-06-26 16:58:36 -0600164 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
165 spv::Builder builder;
166 bool inMain;
167 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700168 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700169 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600170 const glslang::TIntermediate* glslangIntermediate;
171 spv::Id stdBuiltins;
172
John Kessenich2f273362015-07-18 22:34:27 -0600173 std::unordered_map<int, spv::Id> symbolValues;
174 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
175 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700176 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600177 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600178 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600179};
180
181//
182// Helper functions for translating glslang representations to SPIR-V enumerants.
183//
184
185// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700186spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600187{
John Kessenich66e2faf2016-03-12 18:34:36 -0700188 switch (source) {
189 case glslang::EShSourceGlsl:
190 switch (profile) {
191 case ENoProfile:
192 case ECoreProfile:
193 case ECompatibilityProfile:
194 return spv::SourceLanguageGLSL;
195 case EEsProfile:
196 return spv::SourceLanguageESSL;
197 default:
198 return spv::SourceLanguageUnknown;
199 }
200 case glslang::EShSourceHlsl:
201 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 default:
203 return spv::SourceLanguageUnknown;
204 }
205}
206
207// Translate glslang language (stage) to SPIR-V execution model.
208spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
209{
210 switch (stage) {
211 case EShLangVertex: return spv::ExecutionModelVertex;
212 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
213 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
214 case EShLangGeometry: return spv::ExecutionModelGeometry;
215 case EShLangFragment: return spv::ExecutionModelFragment;
216 case EShLangCompute: return spv::ExecutionModelGLCompute;
217 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600219 return spv::ExecutionModelFragment;
220 }
221}
222
223// Translate glslang type to SPIR-V storage class.
224spv::StorageClass TranslateStorageClass(const glslang::TType& type)
225{
226 if (type.getQualifier().isPipeInput())
227 return spv::StorageClassInput;
228 else if (type.getQualifier().isPipeOutput())
229 return spv::StorageClassOutput;
230 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700231 if (type.getQualifier().layoutPushConstant)
232 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 if (type.getBasicType() == glslang::EbtBlock)
234 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800235 else if (type.getBasicType() == glslang::EbtAtomicUint)
236 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 else
238 return spv::StorageClassUniformConstant;
239 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
240 } else {
241 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700242 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
243 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600244 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
245 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400246 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700247 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600248 return spv::StorageClassFunction;
249 }
250 }
251}
252
253// Translate glslang sampler type to SPIR-V dimensionality.
254spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
255{
256 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700257 case glslang::Esd1D: return spv::Dim1D;
258 case glslang::Esd2D: return spv::Dim2D;
259 case glslang::Esd3D: return spv::Dim3D;
260 case glslang::EsdCube: return spv::DimCube;
261 case glslang::EsdRect: return spv::DimRect;
262 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700263 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700265 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600266 return spv::Dim2D;
267 }
268}
269
270// Translate glslang type to SPIR-V precision decorations.
271spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
272{
273 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700274 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600275 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600276 default:
277 return spv::NoPrecision;
278 }
279}
280
281// Translate glslang type to SPIR-V block decorations.
282spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
283{
284 if (type.getBasicType() == glslang::EbtBlock) {
285 switch (type.getQualifier().storage) {
286 case glslang::EvqUniform: return spv::DecorationBlock;
287 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
288 case glslang::EvqVaryingIn: return spv::DecorationBlock;
289 case glslang::EvqVaryingOut: return spv::DecorationBlock;
290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 break;
293 }
294 }
295
296 return (spv::Decoration)spv::BadValue;
297}
298
Rex Xu1da878f2016-02-21 20:59:01 +0800299// Translate glslang type to SPIR-V memory decorations.
300void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
301{
302 if (qualifier.coherent)
303 memory.push_back(spv::DecorationCoherent);
304 if (qualifier.volatil)
305 memory.push_back(spv::DecorationVolatile);
306 if (qualifier.restrict)
307 memory.push_back(spv::DecorationRestrict);
308 if (qualifier.readonly)
309 memory.push_back(spv::DecorationNonWritable);
310 if (qualifier.writeonly)
311 memory.push_back(spv::DecorationNonReadable);
312}
313
John Kessenich140f3df2015-06-26 16:58:36 -0600314// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700315spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600316{
317 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700318 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600319 case glslang::ElmRowMajor:
320 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 default:
324 // opaque layouts don't need a majorness
325 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 }
327 } else {
328 switch (type.getBasicType()) {
329 default:
330 return (spv::Decoration)spv::BadValue;
331 break;
332 case glslang::EbtBlock:
333 switch (type.getQualifier().storage) {
334 case glslang::EvqUniform:
335 case glslang::EvqBuffer:
336 switch (type.getQualifier().layoutPacking) {
337 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
339 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600340 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 }
342 case glslang::EvqVaryingIn:
343 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700344 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return (spv::Decoration)spv::BadValue;
349 }
350 }
351 }
352}
353
354// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700355// Returns spv::Decoration(spv::BadValue) when no decoration
356// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800357spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600358{
Rex Xubbceed72016-05-21 09:40:44 +0800359 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700360 // Smooth decoration doesn't exist in SPIR-V 1.0
361 return (spv::Decoration)spv::BadValue;
Rex Xubbceed72016-05-21 09:40:44 +0800362 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700363 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700364 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600365 return spv::DecorationFlat;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else
367 return (spv::Decoration)spv::BadValue;
368}
369
370// Translate glslang type to SPIR-V auxiliary storage decorations.
371// Returns spv::Decoration(spv::BadValue) when no decoration
372// should be applied.
373spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
374{
375 if (qualifier.patch)
376 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700377 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600378 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700379 else if (qualifier.sample) {
380 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700382 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600383 return (spv::Decoration)spv::BadValue;
384}
385
John Kessenich92187592016-02-01 13:45:25 -0700386// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600388{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700389 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600390 return spv::DecorationInvariant;
391 else
392 return (spv::Decoration)spv::BadValue;
393}
394
qining9220dbb2016-05-04 17:34:38 -0400395// If glslang type is noContraction, return SPIR-V NoContraction decoration.
396spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
397{
398 if (qualifier.noContraction)
399 return spv::DecorationNoContraction;
400 else
401 return (spv::Decoration)spv::BadValue;
402}
403
David Netoa901ffe2016-06-08 14:11:40 +0100404// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
405// associated capabilities when required. For some built-in variables, a capability
406// is generated only when using the variable in an executable instruction, but not when
407// just declaring a struct member variable with it. This is true for PointSize,
408// ClipDistance, and CullDistance.
409spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600410{
411 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700412 case glslang::EbvPointSize:
David Netoa901ffe2016-06-08 14:11:40 +0100413 // Defer adding the capability until the built-in is actually used.
414 if (!memberDeclaration) {
415 switch (glslangIntermediate->getStage()) {
416 case EShLangGeometry:
417 builder.addCapability(spv::CapabilityGeometryPointSize);
418 break;
419 case EShLangTessControl:
420 case EShLangTessEvaluation:
421 builder.addCapability(spv::CapabilityTessellationPointSize);
422 break;
423 default:
424 break;
425 }
John Kessenich92187592016-02-01 13:45:25 -0700426 }
427 return spv::BuiltInPointSize;
428
John Kessenichebb50532016-05-16 19:22:05 -0600429 // These *Distance capabilities logically belong here, but if the member is declared and
430 // then never used, consumers of SPIR-V prefer the capability not be declared.
431 // They are now generated when used, rather than here when declared.
432 // Potentially, the specification should be more clear what the minimum
433 // use needed is to trigger the capability.
434 //
John Kessenich92187592016-02-01 13:45:25 -0700435 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100436 if (!memberDeclaration)
437 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700438 return spv::BuiltInClipDistance;
439
440 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100441 if (!memberDeclaration)
442 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700443 return spv::BuiltInCullDistance;
444
445 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500446 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700447 return spv::BuiltInViewportIndex;
448
John Kessenich5e801132016-02-15 11:09:46 -0700449 case glslang::EbvSampleId:
450 builder.addCapability(spv::CapabilitySampleRateShading);
451 return spv::BuiltInSampleId;
452
453 case glslang::EbvSamplePosition:
454 builder.addCapability(spv::CapabilitySampleRateShading);
455 return spv::BuiltInSamplePosition;
456
457 case glslang::EbvSampleMask:
458 builder.addCapability(spv::CapabilitySampleRateShading);
459 return spv::BuiltInSampleMask;
460
John Kessenich140f3df2015-06-26 16:58:36 -0600461 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600462 case glslang::EbvVertexId: return spv::BuiltInVertexId;
463 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700464 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
465 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600466 case glslang::EbvBaseVertex:
467 case glslang::EbvBaseInstance:
468 case glslang::EbvDrawId:
469 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600470 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600471 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600472 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
473 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
474 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600475 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
476 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
477 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
478 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
479 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
480 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
481 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600482 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
483 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
484 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
485 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
486 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
487 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
488 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
489 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800490 case glslang::EbvSubGroupSize:
491 case glslang::EbvSubGroupInvocation:
492 case glslang::EbvSubGroupEqMask:
493 case glslang::EbvSubGroupGeMask:
494 case glslang::EbvSubGroupGtMask:
495 case glslang::EbvSubGroupLeMask:
496 case glslang::EbvSubGroupLtMask:
497 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600498 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800499 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600500 default: return (spv::BuiltIn)spv::BadValue;
501 }
502}
503
Rex Xufc618912015-09-09 16:42:49 +0800504// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700505spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800506{
507 assert(type.getBasicType() == glslang::EbtSampler);
508
John Kessenich5d0fa972016-02-15 11:57:00 -0700509 // Check for capabilities
510 switch (type.getQualifier().layoutFormat) {
511 case glslang::ElfRg32f:
512 case glslang::ElfRg16f:
513 case glslang::ElfR11fG11fB10f:
514 case glslang::ElfR16f:
515 case glslang::ElfRgba16:
516 case glslang::ElfRgb10A2:
517 case glslang::ElfRg16:
518 case glslang::ElfRg8:
519 case glslang::ElfR16:
520 case glslang::ElfR8:
521 case glslang::ElfRgba16Snorm:
522 case glslang::ElfRg16Snorm:
523 case glslang::ElfRg8Snorm:
524 case glslang::ElfR16Snorm:
525 case glslang::ElfR8Snorm:
526
527 case glslang::ElfRg32i:
528 case glslang::ElfRg16i:
529 case glslang::ElfRg8i:
530 case glslang::ElfR16i:
531 case glslang::ElfR8i:
532
533 case glslang::ElfRgb10a2ui:
534 case glslang::ElfRg32ui:
535 case glslang::ElfRg16ui:
536 case glslang::ElfRg8ui:
537 case glslang::ElfR16ui:
538 case glslang::ElfR8ui:
539 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
540 break;
541
542 default:
543 break;
544 }
545
546 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800547 switch (type.getQualifier().layoutFormat) {
548 case glslang::ElfNone: return spv::ImageFormatUnknown;
549 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
550 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
551 case glslang::ElfR32f: return spv::ImageFormatR32f;
552 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
553 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
554 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
555 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
556 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
557 case glslang::ElfR16f: return spv::ImageFormatR16f;
558 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
559 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
560 case glslang::ElfRg16: return spv::ImageFormatRg16;
561 case glslang::ElfRg8: return spv::ImageFormatRg8;
562 case glslang::ElfR16: return spv::ImageFormatR16;
563 case glslang::ElfR8: return spv::ImageFormatR8;
564 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
565 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
566 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
567 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
568 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
569 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
570 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
571 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
572 case glslang::ElfR32i: return spv::ImageFormatR32i;
573 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
574 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
575 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
576 case glslang::ElfR16i: return spv::ImageFormatR16i;
577 case glslang::ElfR8i: return spv::ImageFormatR8i;
578 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
579 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
580 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
581 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
582 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
583 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
584 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
585 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
586 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
587 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
588 default: return (spv::ImageFormat)spv::BadValue;
589 }
590}
591
qining25262b32016-05-06 17:25:16 -0400592// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700593// descriptor set.
594bool IsDescriptorResource(const glslang::TType& type)
595{
John Kessenichf7497e22016-03-08 21:36:22 -0700596 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700597 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700598 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700599
600 // non block...
601 // basically samplerXXX/subpass/sampler/texture are all included
602 // if they are the global-scope-class, not the function parameter
603 // (or local, if they ever exist) class.
604 if (type.getBasicType() == glslang::EbtSampler)
605 return type.getQualifier().isUniformOrBuffer();
606
607 // None of the above.
608 return false;
609}
610
John Kesseniche0b6cad2015-12-24 10:30:13 -0700611void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
612{
613 if (child.layoutMatrix == glslang::ElmNone)
614 child.layoutMatrix = parent.layoutMatrix;
615
616 if (parent.invariant)
617 child.invariant = true;
618 if (parent.nopersp)
619 child.nopersp = true;
620 if (parent.flat)
621 child.flat = true;
622 if (parent.centroid)
623 child.centroid = true;
624 if (parent.patch)
625 child.patch = true;
626 if (parent.sample)
627 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800628 if (parent.coherent)
629 child.coherent = true;
630 if (parent.volatil)
631 child.volatil = true;
632 if (parent.restrict)
633 child.restrict = true;
634 if (parent.readonly)
635 child.readonly = true;
636 if (parent.writeonly)
637 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700638}
639
640bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
641{
John Kessenich7b9fa252016-01-21 18:56:57 -0700642 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700643 // - struct members can inherit from a struct declaration
644 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
645 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400646 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700647}
648
John Kessenich140f3df2015-06-26 16:58:36 -0600649//
650// Implement the TGlslangToSpvTraverser class.
651//
652
Lei Zhang17535f72016-05-04 15:55:59 -0400653TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
654 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
655 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600656 inMain(false), mainTerminated(false), linkageOnly(false),
657 glslangIntermediate(glslangIntermediate)
658{
659 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
660
661 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700662 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600663 stdBuiltins = builder.import("GLSL.std.450");
664 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700665 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
666 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600667
668 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600669 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
670 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600671 builder.addSourceExtension(it->c_str());
672
673 // Add the top-level modes for this shader.
674
John Kessenich92187592016-02-01 13:45:25 -0700675 if (glslangIntermediate->getXfbMode()) {
676 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600677 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700678 }
John Kessenich140f3df2015-06-26 16:58:36 -0600679
680 unsigned int mode;
681 switch (glslangIntermediate->getStage()) {
682 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600683 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600684 break;
685
686 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600687 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600688 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
689 break;
690
691 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600692 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600693 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700694 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
695 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
696 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600697 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600698 }
699 if (mode != spv::BadValue)
700 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
701
John Kesseniche6903322015-10-13 16:29:02 -0600702 switch (glslangIntermediate->getVertexSpacing()) {
703 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
704 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
705 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
706 default: mode = spv::BadValue; break;
707 }
708 if (mode != spv::BadValue)
709 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
710
711 switch (glslangIntermediate->getVertexOrder()) {
712 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
713 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
714 default: mode = spv::BadValue; break;
715 }
716 if (mode != spv::BadValue)
717 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
718
719 if (glslangIntermediate->getPointMode())
720 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600721 break;
722
723 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600724 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600725 switch (glslangIntermediate->getInputPrimitive()) {
726 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
727 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
728 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700729 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600730 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
731 default: mode = spv::BadValue; break;
732 }
733 if (mode != spv::BadValue)
734 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600735
John Kessenich140f3df2015-06-26 16:58:36 -0600736 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
737
738 switch (glslangIntermediate->getOutputPrimitive()) {
739 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
740 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
741 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
742 default: mode = spv::BadValue; break;
743 }
744 if (mode != spv::BadValue)
745 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
746 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
747 break;
748
749 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600750 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600751 if (glslangIntermediate->getPixelCenterInteger())
752 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600753
John Kessenich140f3df2015-06-26 16:58:36 -0600754 if (glslangIntermediate->getOriginUpperLeft())
755 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600756 else
757 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600758
759 if (glslangIntermediate->getEarlyFragmentTests())
760 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
761
762 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600763 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
764 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
765 default: mode = spv::BadValue; break;
766 }
767 if (mode != spv::BadValue)
768 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
769
770 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
771 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600772 break;
773
774 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600775 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600776 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
777 glslangIntermediate->getLocalSize(1),
778 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600779 break;
780
781 default:
782 break;
783 }
784
785}
786
John Kessenich7ba63412015-12-20 17:37:07 -0700787// Finish everything and dump
788void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
789{
790 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100791 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
792 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700793
qiningda397332016-03-09 19:54:03 -0500794 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700795 builder.dump(out);
796}
797
John Kessenich140f3df2015-06-26 16:58:36 -0600798TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
799{
800 if (! mainTerminated) {
801 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
802 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600803 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600804 }
805}
806
807//
808// Implement the traversal functions.
809//
810// Return true from interior nodes to have the external traversal
811// continue on to children. Return false if children were
812// already processed.
813//
814
815//
qining25262b32016-05-06 17:25:16 -0400816// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600817// - uniform/input reads
818// - output writes
819// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
820// - something simple that degenerates into the last bullet
821//
822void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
823{
qining75d1d802016-04-06 14:42:01 -0400824 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
825 if (symbol->getType().getQualifier().isSpecConstant())
826 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
827
John Kessenich140f3df2015-06-26 16:58:36 -0600828 // getSymbolId() will set up all the IO decorations on the first call.
829 // Formal function parameters were mapped during makeFunctions().
830 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700831
832 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
833 if (builder.isPointer(id)) {
834 spv::StorageClass sc = builder.getStorageClass(id);
835 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
836 iOSet.insert(id);
837 }
838
839 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700840 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600841 // Prepare to generate code for the access
842
843 // L-value chains will be computed left to right. We're on the symbol now,
844 // which is the left-most part of the access chain, so now is "clear" time,
845 // followed by setting the base.
846 builder.clearAccessChain();
847
848 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700849 // except for
850 // A) "const in" arguments to a function, which are an intermediate object.
851 // See comments in handleUserFunctionCall().
852 // B) Specialization constants (normal constant don't even come in as a variable),
853 // These are also pure R-values.
854 glslang::TQualifier qualifier = symbol->getQualifier();
855 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
856 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600857 builder.setAccessChainRValue(id);
858 else
859 builder.setAccessChainLValue(id);
860 }
861}
862
863bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
864{
qining40887662016-04-03 22:20:42 -0400865 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
866 if (node->getType().getQualifier().isSpecConstant())
867 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
868
John Kessenich140f3df2015-06-26 16:58:36 -0600869 // First, handle special cases
870 switch (node->getOp()) {
871 case glslang::EOpAssign:
872 case glslang::EOpAddAssign:
873 case glslang::EOpSubAssign:
874 case glslang::EOpMulAssign:
875 case glslang::EOpVectorTimesMatrixAssign:
876 case glslang::EOpVectorTimesScalarAssign:
877 case glslang::EOpMatrixTimesScalarAssign:
878 case glslang::EOpMatrixTimesMatrixAssign:
879 case glslang::EOpDivAssign:
880 case glslang::EOpModAssign:
881 case glslang::EOpAndAssign:
882 case glslang::EOpInclusiveOrAssign:
883 case glslang::EOpExclusiveOrAssign:
884 case glslang::EOpLeftShiftAssign:
885 case glslang::EOpRightShiftAssign:
886 // A bin-op assign "a += b" means the same thing as "a = a + b"
887 // where a is evaluated before b. For a simple assignment, GLSL
888 // says to evaluate the left before the right. So, always, left
889 // node then right node.
890 {
891 // get the left l-value, save it away
892 builder.clearAccessChain();
893 node->getLeft()->traverse(this);
894 spv::Builder::AccessChain lValue = builder.getAccessChain();
895
896 // evaluate the right
897 builder.clearAccessChain();
898 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700899 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600900
901 if (node->getOp() != glslang::EOpAssign) {
902 // the left is also an r-value
903 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700904 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600905
906 // do the operation
qining25262b32016-05-06 17:25:16 -0400907 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
908 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600909 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
910 node->getType().getBasicType());
911
912 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700913 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600914 }
915
916 // store the result
917 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800918 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600919
920 // assignments are expressions having an rValue after they are evaluated...
921 builder.clearAccessChain();
922 builder.setAccessChainRValue(rValue);
923 }
924 return false;
925 case glslang::EOpIndexDirect:
926 case glslang::EOpIndexDirectStruct:
927 {
928 // Get the left part of the access chain.
929 node->getLeft()->traverse(this);
930
931 // Add the next element in the chain
932
David Netoa901ffe2016-06-08 14:11:40 +0100933 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600934 if (! node->getLeft()->getType().isArray() &&
935 node->getLeft()->getType().isVector() &&
936 node->getOp() == glslang::EOpIndexDirect) {
937 // This is essentially a hard-coded vector swizzle of size 1,
938 // so short circuit the access-chain stuff with a swizzle.
939 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100940 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600941 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600942 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100943 int spvIndex = glslangIndex;
944 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
945 node->getOp() == glslang::EOpIndexDirectStruct)
946 {
947 // This may be, e.g., an anonymous block-member selection, which generally need
948 // index remapping due to hidden members in anonymous blocks.
949 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
950 assert(remapper.size() > 0);
951 spvIndex = remapper[glslangIndex];
952 }
John Kessenichebb50532016-05-16 19:22:05 -0600953
David Netoa901ffe2016-06-08 14:11:40 +0100954 // normal case for indexing array or structure or block
955 builder.accessChainPush(builder.makeIntConstant(spvIndex));
956
957 // Add capabilities here for accessing PointSize and clip/cull distance.
958 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600959 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100960 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600961 }
962 }
963 return false;
964 case glslang::EOpIndexIndirect:
965 {
966 // Structure or array or vector indirection.
967 // Will use native SPIR-V access-chain for struct and array indirection;
968 // matrices are arrays of vectors, so will also work for a matrix.
969 // Will use the access chain's 'component' for variable index into a vector.
970
971 // This adapter is building access chains left to right.
972 // Set up the access chain to the left.
973 node->getLeft()->traverse(this);
974
975 // save it so that computing the right side doesn't trash it
976 spv::Builder::AccessChain partial = builder.getAccessChain();
977
978 // compute the next index in the chain
979 builder.clearAccessChain();
980 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700981 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600982
983 // restore the saved access chain
984 builder.setAccessChain(partial);
985
986 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600987 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600988 else
John Kessenichfa668da2015-09-13 14:46:30 -0600989 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600990 }
991 return false;
992 case glslang::EOpVectorSwizzle:
993 {
994 node->getLeft()->traverse(this);
995 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
996 std::vector<unsigned> swizzle;
997 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
998 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600999 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001000 }
1001 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001002 case glslang::EOpLogicalOr:
1003 case glslang::EOpLogicalAnd:
1004 {
1005
1006 // These may require short circuiting, but can sometimes be done as straight
1007 // binary operations. The right operand must be short circuited if it has
1008 // side effects, and should probably be if it is complex.
1009 if (isTrivial(node->getRight()->getAsTyped()))
1010 break; // handle below as a normal binary operation
1011 // otherwise, we need to do dynamic short circuiting on the right operand
1012 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1013 builder.clearAccessChain();
1014 builder.setAccessChainRValue(result);
1015 }
1016 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001017 default:
1018 break;
1019 }
1020
1021 // Assume generic binary op...
1022
John Kessenich32cfd492016-02-02 12:37:46 -07001023 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001024 builder.clearAccessChain();
1025 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001026 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001027
John Kessenich32cfd492016-02-02 12:37:46 -07001028 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001029 builder.clearAccessChain();
1030 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001031 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001032
John Kessenich32cfd492016-02-02 12:37:46 -07001033 // get result
1034 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001035 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001036 convertGlslangToSpvType(node->getType()), left, right,
1037 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001038
John Kessenich50e57562015-12-21 21:21:11 -07001039 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001040 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001041 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001042 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001043 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001044 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001045 return false;
1046 }
John Kessenich140f3df2015-06-26 16:58:36 -06001047}
1048
1049bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1050{
qining40887662016-04-03 22:20:42 -04001051 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1052 if (node->getType().getQualifier().isSpecConstant())
1053 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1054
John Kessenichfc51d282015-08-19 13:34:18 -06001055 spv::Id result = spv::NoResult;
1056
1057 // try texturing first
1058 result = createImageTextureFunctionCall(node);
1059 if (result != spv::NoResult) {
1060 builder.clearAccessChain();
1061 builder.setAccessChainRValue(result);
1062
1063 return false; // done with this node
1064 }
1065
1066 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001067
1068 if (node->getOp() == glslang::EOpArrayLength) {
1069 // Quite special; won't want to evaluate the operand.
1070
1071 // Normal .length() would have been constant folded by the front-end.
1072 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001073 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001074 assert(node->getOperand()->getType().isRuntimeSizedArray());
1075 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1076 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001077 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1078 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001079
1080 builder.clearAccessChain();
1081 builder.setAccessChainRValue(length);
1082
1083 return false;
1084 }
1085
John Kessenichfc51d282015-08-19 13:34:18 -06001086 // Start by evaluating the operand
1087
John Kessenich140f3df2015-06-26 16:58:36 -06001088 builder.clearAccessChain();
1089 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001090
Rex Xufc618912015-09-09 16:42:49 +08001091 spv::Id operand = spv::NoResult;
1092
1093 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1094 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001095 node->getOp() == glslang::EOpAtomicCounter ||
1096 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001097 operand = builder.accessChainGetLValue(); // Special case l-value operands
1098 else
John Kessenich32cfd492016-02-02 12:37:46 -07001099 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001100
1101 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001102 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001103
1104 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001105 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001106 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001107
1108 // if not, then possibly an operation
1109 if (! result)
qining25262b32016-05-06 17:25:16 -04001110 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001111
1112 if (result) {
1113 builder.clearAccessChain();
1114 builder.setAccessChainRValue(result);
1115
1116 return false; // done with this node
1117 }
1118
1119 // it must be a special case, check...
1120 switch (node->getOp()) {
1121 case glslang::EOpPostIncrement:
1122 case glslang::EOpPostDecrement:
1123 case glslang::EOpPreIncrement:
1124 case glslang::EOpPreDecrement:
1125 {
1126 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001127 spv::Id one = 0;
1128 if (node->getBasicType() == glslang::EbtFloat)
1129 one = builder.makeFloatConstant(1.0F);
1130 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1131 one = builder.makeInt64Constant(1);
1132 else
1133 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001134 glslang::TOperator op;
1135 if (node->getOp() == glslang::EOpPreIncrement ||
1136 node->getOp() == glslang::EOpPostIncrement)
1137 op = glslang::EOpAdd;
1138 else
1139 op = glslang::EOpSub;
1140
qining25262b32016-05-06 17:25:16 -04001141 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1142 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001143 convertGlslangToSpvType(node->getType()), operand, one,
1144 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001145 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001146
1147 // The result of operation is always stored, but conditionally the
1148 // consumed result. The consumed result is always an r-value.
1149 builder.accessChainStore(result);
1150 builder.clearAccessChain();
1151 if (node->getOp() == glslang::EOpPreIncrement ||
1152 node->getOp() == glslang::EOpPreDecrement)
1153 builder.setAccessChainRValue(result);
1154 else
1155 builder.setAccessChainRValue(operand);
1156 }
1157
1158 return false;
1159
1160 case glslang::EOpEmitStreamVertex:
1161 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1162 return false;
1163 case glslang::EOpEndStreamPrimitive:
1164 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1165 return false;
1166
1167 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001168 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001169 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001170 }
John Kessenich140f3df2015-06-26 16:58:36 -06001171}
1172
1173bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1174{
qining27e04a02016-04-14 16:40:20 -04001175 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1176 if (node->getType().getQualifier().isSpecConstant())
1177 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1178
John Kessenichfc51d282015-08-19 13:34:18 -06001179 spv::Id result = spv::NoResult;
1180
1181 // try texturing
1182 result = createImageTextureFunctionCall(node);
1183 if (result != spv::NoResult) {
1184 builder.clearAccessChain();
1185 builder.setAccessChainRValue(result);
1186
1187 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001188 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001189 // "imageStore" is a special case, which has no result
1190 return false;
1191 }
John Kessenichfc51d282015-08-19 13:34:18 -06001192
John Kessenich140f3df2015-06-26 16:58:36 -06001193 glslang::TOperator binOp = glslang::EOpNull;
1194 bool reduceComparison = true;
1195 bool isMatrix = false;
1196 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001197 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001198
1199 assert(node->getOp());
1200
1201 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1202
1203 switch (node->getOp()) {
1204 case glslang::EOpSequence:
1205 {
1206 if (preVisit)
1207 ++sequenceDepth;
1208 else
1209 --sequenceDepth;
1210
1211 if (sequenceDepth == 1) {
1212 // If this is the parent node of all the functions, we want to see them
1213 // early, so all call points have actual SPIR-V functions to reference.
1214 // In all cases, still let the traverser visit the children for us.
1215 makeFunctions(node->getAsAggregate()->getSequence());
1216
1217 // Also, we want all globals initializers to go into the entry of main(), before
1218 // anything else gets there, so visit out of order, doing them all now.
1219 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1220
1221 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1222 // so do them manually.
1223 visitFunctions(node->getAsAggregate()->getSequence());
1224
1225 return false;
1226 }
1227
1228 return true;
1229 }
1230 case glslang::EOpLinkerObjects:
1231 {
1232 if (visit == glslang::EvPreVisit)
1233 linkageOnly = true;
1234 else
1235 linkageOnly = false;
1236
1237 return true;
1238 }
1239 case glslang::EOpComma:
1240 {
1241 // processing from left to right naturally leaves the right-most
1242 // lying around in the access chain
1243 glslang::TIntermSequence& glslangOperands = node->getSequence();
1244 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1245 glslangOperands[i]->traverse(this);
1246
1247 return false;
1248 }
1249 case glslang::EOpFunction:
1250 if (visit == glslang::EvPreVisit) {
1251 if (isShaderEntrypoint(node)) {
1252 inMain = true;
1253 builder.setBuildPoint(shaderEntry->getLastBlock());
1254 } else {
1255 handleFunctionEntry(node);
1256 }
1257 } else {
1258 if (inMain)
1259 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001260 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001261 inMain = false;
1262 }
1263
1264 return true;
1265 case glslang::EOpParameters:
1266 // Parameters will have been consumed by EOpFunction processing, but not
1267 // the body, so we still visited the function node's children, making this
1268 // child redundant.
1269 return false;
1270 case glslang::EOpFunctionCall:
1271 {
1272 if (node->isUserDefined())
1273 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001274 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1275 if (result) {
1276 builder.clearAccessChain();
1277 builder.setAccessChainRValue(result);
1278 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001279 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001280
1281 return false;
1282 }
1283 case glslang::EOpConstructMat2x2:
1284 case glslang::EOpConstructMat2x3:
1285 case glslang::EOpConstructMat2x4:
1286 case glslang::EOpConstructMat3x2:
1287 case glslang::EOpConstructMat3x3:
1288 case glslang::EOpConstructMat3x4:
1289 case glslang::EOpConstructMat4x2:
1290 case glslang::EOpConstructMat4x3:
1291 case glslang::EOpConstructMat4x4:
1292 case glslang::EOpConstructDMat2x2:
1293 case glslang::EOpConstructDMat2x3:
1294 case glslang::EOpConstructDMat2x4:
1295 case glslang::EOpConstructDMat3x2:
1296 case glslang::EOpConstructDMat3x3:
1297 case glslang::EOpConstructDMat3x4:
1298 case glslang::EOpConstructDMat4x2:
1299 case glslang::EOpConstructDMat4x3:
1300 case glslang::EOpConstructDMat4x4:
1301 isMatrix = true;
1302 // fall through
1303 case glslang::EOpConstructFloat:
1304 case glslang::EOpConstructVec2:
1305 case glslang::EOpConstructVec3:
1306 case glslang::EOpConstructVec4:
1307 case glslang::EOpConstructDouble:
1308 case glslang::EOpConstructDVec2:
1309 case glslang::EOpConstructDVec3:
1310 case glslang::EOpConstructDVec4:
1311 case glslang::EOpConstructBool:
1312 case glslang::EOpConstructBVec2:
1313 case glslang::EOpConstructBVec3:
1314 case glslang::EOpConstructBVec4:
1315 case glslang::EOpConstructInt:
1316 case glslang::EOpConstructIVec2:
1317 case glslang::EOpConstructIVec3:
1318 case glslang::EOpConstructIVec4:
1319 case glslang::EOpConstructUint:
1320 case glslang::EOpConstructUVec2:
1321 case glslang::EOpConstructUVec3:
1322 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001323 case glslang::EOpConstructInt64:
1324 case glslang::EOpConstructI64Vec2:
1325 case glslang::EOpConstructI64Vec3:
1326 case glslang::EOpConstructI64Vec4:
1327 case glslang::EOpConstructUint64:
1328 case glslang::EOpConstructU64Vec2:
1329 case glslang::EOpConstructU64Vec3:
1330 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001331 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001332 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001333 {
1334 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001335 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001336 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1337 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001338 if (node->getOp() == glslang::EOpConstructTextureSampler)
1339 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1340 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001341 std::vector<spv::Id> constituents;
1342 for (int c = 0; c < (int)arguments.size(); ++c)
1343 constituents.push_back(arguments[c]);
1344 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001345 } else if (isMatrix)
1346 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1347 else
1348 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001349
1350 builder.clearAccessChain();
1351 builder.setAccessChainRValue(constructed);
1352
1353 return false;
1354 }
1355
1356 // These six are component-wise compares with component-wise results.
1357 // Forward on to createBinaryOperation(), requesting a vector result.
1358 case glslang::EOpLessThan:
1359 case glslang::EOpGreaterThan:
1360 case glslang::EOpLessThanEqual:
1361 case glslang::EOpGreaterThanEqual:
1362 case glslang::EOpVectorEqual:
1363 case glslang::EOpVectorNotEqual:
1364 {
1365 // Map the operation to a binary
1366 binOp = node->getOp();
1367 reduceComparison = false;
1368 switch (node->getOp()) {
1369 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1370 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1371 default: binOp = node->getOp(); break;
1372 }
1373
1374 break;
1375 }
1376 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001377 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001378 binOp = glslang::EOpMul;
1379 break;
1380 case glslang::EOpOuterProduct:
1381 // two vectors multiplied to make a matrix
1382 binOp = glslang::EOpOuterProduct;
1383 break;
1384 case glslang::EOpDot:
1385 {
qining25262b32016-05-06 17:25:16 -04001386 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001387 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001388 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001389 binOp = glslang::EOpMul;
1390 break;
1391 }
1392 case glslang::EOpMod:
1393 // when an aggregate, this is the floating-point mod built-in function,
1394 // which can be emitted by the one in createBinaryOperation()
1395 binOp = glslang::EOpMod;
1396 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001397 case glslang::EOpEmitVertex:
1398 case glslang::EOpEndPrimitive:
1399 case glslang::EOpBarrier:
1400 case glslang::EOpMemoryBarrier:
1401 case glslang::EOpMemoryBarrierAtomicCounter:
1402 case glslang::EOpMemoryBarrierBuffer:
1403 case glslang::EOpMemoryBarrierImage:
1404 case glslang::EOpMemoryBarrierShared:
1405 case glslang::EOpGroupMemoryBarrier:
1406 noReturnValue = true;
1407 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1408 break;
1409
John Kessenich426394d2015-07-23 10:22:48 -06001410 case glslang::EOpAtomicAdd:
1411 case glslang::EOpAtomicMin:
1412 case glslang::EOpAtomicMax:
1413 case glslang::EOpAtomicAnd:
1414 case glslang::EOpAtomicOr:
1415 case glslang::EOpAtomicXor:
1416 case glslang::EOpAtomicExchange:
1417 case glslang::EOpAtomicCompSwap:
1418 atomic = true;
1419 break;
1420
John Kessenich140f3df2015-06-26 16:58:36 -06001421 default:
1422 break;
1423 }
1424
1425 //
1426 // See if it maps to a regular operation.
1427 //
John Kessenich140f3df2015-06-26 16:58:36 -06001428 if (binOp != glslang::EOpNull) {
1429 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1430 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1431 assert(left && right);
1432
1433 builder.clearAccessChain();
1434 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001435 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001436
1437 builder.clearAccessChain();
1438 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001439 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001440
qining25262b32016-05-06 17:25:16 -04001441 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1442 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001443 left->getType().getBasicType(), reduceComparison);
1444
1445 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001446 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001447 builder.clearAccessChain();
1448 builder.setAccessChainRValue(result);
1449
1450 return false;
1451 }
1452
John Kessenich426394d2015-07-23 10:22:48 -06001453 //
1454 // Create the list of operands.
1455 //
John Kessenich140f3df2015-06-26 16:58:36 -06001456 glslang::TIntermSequence& glslangOperands = node->getSequence();
1457 std::vector<spv::Id> operands;
1458 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1459 builder.clearAccessChain();
1460 glslangOperands[arg]->traverse(this);
1461
1462 // special case l-value operands; there are just a few
1463 bool lvalue = false;
1464 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001465 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001466 case glslang::EOpModf:
1467 if (arg == 1)
1468 lvalue = true;
1469 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001470 case glslang::EOpInterpolateAtSample:
1471 case glslang::EOpInterpolateAtOffset:
1472 if (arg == 0)
1473 lvalue = true;
1474 break;
Rex Xud4782c12015-09-06 16:30:11 +08001475 case glslang::EOpAtomicAdd:
1476 case glslang::EOpAtomicMin:
1477 case glslang::EOpAtomicMax:
1478 case glslang::EOpAtomicAnd:
1479 case glslang::EOpAtomicOr:
1480 case glslang::EOpAtomicXor:
1481 case glslang::EOpAtomicExchange:
1482 case glslang::EOpAtomicCompSwap:
1483 if (arg == 0)
1484 lvalue = true;
1485 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001486 case glslang::EOpAddCarry:
1487 case glslang::EOpSubBorrow:
1488 if (arg == 2)
1489 lvalue = true;
1490 break;
1491 case glslang::EOpUMulExtended:
1492 case glslang::EOpIMulExtended:
1493 if (arg >= 2)
1494 lvalue = true;
1495 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001496 default:
1497 break;
1498 }
1499 if (lvalue)
1500 operands.push_back(builder.accessChainGetLValue());
1501 else
John Kessenich32cfd492016-02-02 12:37:46 -07001502 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001503 }
John Kessenich426394d2015-07-23 10:22:48 -06001504
1505 if (atomic) {
1506 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001507 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001508 } else {
1509 // Pass through to generic operations.
1510 switch (glslangOperands.size()) {
1511 case 0:
1512 result = createNoArgOperation(node->getOp());
1513 break;
1514 case 1:
qining25262b32016-05-06 17:25:16 -04001515 result = createUnaryOperation(
1516 node->getOp(), precision,
1517 TranslateNoContractionDecoration(node->getType().getQualifier()),
1518 convertGlslangToSpvType(node->getType()), operands.front(),
1519 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001520 break;
1521 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001522 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001523 break;
1524 }
John Kessenich140f3df2015-06-26 16:58:36 -06001525 }
1526
1527 if (noReturnValue)
1528 return false;
1529
1530 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001531 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001532 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001533 } else {
1534 builder.clearAccessChain();
1535 builder.setAccessChainRValue(result);
1536 return false;
1537 }
1538}
1539
1540bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1541{
1542 // This path handles both if-then-else and ?:
1543 // The if-then-else has a node type of void, while
1544 // ?: has a non-void node type
1545 spv::Id result = 0;
1546 if (node->getBasicType() != glslang::EbtVoid) {
1547 // don't handle this as just on-the-fly temporaries, because there will be two names
1548 // and better to leave SSA to later passes
1549 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1550 }
1551
1552 // emit the condition before doing anything with selection
1553 node->getCondition()->traverse(this);
1554
1555 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001556 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001557
1558 if (node->getTrueBlock()) {
1559 // emit the "then" statement
1560 node->getTrueBlock()->traverse(this);
1561 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001562 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001563 }
1564
1565 if (node->getFalseBlock()) {
1566 ifBuilder.makeBeginElse();
1567 // emit the "else" statement
1568 node->getFalseBlock()->traverse(this);
1569 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001570 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001571 }
1572
1573 ifBuilder.makeEndIf();
1574
1575 if (result) {
1576 // GLSL only has r-values as the result of a :?, but
1577 // if we have an l-value, that can be more efficient if it will
1578 // become the base of a complex r-value expression, because the
1579 // next layer copies r-values into memory to use the access-chain mechanism
1580 builder.clearAccessChain();
1581 builder.setAccessChainLValue(result);
1582 }
1583
1584 return false;
1585}
1586
1587bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1588{
1589 // emit and get the condition before doing anything with switch
1590 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001591 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001592
1593 // browse the children to sort out code segments
1594 int defaultSegment = -1;
1595 std::vector<TIntermNode*> codeSegments;
1596 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1597 std::vector<int> caseValues;
1598 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1599 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1600 TIntermNode* child = *c;
1601 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001602 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001603 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001604 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001605 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1606 } else
1607 codeSegments.push_back(child);
1608 }
1609
qining25262b32016-05-06 17:25:16 -04001610 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001611 // statements between the last case and the end of the switch statement
1612 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1613 (int)codeSegments.size() == defaultSegment)
1614 codeSegments.push_back(nullptr);
1615
1616 // make the switch statement
1617 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001618 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001619
1620 // emit all the code in the segments
1621 breakForLoop.push(false);
1622 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1623 builder.nextSwitchSegment(segmentBlocks, s);
1624 if (codeSegments[s])
1625 codeSegments[s]->traverse(this);
1626 else
1627 builder.addSwitchBreak();
1628 }
1629 breakForLoop.pop();
1630
1631 builder.endSwitch(segmentBlocks);
1632
1633 return false;
1634}
1635
1636void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1637{
1638 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001639 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001640
1641 builder.clearAccessChain();
1642 builder.setAccessChainRValue(constant);
1643}
1644
1645bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1646{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001647 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001648 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001649 // Spec requires back edges to target header blocks, and every header block
1650 // must dominate its merge block. Make a header block first to ensure these
1651 // conditions are met. By definition, it will contain OpLoopMerge, followed
1652 // by a block-ending branch. But we don't want to put any other body/test
1653 // instructions in it, since the body/test may have arbitrary instructions,
1654 // including merges of its own.
1655 builder.setBuildPoint(&blocks.head);
1656 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001657 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001658 spv::Block& test = builder.makeNewBlock();
1659 builder.createBranch(&test);
1660
1661 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001662 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001663 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001664 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001665 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1666
1667 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001668 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001669 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001670 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001671 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001672 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001673
1674 builder.setBuildPoint(&blocks.continue_target);
1675 if (node->getTerminal())
1676 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001677 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001678 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001679 builder.createBranch(&blocks.body);
1680
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001681 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001682 builder.setBuildPoint(&blocks.body);
1683 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001684 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001685 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001686 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001687
1688 builder.setBuildPoint(&blocks.continue_target);
1689 if (node->getTerminal())
1690 node->getTerminal()->traverse(this);
1691 if (node->getTest()) {
1692 node->getTest()->traverse(this);
1693 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001694 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001695 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001696 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001697 // TODO: unless there was a break/return/discard instruction
1698 // somewhere in the body, this is an infinite loop, so we should
1699 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001700 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001701 }
John Kessenich140f3df2015-06-26 16:58:36 -06001702 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001703 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001704 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001705 return false;
1706}
1707
1708bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1709{
1710 if (node->getExpression())
1711 node->getExpression()->traverse(this);
1712
1713 switch (node->getFlowOp()) {
1714 case glslang::EOpKill:
1715 builder.makeDiscard();
1716 break;
1717 case glslang::EOpBreak:
1718 if (breakForLoop.top())
1719 builder.createLoopExit();
1720 else
1721 builder.addSwitchBreak();
1722 break;
1723 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001724 builder.createLoopContinue();
1725 break;
1726 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001727 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001728 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001729 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001730 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001731
1732 builder.clearAccessChain();
1733 break;
1734
1735 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001736 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001737 break;
1738 }
1739
1740 return false;
1741}
1742
1743spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1744{
qining25262b32016-05-06 17:25:16 -04001745 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001746 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001747 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001748 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001749 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001750 }
1751
1752 // Now, handle actual variables
1753 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1754 spv::Id spvType = convertGlslangToSpvType(node->getType());
1755
1756 const char* name = node->getName().c_str();
1757 if (glslang::IsAnonymous(name))
1758 name = "";
1759
1760 return builder.createVariable(storageClass, spvType, name);
1761}
1762
1763// Return type Id of the sampled type.
1764spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1765{
1766 switch (sampler.type) {
1767 case glslang::EbtFloat: return builder.makeFloatType(32);
1768 case glslang::EbtInt: return builder.makeIntType(32);
1769 case glslang::EbtUint: return builder.makeUintType(32);
1770 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001771 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001772 return builder.makeFloatType(32);
1773 }
1774}
1775
John Kessenich3ac051e2015-12-20 11:29:16 -07001776// Convert from a glslang type to an SPV type, by calling into a
1777// recursive version of this function. This establishes the inherited
1778// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001779spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1780{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001781 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001782}
1783
1784// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001785// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001786spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001787{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001788 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001789
1790 switch (type.getBasicType()) {
1791 case glslang::EbtVoid:
1792 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001793 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001794 break;
1795 case glslang::EbtFloat:
1796 spvType = builder.makeFloatType(32);
1797 break;
1798 case glslang::EbtDouble:
1799 spvType = builder.makeFloatType(64);
1800 break;
1801 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001802 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1803 // a 32-bit int where non-0 means true.
1804 if (explicitLayout != glslang::ElpNone)
1805 spvType = builder.makeUintType(32);
1806 else
1807 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001808 break;
1809 case glslang::EbtInt:
1810 spvType = builder.makeIntType(32);
1811 break;
1812 case glslang::EbtUint:
1813 spvType = builder.makeUintType(32);
1814 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001815 case glslang::EbtInt64:
1816 builder.addCapability(spv::CapabilityInt64);
1817 spvType = builder.makeIntType(64);
1818 break;
1819 case glslang::EbtUint64:
1820 builder.addCapability(spv::CapabilityInt64);
1821 spvType = builder.makeUintType(64);
1822 break;
John Kessenich426394d2015-07-23 10:22:48 -06001823 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001824 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 -06001825 spvType = builder.makeUintType(32);
1826 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001827 case glslang::EbtSampler:
1828 {
1829 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001830 if (sampler.sampler) {
1831 // pure sampler
1832 spvType = builder.makeSamplerType();
1833 } else {
1834 // an image is present, make its type
1835 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1836 sampler.image ? 2 : 1, TranslateImageFormat(type));
1837 if (sampler.combined) {
1838 // already has both image and sampler, make the combined type
1839 spvType = builder.makeSampledImageType(spvType);
1840 }
John Kessenich55e7d112015-11-15 21:33:39 -07001841 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001842 }
John Kessenich140f3df2015-06-26 16:58:36 -06001843 break;
1844 case glslang::EbtStruct:
1845 case glslang::EbtBlock:
1846 {
1847 // If we've seen this struct type, return it
1848 const glslang::TTypeList* glslangStruct = type.getStruct();
1849 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001850
1851 // Try to share structs for different layouts, but not yet for other
1852 // kinds of qualification (primarily not yet including interpolant qualification).
1853 if (! HasNonLayoutQualifiers(qualifier))
1854 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1855 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001856 break;
1857
1858 // else, we haven't seen it...
1859
1860 // Create a vector of struct types for SPIR-V to consume
1861 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1862 if (type.getBasicType() == glslang::EbtBlock)
1863 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001864 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001865 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1866 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1867 if (glslangType.hiddenMember()) {
1868 ++memberDelta;
1869 if (type.getBasicType() == glslang::EbtBlock)
1870 memberRemapper[glslangStruct][i] = -1;
1871 } else {
1872 if (type.getBasicType() == glslang::EbtBlock)
1873 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001874 // modify just this child's view of the qualifier
1875 glslang::TQualifier subQualifier = glslangType.getQualifier();
1876 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001877
1878 // manually inherit location; it's more complex
1879 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1880 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1881 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001882 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001883
1884 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001885 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001886 }
1887 }
1888
1889 // Make the SPIR-V type
1890 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001891 if (! HasNonLayoutQualifiers(qualifier))
1892 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001893
1894 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001895 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001896 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001897 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1898 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1899 int member = i;
1900 if (type.getBasicType() == glslang::EbtBlock)
1901 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001902
John Kesseniche0b6cad2015-12-24 10:30:13 -07001903 // modify just this child's view of the qualifier
1904 glslang::TQualifier subQualifier = glslangType.getQualifier();
1905 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001906
John Kessenich140f3df2015-06-26 16:58:36 -06001907 // using -1 above to indicate a hidden member
1908 if (member >= 0) {
1909 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001910 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001911 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
Rex Xubbceed72016-05-21 09:40:44 +08001912 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001913 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
scygan8add1512016-05-06 16:54:54 +02001914 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
Rex Xubbceed72016-05-21 09:40:44 +08001915 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(subQualifier));
scygan8add1512016-05-06 16:54:54 +02001916 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001917 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001918
Rex Xu1da878f2016-02-21 20:59:01 +08001919 if (qualifier.storage == glslang::EvqBuffer) {
1920 std::vector<spv::Decoration> memory;
1921 TranslateMemoryDecoration(subQualifier, memory);
1922 for (unsigned int i = 0; i < memory.size(); ++i)
1923 addMemberDecoration(spvType, member, memory[i]);
1924 }
1925
John Kessenich09677482016-02-19 12:21:50 -07001926 // compute location decoration; tricky based on whether inheritance is at play
1927 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1928 // probably move to the linker stage of the front end proper, and just have the
1929 // answer sitting already distributed throughout the individual member locations.
1930 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001931 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001932 // struct members should not have explicit locations
1933 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001934 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001935 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001936 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1937 // The members, and their nested types, must not themselves have Location decorations.
1938 }
John Kessenich09677482016-02-19 12:21:50 -07001939 else if (qualifier.hasLocation()) // inheritance
1940 location = qualifier.layoutLocation + locationOffset;
1941 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001942 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001943 if (location >= 0)
1944 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1945
1946 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001947 if (glslangType.getQualifier().hasComponent())
1948 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1949 if (glslangType.getQualifier().hasXfbOffset())
1950 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001951 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001952 // figure out what to do with offset, which is accumulating
1953 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001954 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001955 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001956 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001957 offset = nextOffset;
1958 }
John Kessenich140f3df2015-06-26 16:58:36 -06001959
John Kessenichf85e8062015-12-19 13:57:10 -07001960 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001961 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001962
John Kessenich140f3df2015-06-26 16:58:36 -06001963 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001964 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001965 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001966 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001967 }
1968 }
1969
1970 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001971 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001972 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001973 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001974 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001975 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001976 }
John Kessenich140f3df2015-06-26 16:58:36 -06001977 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001978 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001979 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001980 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001981 if (type.getQualifier().hasXfbBuffer())
1982 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1983 }
1984 }
1985 break;
1986 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001987 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001988 break;
1989 }
1990
1991 if (type.isMatrix())
1992 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1993 else {
1994 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1995 if (type.getVectorSize() > 1)
1996 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1997 }
1998
1999 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002000 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2001
John Kessenichc9a80832015-09-12 12:17:44 -06002002 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002003 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002004 // We need to decorate array strides for types needing explicit layout, except blocks.
2005 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002006 // Use a dummy glslang type for querying internal strides of
2007 // arrays of arrays, but using just a one-dimensional array.
2008 glslang::TType simpleArrayType(type, 0); // deference type of the array
2009 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2010 simpleArrayType.getArraySizes().dereference();
2011
2012 // Will compute the higher-order strides here, rather than making a whole
2013 // pile of types and doing repetitive recursion on their contents.
2014 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2015 }
John Kessenichf8842e52016-01-04 19:22:56 -07002016
2017 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002018 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002019 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002020 if (stride > 0)
2021 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002022 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002023 }
2024 } else {
2025 // single-dimensional array, and don't yet have stride
2026
John Kessenichf8842e52016-01-04 19:22:56 -07002027 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002028 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2029 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002030 }
John Kessenich31ed4832015-09-09 17:51:38 -06002031
John Kessenichc9a80832015-09-12 12:17:44 -06002032 // Do the outer dimension, which might not be known for a runtime-sized array
2033 if (type.isRuntimeSizedArray()) {
2034 spvType = builder.makeRuntimeArray(spvType);
2035 } else {
2036 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002037 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002038 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002039 if (stride > 0)
2040 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002041 }
2042
2043 return spvType;
2044}
2045
John Kessenich6c292d32016-02-15 20:58:50 -07002046// Turn the expression forming the array size into an id.
2047// This is not quite trivial, because of specialization constants.
2048// Sometimes, a raw constant is turned into an Id, and sometimes
2049// a specialization constant expression is.
2050spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2051{
2052 // First, see if this is sized with a node, meaning a specialization constant:
2053 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2054 if (specNode != nullptr) {
2055 builder.clearAccessChain();
2056 specNode->traverse(this);
2057 return accessChainLoad(specNode->getAsTyped()->getType());
2058 }
qining25262b32016-05-06 17:25:16 -04002059
John Kessenich6c292d32016-02-15 20:58:50 -07002060 // Otherwise, need a compile-time (front end) size, get it:
2061 int size = arraySizes.getDimSize(dim);
2062 assert(size > 0);
2063 return builder.makeUintConstant(size);
2064}
2065
John Kessenich103bef92016-02-08 21:38:15 -07002066// Wrap the builder's accessChainLoad to:
2067// - localize handling of RelaxedPrecision
2068// - use the SPIR-V inferred type instead of another conversion of the glslang type
2069// (avoids unnecessary work and possible type punning for structures)
2070// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002071spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2072{
John Kessenich103bef92016-02-08 21:38:15 -07002073 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2074 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2075
2076 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002077 if (type.getBasicType() == glslang::EbtBool) {
2078 if (builder.isScalarType(nominalTypeId)) {
2079 // Conversion for bool
2080 spv::Id boolType = builder.makeBoolType();
2081 if (nominalTypeId != boolType)
2082 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2083 } else if (builder.isVectorType(nominalTypeId)) {
2084 // Conversion for bvec
2085 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2086 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2087 if (nominalTypeId != bvecType)
2088 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2089 }
2090 }
John Kessenich103bef92016-02-08 21:38:15 -07002091
2092 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002093}
2094
Rex Xu27253232016-02-23 17:51:09 +08002095// Wrap the builder's accessChainStore to:
2096// - do conversion of concrete to abstract type
2097void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2098{
2099 // Need to convert to abstract types when necessary
2100 if (type.getBasicType() == glslang::EbtBool) {
2101 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2102
2103 if (builder.isScalarType(nominalTypeId)) {
2104 // Conversion for bool
2105 spv::Id boolType = builder.makeBoolType();
2106 if (nominalTypeId != boolType) {
2107 spv::Id zero = builder.makeUintConstant(0);
2108 spv::Id one = builder.makeUintConstant(1);
2109 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2110 }
2111 } else if (builder.isVectorType(nominalTypeId)) {
2112 // Conversion for bvec
2113 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2114 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2115 if (nominalTypeId != bvecType) {
2116 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2117 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2118 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2119 }
2120 }
2121 }
2122
2123 builder.accessChainStore(rvalue);
2124}
2125
John Kessenichf85e8062015-12-19 13:57:10 -07002126// Decide whether or not this type should be
2127// decorated with offsets and strides, and if so
2128// whether std140 or std430 rules should be applied.
2129glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002130{
John Kessenichf85e8062015-12-19 13:57:10 -07002131 // has to be a block
2132 if (type.getBasicType() != glslang::EbtBlock)
2133 return glslang::ElpNone;
2134
2135 // has to be a uniform or buffer block
2136 if (type.getQualifier().storage != glslang::EvqUniform &&
2137 type.getQualifier().storage != glslang::EvqBuffer)
2138 return glslang::ElpNone;
2139
2140 // return the layout to use
2141 switch (type.getQualifier().layoutPacking) {
2142 case glslang::ElpStd140:
2143 case glslang::ElpStd430:
2144 return type.getQualifier().layoutPacking;
2145 default:
2146 return glslang::ElpNone;
2147 }
John Kessenich31ed4832015-09-09 17:51:38 -06002148}
2149
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002150// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002151int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002152{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002153 int size;
John Kessenich49987892015-12-29 17:11:44 -07002154 int stride;
2155 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002156
2157 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002158}
2159
John Kessenich49987892015-12-29 17:11:44 -07002160// 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 -07002161// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002162int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002163{
John Kessenich49987892015-12-29 17:11:44 -07002164 glslang::TType elementType;
2165 elementType.shallowCopy(matrixType);
2166 elementType.clearArraySizes();
2167
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002168 int size;
John Kessenich49987892015-12-29 17:11:44 -07002169 int stride;
2170 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2171
2172 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002173}
2174
John Kessenich5e4b1242015-08-06 22:53:06 -06002175// Given a member type of a struct, realign the current offset for it, and compute
2176// the next (not yet aligned) offset for the next member, which will get aligned
2177// on the next call.
2178// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2179// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2180// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002181void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002182 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002183{
2184 // this will get a positive value when deemed necessary
2185 nextOffset = -1;
2186
John Kessenich5e4b1242015-08-06 22:53:06 -06002187 // override anything in currentOffset with user-set offset
2188 if (memberType.getQualifier().hasOffset())
2189 currentOffset = memberType.getQualifier().layoutOffset;
2190
2191 // It could be that current linker usage in glslang updated all the layoutOffset,
2192 // in which case the following code does not matter. But, that's not quite right
2193 // once cross-compilation unit GLSL validation is done, as the original user
2194 // settings are needed in layoutOffset, and then the following will come into play.
2195
John Kessenichf85e8062015-12-19 13:57:10 -07002196 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002197 if (! memberType.getQualifier().hasOffset())
2198 currentOffset = -1;
2199
2200 return;
2201 }
2202
John Kessenichf85e8062015-12-19 13:57:10 -07002203 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002204 if (currentOffset < 0)
2205 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002206
John Kessenich5e4b1242015-08-06 22:53:06 -06002207 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2208 // but possibly not yet correctly aligned.
2209
2210 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002211 int dummyStride;
2212 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002213 glslang::RoundToPow2(currentOffset, memberAlignment);
2214 nextOffset = currentOffset + memberSize;
2215}
2216
David Netoa901ffe2016-06-08 14:11:40 +01002217void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002218{
David Netoa901ffe2016-06-08 14:11:40 +01002219 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2220 switch (glslangBuiltIn)
2221 {
2222 case glslang::EbvClipDistance:
2223 case glslang::EbvCullDistance:
2224 case glslang::EbvPointSize:
2225 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2226 // Alternately, we could just call this for any glslang built-in, since the
2227 // capability already guards against duplicates.
2228 TranslateBuiltInDecoration(glslangBuiltIn, false);
2229 break;
2230 default:
2231 // Capabilities were already generated when the struct was declared.
2232 break;
2233 }
John Kessenichebb50532016-05-16 19:22:05 -06002234}
2235
John Kessenich140f3df2015-06-26 16:58:36 -06002236bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2237{
John Kessenich4d65ee32016-03-12 18:17:47 -07002238 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002239 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002240 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002241}
2242
2243// Make all the functions, skeletally, without actually visiting their bodies.
2244void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2245{
2246 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2247 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2248 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2249 continue;
2250
2251 // We're on a user function. Set up the basic interface for the function now,
2252 // so that it's available to call.
2253 // Translating the body will happen later.
2254 //
qining25262b32016-05-06 17:25:16 -04002255 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002256 // function. What it is an address of varies:
2257 //
2258 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2259 // so that write needs to be to a copy, hence the address of a copy works.
2260 //
2261 // - "const in" parameters can just be the r-value, as no writes need occur.
2262 //
2263 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2264 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2265
2266 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002267 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002268 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2269
2270 for (int p = 0; p < (int)parameters.size(); ++p) {
2271 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2272 spv::Id typeId = convertGlslangToSpvType(paramType);
2273 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2274 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2275 else
2276 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002277 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002278 paramTypes.push_back(typeId);
2279 }
2280
2281 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002282 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2283 convertGlslangToSpvType(glslFunction->getType()),
2284 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002285
2286 // Track function to emit/call later
2287 functionMap[glslFunction->getName().c_str()] = function;
2288
2289 // Set the parameter id's
2290 for (int p = 0; p < (int)parameters.size(); ++p) {
2291 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2292 // give a name too
2293 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2294 }
2295 }
2296}
2297
2298// Process all the initializers, while skipping the functions and link objects
2299void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2300{
2301 builder.setBuildPoint(shaderEntry->getLastBlock());
2302 for (int i = 0; i < (int)initializers.size(); ++i) {
2303 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2304 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2305
2306 // We're on a top-level node that's not a function. Treat as an initializer, whose
2307 // code goes into the beginning of main.
2308 initializer->traverse(this);
2309 }
2310 }
2311}
2312
2313// Process all the functions, while skipping initializers.
2314void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2315{
2316 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2317 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2318 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2319 node->traverse(this);
2320 }
2321}
2322
2323void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2324{
qining25262b32016-05-06 17:25:16 -04002325 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002326 // that called makeFunctions().
2327 spv::Function* function = functionMap[node->getName().c_str()];
2328 spv::Block* functionBlock = function->getEntryBlock();
2329 builder.setBuildPoint(functionBlock);
2330}
2331
Rex Xu04db3f52015-09-16 11:44:02 +08002332void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002333{
Rex Xufc618912015-09-09 16:42:49 +08002334 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002335
2336 glslang::TSampler sampler = {};
2337 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002338 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002339 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2340 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2341 }
2342
John Kessenich140f3df2015-06-26 16:58:36 -06002343 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2344 builder.clearAccessChain();
2345 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002346
2347 // Special case l-value operands
2348 bool lvalue = false;
2349 switch (node.getOp()) {
2350 case glslang::EOpImageAtomicAdd:
2351 case glslang::EOpImageAtomicMin:
2352 case glslang::EOpImageAtomicMax:
2353 case glslang::EOpImageAtomicAnd:
2354 case glslang::EOpImageAtomicOr:
2355 case glslang::EOpImageAtomicXor:
2356 case glslang::EOpImageAtomicExchange:
2357 case glslang::EOpImageAtomicCompSwap:
2358 if (i == 0)
2359 lvalue = true;
2360 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002361 case glslang::EOpSparseImageLoad:
2362 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2363 lvalue = true;
2364 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002365 case glslang::EOpSparseTexture:
2366 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2367 lvalue = true;
2368 break;
2369 case glslang::EOpSparseTextureClamp:
2370 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2371 lvalue = true;
2372 break;
2373 case glslang::EOpSparseTextureLod:
2374 case glslang::EOpSparseTextureOffset:
2375 if (i == 3)
2376 lvalue = true;
2377 break;
2378 case glslang::EOpSparseTextureFetch:
2379 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2380 lvalue = true;
2381 break;
2382 case glslang::EOpSparseTextureFetchOffset:
2383 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2384 lvalue = true;
2385 break;
2386 case glslang::EOpSparseTextureLodOffset:
2387 case glslang::EOpSparseTextureGrad:
2388 case glslang::EOpSparseTextureOffsetClamp:
2389 if (i == 4)
2390 lvalue = true;
2391 break;
2392 case glslang::EOpSparseTextureGradOffset:
2393 case glslang::EOpSparseTextureGradClamp:
2394 if (i == 5)
2395 lvalue = true;
2396 break;
2397 case glslang::EOpSparseTextureGradOffsetClamp:
2398 if (i == 6)
2399 lvalue = true;
2400 break;
2401 case glslang::EOpSparseTextureGather:
2402 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2403 lvalue = true;
2404 break;
2405 case glslang::EOpSparseTextureGatherOffset:
2406 case glslang::EOpSparseTextureGatherOffsets:
2407 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2408 lvalue = true;
2409 break;
Rex Xufc618912015-09-09 16:42:49 +08002410 default:
2411 break;
2412 }
2413
Rex Xu6b86d492015-09-16 17:48:22 +08002414 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002415 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002416 else
John Kessenich32cfd492016-02-02 12:37:46 -07002417 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002418 }
2419}
2420
John Kessenichfc51d282015-08-19 13:34:18 -06002421void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002422{
John Kessenichfc51d282015-08-19 13:34:18 -06002423 builder.clearAccessChain();
2424 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002425 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002426}
John Kessenich140f3df2015-06-26 16:58:36 -06002427
John Kessenichfc51d282015-08-19 13:34:18 -06002428spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2429{
Rex Xufc618912015-09-09 16:42:49 +08002430 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002431 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002432 }
2433
John Kessenichfc51d282015-08-19 13:34:18 -06002434 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002435 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2436 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2437 std::vector<spv::Id> arguments;
2438 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002439 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002440 else
2441 translateArguments(*node->getAsUnaryNode(), arguments);
2442 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2443
2444 spv::Builder::TextureParameters params = { };
2445 params.sampler = arguments[0];
2446
Rex Xu04db3f52015-09-16 11:44:02 +08002447 glslang::TCrackedTextureOp cracked;
2448 node->crackTexture(sampler, cracked);
2449
John Kessenichfc51d282015-08-19 13:34:18 -06002450 // Check for queries
2451 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002452 // a sampled image needs to have the image extracted first
2453 if (builder.isSampledImage(params.sampler))
2454 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002455 switch (node->getOp()) {
2456 case glslang::EOpImageQuerySize:
2457 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002458 if (arguments.size() > 1) {
2459 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002460 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002461 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002462 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002463 case glslang::EOpImageQuerySamples:
2464 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002465 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002466 case glslang::EOpTextureQueryLod:
2467 params.coords = arguments[1];
2468 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2469 case glslang::EOpTextureQueryLevels:
2470 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002471 case glslang::EOpSparseTexelsResident:
2472 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002473 default:
2474 assert(0);
2475 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002476 }
John Kessenich140f3df2015-06-26 16:58:36 -06002477 }
2478
Rex Xufc618912015-09-09 16:42:49 +08002479 // Check for image functions other than queries
2480 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002481 std::vector<spv::Id> operands;
2482 auto opIt = arguments.begin();
2483 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002484
2485 // Handle subpass operations
2486 // TODO: GLSL should change to have the "MS" only on the type rather than the
2487 // built-in function.
2488 if (cracked.subpass) {
2489 // add on the (0,0) coordinate
2490 spv::Id zero = builder.makeIntConstant(0);
2491 std::vector<spv::Id> comps;
2492 comps.push_back(zero);
2493 comps.push_back(zero);
2494 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2495 if (sampler.ms) {
2496 operands.push_back(spv::ImageOperandsSampleMask);
2497 operands.push_back(*(opIt++));
2498 }
2499 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2500 }
2501
John Kessenich56bab042015-09-16 10:54:31 -06002502 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002503 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002504 if (sampler.ms) {
2505 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002506 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002507 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002508 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2509 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002510 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002511 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002512 if (sampler.ms) {
2513 operands.push_back(*(opIt + 1));
2514 operands.push_back(spv::ImageOperandsSampleMask);
2515 operands.push_back(*opIt);
2516 } else
2517 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002518 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002519 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2520 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002521 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002522 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2523 builder.addCapability(spv::CapabilitySparseResidency);
2524 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2525 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2526
2527 if (sampler.ms) {
2528 operands.push_back(spv::ImageOperandsSampleMask);
2529 operands.push_back(*opIt++);
2530 }
2531
2532 // Create the return type that was a special structure
2533 spv::Id texelOut = *opIt;
2534 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2535 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2536 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2537
2538 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2539
2540 // Decode the return type
2541 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2542 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002543 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002544 // Process image atomic operations
2545
2546 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2547 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002548 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002549
Rex Xufc618912015-09-09 16:42:49 +08002550 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002551 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002552
2553 std::vector<spv::Id> operands;
2554 operands.push_back(pointer);
2555 for (; opIt != arguments.end(); ++opIt)
2556 operands.push_back(*opIt);
2557
Rex Xu04db3f52015-09-16 11:44:02 +08002558 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002559 }
2560 }
2561
2562 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002563 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002564 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2565
John Kessenichfc51d282015-08-19 13:34:18 -06002566 // check for bias argument
2567 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002568 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002569 int nonBiasArgCount = 2;
2570 if (cracked.offset)
2571 ++nonBiasArgCount;
2572 if (cracked.grad)
2573 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002574 if (cracked.lodClamp)
2575 ++nonBiasArgCount;
2576 if (sparse)
2577 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002578
2579 if ((int)arguments.size() > nonBiasArgCount)
2580 bias = true;
2581 }
2582
John Kessenicha5c33d62016-06-02 23:45:21 -06002583 // See if the sampler param should really be just the SPV image part
2584 if (cracked.fetch) {
2585 // a fetch needs to have the image extracted first
2586 if (builder.isSampledImage(params.sampler))
2587 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2588 }
2589
John Kessenichfc51d282015-08-19 13:34:18 -06002590 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002591
John Kessenichfc51d282015-08-19 13:34:18 -06002592 params.coords = arguments[1];
2593 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002594 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002595
2596 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002597 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002598 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002599 ++extraArgs;
2600 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002601 params.Dref = arguments[2];
2602 ++extraArgs;
2603 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002604 std::vector<spv::Id> indexes;
2605 int comp;
2606 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002607 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002608 else
2609 comp = builder.getNumComponents(params.coords) - 1;
2610 indexes.push_back(comp);
2611 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2612 }
2613 if (cracked.lod) {
2614 params.lod = arguments[2];
2615 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002616 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2617 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2618 noImplicitLod = true;
2619 }
2620 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002621 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002622 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002623 }
2624 if (cracked.grad) {
2625 params.gradX = arguments[2 + extraArgs];
2626 params.gradY = arguments[3 + extraArgs];
2627 extraArgs += 2;
2628 }
John Kessenich55e7d112015-11-15 21:33:39 -07002629 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002630 params.offset = arguments[2 + extraArgs];
2631 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002632 } else if (cracked.offsets) {
2633 params.offsets = arguments[2 + extraArgs];
2634 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002635 }
Rex Xu48edadf2015-12-31 16:11:41 +08002636 if (cracked.lodClamp) {
2637 params.lodClamp = arguments[2 + extraArgs];
2638 ++extraArgs;
2639 }
2640 if (sparse) {
2641 params.texelOut = arguments[2 + extraArgs];
2642 ++extraArgs;
2643 }
John Kessenichfc51d282015-08-19 13:34:18 -06002644 if (bias) {
2645 params.bias = arguments[2 + extraArgs];
2646 ++extraArgs;
2647 }
John Kessenich55e7d112015-11-15 21:33:39 -07002648 if (cracked.gather && ! sampler.shadow) {
2649 // default component is 0, if missing, otherwise an argument
2650 if (2 + extraArgs < (int)arguments.size()) {
2651 params.comp = arguments[2 + extraArgs];
2652 ++extraArgs;
2653 } else {
2654 params.comp = builder.makeIntConstant(0);
2655 }
2656 }
John Kessenichfc51d282015-08-19 13:34:18 -06002657
John Kessenich019f08f2016-02-15 15:40:42 -07002658 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002659}
2660
2661spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2662{
2663 // Grab the function's pointer from the previously created function
2664 spv::Function* function = functionMap[node->getName().c_str()];
2665 if (! function)
2666 return 0;
2667
2668 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2669 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2670
2671 // See comments in makeFunctions() for details about the semantics for parameter passing.
2672 //
2673 // These imply we need a four step process:
2674 // 1. Evaluate the arguments
2675 // 2. Allocate and make copies of in, out, and inout arguments
2676 // 3. Make the call
2677 // 4. Copy back the results
2678
2679 // 1. Evaluate the arguments
2680 std::vector<spv::Builder::AccessChain> lValues;
2681 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002682 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002683 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002684 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002685 // build l-value
2686 builder.clearAccessChain();
2687 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002688 argTypes.push_back(&paramType);
2689 // keep outputs as and samplers l-values, evaluate input-only as r-values
2690 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.getBasicType() == glslang::EbtSampler) {
John Kessenich140f3df2015-06-26 16:58:36 -06002691 // save l-value
2692 lValues.push_back(builder.getAccessChain());
2693 } else {
2694 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002695 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002696 }
2697 }
2698
2699 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2700 // copy the original into that space.
2701 //
2702 // Also, build up the list of actual arguments to pass in for the call
2703 int lValueCount = 0;
2704 int rValueCount = 0;
2705 std::vector<spv::Id> spvArgs;
2706 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002707 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002708 spv::Id arg;
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002709 if (paramType.getBasicType() == glslang::EbtSampler) {
2710 builder.setAccessChain(lValues[lValueCount]);
2711 arg = builder.accessChainGetLValue();
2712 ++lValueCount;
2713 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002714 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002715 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2716 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2717 // need to copy the input into output space
2718 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002719 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002720 builder.createStore(copy, arg);
2721 }
2722 ++lValueCount;
2723 } else {
2724 arg = rValues[rValueCount];
2725 ++rValueCount;
2726 }
2727 spvArgs.push_back(arg);
2728 }
2729
2730 // 3. Make the call.
2731 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002732 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002733
2734 // 4. Copy back out an "out" arguments.
2735 lValueCount = 0;
2736 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2737 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2738 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2739 spv::Id copy = builder.createLoad(spvArgs[a]);
2740 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002741 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002742 }
2743 ++lValueCount;
2744 }
2745 }
2746
2747 return result;
2748}
2749
2750// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002751spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2752 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002753 spv::Id typeId, spv::Id left, spv::Id right,
2754 glslang::TBasicType typeProxy, bool reduceComparison)
2755{
Rex Xu8ff43de2016-04-22 16:51:45 +08002756 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002757 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002758 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002759
2760 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002761 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002762 bool comparison = false;
2763
2764 switch (op) {
2765 case glslang::EOpAdd:
2766 case glslang::EOpAddAssign:
2767 if (isFloat)
2768 binOp = spv::OpFAdd;
2769 else
2770 binOp = spv::OpIAdd;
2771 break;
2772 case glslang::EOpSub:
2773 case glslang::EOpSubAssign:
2774 if (isFloat)
2775 binOp = spv::OpFSub;
2776 else
2777 binOp = spv::OpISub;
2778 break;
2779 case glslang::EOpMul:
2780 case glslang::EOpMulAssign:
2781 if (isFloat)
2782 binOp = spv::OpFMul;
2783 else
2784 binOp = spv::OpIMul;
2785 break;
2786 case glslang::EOpVectorTimesScalar:
2787 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002788 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002789 if (builder.isVector(right))
2790 std::swap(left, right);
2791 assert(builder.isScalar(right));
2792 needMatchingVectors = false;
2793 binOp = spv::OpVectorTimesScalar;
2794 } else
2795 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002796 break;
2797 case glslang::EOpVectorTimesMatrix:
2798 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002799 binOp = spv::OpVectorTimesMatrix;
2800 break;
2801 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002802 binOp = spv::OpMatrixTimesVector;
2803 break;
2804 case glslang::EOpMatrixTimesScalar:
2805 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002806 binOp = spv::OpMatrixTimesScalar;
2807 break;
2808 case glslang::EOpMatrixTimesMatrix:
2809 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002810 binOp = spv::OpMatrixTimesMatrix;
2811 break;
2812 case glslang::EOpOuterProduct:
2813 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002814 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002815 break;
2816
2817 case glslang::EOpDiv:
2818 case glslang::EOpDivAssign:
2819 if (isFloat)
2820 binOp = spv::OpFDiv;
2821 else if (isUnsigned)
2822 binOp = spv::OpUDiv;
2823 else
2824 binOp = spv::OpSDiv;
2825 break;
2826 case glslang::EOpMod:
2827 case glslang::EOpModAssign:
2828 if (isFloat)
2829 binOp = spv::OpFMod;
2830 else if (isUnsigned)
2831 binOp = spv::OpUMod;
2832 else
2833 binOp = spv::OpSMod;
2834 break;
2835 case glslang::EOpRightShift:
2836 case glslang::EOpRightShiftAssign:
2837 if (isUnsigned)
2838 binOp = spv::OpShiftRightLogical;
2839 else
2840 binOp = spv::OpShiftRightArithmetic;
2841 break;
2842 case glslang::EOpLeftShift:
2843 case glslang::EOpLeftShiftAssign:
2844 binOp = spv::OpShiftLeftLogical;
2845 break;
2846 case glslang::EOpAnd:
2847 case glslang::EOpAndAssign:
2848 binOp = spv::OpBitwiseAnd;
2849 break;
2850 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002851 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002852 binOp = spv::OpLogicalAnd;
2853 break;
2854 case glslang::EOpInclusiveOr:
2855 case glslang::EOpInclusiveOrAssign:
2856 binOp = spv::OpBitwiseOr;
2857 break;
2858 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002859 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002860 binOp = spv::OpLogicalOr;
2861 break;
2862 case glslang::EOpExclusiveOr:
2863 case glslang::EOpExclusiveOrAssign:
2864 binOp = spv::OpBitwiseXor;
2865 break;
2866 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002867 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002868 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002869 break;
2870
2871 case glslang::EOpLessThan:
2872 case glslang::EOpGreaterThan:
2873 case glslang::EOpLessThanEqual:
2874 case glslang::EOpGreaterThanEqual:
2875 case glslang::EOpEqual:
2876 case glslang::EOpNotEqual:
2877 case glslang::EOpVectorEqual:
2878 case glslang::EOpVectorNotEqual:
2879 comparison = true;
2880 break;
2881 default:
2882 break;
2883 }
2884
John Kessenich7c1aa102015-10-15 13:29:11 -06002885 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002886 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002887 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002888 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002889 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002890
2891 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002892 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002893 builder.promoteScalar(precision, left, right);
2894
qining25262b32016-05-06 17:25:16 -04002895 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2896 addDecoration(result, noContraction);
2897 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002898 }
2899
2900 if (! comparison)
2901 return 0;
2902
John Kessenich7c1aa102015-10-15 13:29:11 -06002903 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002904
2905 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2906 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2907
John Kessenich22118352015-12-21 20:54:09 -07002908 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002909 }
2910
2911 switch (op) {
2912 case glslang::EOpLessThan:
2913 if (isFloat)
2914 binOp = spv::OpFOrdLessThan;
2915 else if (isUnsigned)
2916 binOp = spv::OpULessThan;
2917 else
2918 binOp = spv::OpSLessThan;
2919 break;
2920 case glslang::EOpGreaterThan:
2921 if (isFloat)
2922 binOp = spv::OpFOrdGreaterThan;
2923 else if (isUnsigned)
2924 binOp = spv::OpUGreaterThan;
2925 else
2926 binOp = spv::OpSGreaterThan;
2927 break;
2928 case glslang::EOpLessThanEqual:
2929 if (isFloat)
2930 binOp = spv::OpFOrdLessThanEqual;
2931 else if (isUnsigned)
2932 binOp = spv::OpULessThanEqual;
2933 else
2934 binOp = spv::OpSLessThanEqual;
2935 break;
2936 case glslang::EOpGreaterThanEqual:
2937 if (isFloat)
2938 binOp = spv::OpFOrdGreaterThanEqual;
2939 else if (isUnsigned)
2940 binOp = spv::OpUGreaterThanEqual;
2941 else
2942 binOp = spv::OpSGreaterThanEqual;
2943 break;
2944 case glslang::EOpEqual:
2945 case glslang::EOpVectorEqual:
2946 if (isFloat)
2947 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002948 else if (isBool)
2949 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002950 else
2951 binOp = spv::OpIEqual;
2952 break;
2953 case glslang::EOpNotEqual:
2954 case glslang::EOpVectorNotEqual:
2955 if (isFloat)
2956 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002957 else if (isBool)
2958 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002959 else
2960 binOp = spv::OpINotEqual;
2961 break;
2962 default:
2963 break;
2964 }
2965
qining25262b32016-05-06 17:25:16 -04002966 if (binOp != spv::OpNop) {
2967 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2968 addDecoration(result, noContraction);
2969 return builder.setPrecision(result, precision);
2970 }
John Kessenich140f3df2015-06-26 16:58:36 -06002971
2972 return 0;
2973}
2974
John Kessenich04bb8a02015-12-12 12:28:14 -07002975//
2976// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2977// These can be any of:
2978//
2979// matrix * scalar
2980// scalar * matrix
2981// matrix * matrix linear algebraic
2982// matrix * vector
2983// vector * matrix
2984// matrix * matrix componentwise
2985// matrix op matrix op in {+, -, /}
2986// matrix op scalar op in {+, -, /}
2987// scalar op matrix op in {+, -, /}
2988//
qining25262b32016-05-06 17:25:16 -04002989spv::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 -07002990{
2991 bool firstClass = true;
2992
2993 // First, handle first-class matrix operations (* and matrix/scalar)
2994 switch (op) {
2995 case spv::OpFDiv:
2996 if (builder.isMatrix(left) && builder.isScalar(right)) {
2997 // turn matrix / scalar into a multiply...
2998 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2999 op = spv::OpMatrixTimesScalar;
3000 } else
3001 firstClass = false;
3002 break;
3003 case spv::OpMatrixTimesScalar:
3004 if (builder.isMatrix(right))
3005 std::swap(left, right);
3006 assert(builder.isScalar(right));
3007 break;
3008 case spv::OpVectorTimesMatrix:
3009 assert(builder.isVector(left));
3010 assert(builder.isMatrix(right));
3011 break;
3012 case spv::OpMatrixTimesVector:
3013 assert(builder.isMatrix(left));
3014 assert(builder.isVector(right));
3015 break;
3016 case spv::OpMatrixTimesMatrix:
3017 assert(builder.isMatrix(left));
3018 assert(builder.isMatrix(right));
3019 break;
3020 default:
3021 firstClass = false;
3022 break;
3023 }
3024
qining25262b32016-05-06 17:25:16 -04003025 if (firstClass) {
3026 spv::Id result = builder.createBinOp(op, typeId, left, right);
3027 addDecoration(result, noContraction);
3028 return builder.setPrecision(result, precision);
3029 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003030
3031 // Handle component-wise +, -, *, and / for all combinations of type.
3032 // The result type of all of them is the same type as the (a) matrix operand.
3033 // The algorithm is to:
3034 // - break the matrix(es) into vectors
3035 // - smear any scalar to a vector
3036 // - do vector operations
3037 // - make a matrix out the vector results
3038 switch (op) {
3039 case spv::OpFAdd:
3040 case spv::OpFSub:
3041 case spv::OpFDiv:
3042 case spv::OpFMul:
3043 {
3044 // one time set up...
3045 bool leftMat = builder.isMatrix(left);
3046 bool rightMat = builder.isMatrix(right);
3047 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3048 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3049 spv::Id scalarType = builder.getScalarTypeId(typeId);
3050 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3051 std::vector<spv::Id> results;
3052 spv::Id smearVec = spv::NoResult;
3053 if (builder.isScalar(left))
3054 smearVec = builder.smearScalar(precision, left, vecType);
3055 else if (builder.isScalar(right))
3056 smearVec = builder.smearScalar(precision, right, vecType);
3057
3058 // do each vector op
3059 for (unsigned int c = 0; c < numCols; ++c) {
3060 std::vector<unsigned int> indexes;
3061 indexes.push_back(c);
3062 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3063 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003064 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3065 addDecoration(result, noContraction);
3066 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003067 }
3068
3069 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003070 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003071 }
3072 default:
3073 assert(0);
3074 return spv::NoResult;
3075 }
3076}
3077
qining25262b32016-05-06 17:25:16 -04003078spv::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 -06003079{
3080 spv::Op unaryOp = spv::OpNop;
3081 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003082 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003083 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003084
3085 switch (op) {
3086 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003087 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003088 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003089 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003090 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003091 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003092 unaryOp = spv::OpSNegate;
3093 break;
3094
3095 case glslang::EOpLogicalNot:
3096 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003097 unaryOp = spv::OpLogicalNot;
3098 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003099 case glslang::EOpBitwiseNot:
3100 unaryOp = spv::OpNot;
3101 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003102
John Kessenich140f3df2015-06-26 16:58:36 -06003103 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003104 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003105 break;
3106 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003107 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003108 break;
3109 case glslang::EOpTranspose:
3110 unaryOp = spv::OpTranspose;
3111 break;
3112
3113 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003114 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003115 break;
3116 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003118 break;
3119 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003135 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003136 break;
3137
3138 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003139 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003140 break;
3141 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003142 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003143 break;
3144 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003145 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003146 break;
3147 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003148 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003149 break;
3150 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003151 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003152 break;
3153 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003154 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003155 break;
3156
3157 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003161 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003162 break;
3163
3164 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003168 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003171 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003172 break;
3173 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003174 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003175 break;
3176 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003177 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003178 break;
3179 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003180 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003181 break;
3182
3183 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003184 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003185 break;
3186 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003187 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003188 break;
3189 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
3195 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003196 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003197 break;
3198 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003200 break;
3201
3202 case glslang::EOpIsNan:
3203 unaryOp = spv::OpIsNan;
3204 break;
3205 case glslang::EOpIsInf:
3206 unaryOp = spv::OpIsInf;
3207 break;
3208
Rex Xucbc426e2015-12-15 16:03:10 +08003209 case glslang::EOpFloatBitsToInt:
3210 case glslang::EOpFloatBitsToUint:
3211 case glslang::EOpIntBitsToFloat:
3212 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003213 case glslang::EOpDoubleBitsToInt64:
3214 case glslang::EOpDoubleBitsToUint64:
3215 case glslang::EOpInt64BitsToDouble:
3216 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003217 unaryOp = spv::OpBitcast;
3218 break;
3219
John Kessenich140f3df2015-06-26 16:58:36 -06003220 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003221 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 break;
3223 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003224 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003225 break;
3226 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003227 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003228 break;
3229 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003230 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003231 break;
3232 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003233 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003234 break;
3235 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003236 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003237 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003238 case glslang::EOpPackSnorm4x8:
3239 libCall = spv::GLSLstd450PackSnorm4x8;
3240 break;
3241 case glslang::EOpUnpackSnorm4x8:
3242 libCall = spv::GLSLstd450UnpackSnorm4x8;
3243 break;
3244 case glslang::EOpPackUnorm4x8:
3245 libCall = spv::GLSLstd450PackUnorm4x8;
3246 break;
3247 case glslang::EOpUnpackUnorm4x8:
3248 libCall = spv::GLSLstd450UnpackUnorm4x8;
3249 break;
3250 case glslang::EOpPackDouble2x32:
3251 libCall = spv::GLSLstd450PackDouble2x32;
3252 break;
3253 case glslang::EOpUnpackDouble2x32:
3254 libCall = spv::GLSLstd450UnpackDouble2x32;
3255 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003256
Rex Xu8ff43de2016-04-22 16:51:45 +08003257 case glslang::EOpPackInt2x32:
3258 case glslang::EOpUnpackInt2x32:
3259 case glslang::EOpPackUint2x32:
3260 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003261 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003262 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3263 break;
3264
John Kessenich140f3df2015-06-26 16:58:36 -06003265 case glslang::EOpDPdx:
3266 unaryOp = spv::OpDPdx;
3267 break;
3268 case glslang::EOpDPdy:
3269 unaryOp = spv::OpDPdy;
3270 break;
3271 case glslang::EOpFwidth:
3272 unaryOp = spv::OpFwidth;
3273 break;
3274 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003275 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003276 unaryOp = spv::OpDPdxFine;
3277 break;
3278 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003279 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003280 unaryOp = spv::OpDPdyFine;
3281 break;
3282 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003283 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003284 unaryOp = spv::OpFwidthFine;
3285 break;
3286 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003287 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003288 unaryOp = spv::OpDPdxCoarse;
3289 break;
3290 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003291 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003292 unaryOp = spv::OpDPdyCoarse;
3293 break;
3294 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003295 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003296 unaryOp = spv::OpFwidthCoarse;
3297 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003298 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003299 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003300 libCall = spv::GLSLstd450InterpolateAtCentroid;
3301 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003302 case glslang::EOpAny:
3303 unaryOp = spv::OpAny;
3304 break;
3305 case glslang::EOpAll:
3306 unaryOp = spv::OpAll;
3307 break;
3308
3309 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003310 if (isFloat)
3311 libCall = spv::GLSLstd450FAbs;
3312 else
3313 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 if (isFloat)
3317 libCall = spv::GLSLstd450FSign;
3318 else
3319 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321
John Kessenichfc51d282015-08-19 13:34:18 -06003322 case glslang::EOpAtomicCounterIncrement:
3323 case glslang::EOpAtomicCounterDecrement:
3324 case glslang::EOpAtomicCounter:
3325 {
3326 // Handle all of the atomics in one place, in createAtomicOperation()
3327 std::vector<spv::Id> operands;
3328 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003329 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003330 }
3331
John Kessenichfc51d282015-08-19 13:34:18 -06003332 case glslang::EOpBitFieldReverse:
3333 unaryOp = spv::OpBitReverse;
3334 break;
3335 case glslang::EOpBitCount:
3336 unaryOp = spv::OpBitCount;
3337 break;
3338 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003339 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003340 break;
3341 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003342 if (isUnsigned)
3343 libCall = spv::GLSLstd450FindUMsb;
3344 else
3345 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003346 break;
3347
Rex Xu574ab042016-04-14 16:53:07 +08003348 case glslang::EOpBallot:
3349 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003350 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003351 libCall = spv::GLSLstd450Bad;
3352 break;
3353
Rex Xu338b1852016-05-05 20:38:33 +08003354 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003355 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003356 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003357 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003358
John Kessenich140f3df2015-06-26 16:58:36 -06003359 default:
3360 return 0;
3361 }
3362
3363 spv::Id id;
3364 if (libCall >= 0) {
3365 std::vector<spv::Id> args;
3366 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003367 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003368 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003369 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003370 }
John Kessenich140f3df2015-06-26 16:58:36 -06003371
qining25262b32016-05-06 17:25:16 -04003372 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003373 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003374}
3375
John Kessenich7a53f762016-01-20 11:19:27 -07003376// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003377spv::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 -07003378{
3379 // Handle unary operations vector by vector.
3380 // The result type is the same type as the original type.
3381 // The algorithm is to:
3382 // - break the matrix into vectors
3383 // - apply the operation to each vector
3384 // - make a matrix out the vector results
3385
3386 // get the types sorted out
3387 int numCols = builder.getNumColumns(operand);
3388 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003389 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3390 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003391 std::vector<spv::Id> results;
3392
3393 // do each vector op
3394 for (int c = 0; c < numCols; ++c) {
3395 std::vector<unsigned int> indexes;
3396 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003397 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3398 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3399 addDecoration(destVec, noContraction);
3400 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003401 }
3402
3403 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003404 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003405}
3406
Rex Xu73e3ce72016-04-27 18:48:17 +08003407spv::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 -06003408{
3409 spv::Op convOp = spv::OpNop;
3410 spv::Id zero = 0;
3411 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003412 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003413
3414 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3415
3416 switch (op) {
3417 case glslang::EOpConvIntToBool:
3418 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003419 case glslang::EOpConvInt64ToBool:
3420 case glslang::EOpConvUint64ToBool:
3421 zero = (op == glslang::EOpConvInt64ToBool ||
3422 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003423 zero = makeSmearedConstant(zero, vectorSize);
3424 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3425
3426 case glslang::EOpConvFloatToBool:
3427 zero = builder.makeFloatConstant(0.0F);
3428 zero = makeSmearedConstant(zero, vectorSize);
3429 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3430
3431 case glslang::EOpConvDoubleToBool:
3432 zero = builder.makeDoubleConstant(0.0);
3433 zero = makeSmearedConstant(zero, vectorSize);
3434 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3435
3436 case glslang::EOpConvBoolToFloat:
3437 convOp = spv::OpSelect;
3438 zero = builder.makeFloatConstant(0.0);
3439 one = builder.makeFloatConstant(1.0);
3440 break;
3441 case glslang::EOpConvBoolToDouble:
3442 convOp = spv::OpSelect;
3443 zero = builder.makeDoubleConstant(0.0);
3444 one = builder.makeDoubleConstant(1.0);
3445 break;
3446 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003447 case glslang::EOpConvBoolToInt64:
3448 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3449 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003450 convOp = spv::OpSelect;
3451 break;
3452 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003453 case glslang::EOpConvBoolToUint64:
3454 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3455 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003456 convOp = spv::OpSelect;
3457 break;
3458
3459 case glslang::EOpConvIntToFloat:
3460 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003461 case glslang::EOpConvInt64ToFloat:
3462 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003463 convOp = spv::OpConvertSToF;
3464 break;
3465
3466 case glslang::EOpConvUintToFloat:
3467 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003468 case glslang::EOpConvUint64ToFloat:
3469 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003470 convOp = spv::OpConvertUToF;
3471 break;
3472
3473 case glslang::EOpConvDoubleToFloat:
3474 case glslang::EOpConvFloatToDouble:
3475 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003476 if (builder.isMatrixType(destType))
3477 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003478 break;
3479
3480 case glslang::EOpConvFloatToInt:
3481 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003482 case glslang::EOpConvFloatToInt64:
3483 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003484 convOp = spv::OpConvertFToS;
3485 break;
3486
3487 case glslang::EOpConvUintToInt:
3488 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003489 case glslang::EOpConvUint64ToInt64:
3490 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003491 if (builder.isInSpecConstCodeGenMode()) {
3492 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003493 zero = (op == glslang::EOpConvUintToInt64 ||
3494 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003495 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003496 // Use OpIAdd, instead of OpBitcast to do the conversion when
3497 // generating for OpSpecConstantOp instruction.
3498 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3499 }
3500 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003501 convOp = spv::OpBitcast;
3502 break;
3503
3504 case glslang::EOpConvFloatToUint:
3505 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003506 case glslang::EOpConvFloatToUint64:
3507 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003508 convOp = spv::OpConvertFToU;
3509 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003510
3511 case glslang::EOpConvIntToInt64:
3512 case glslang::EOpConvInt64ToInt:
3513 convOp = spv::OpSConvert;
3514 break;
3515
3516 case glslang::EOpConvUintToUint64:
3517 case glslang::EOpConvUint64ToUint:
3518 convOp = spv::OpUConvert;
3519 break;
3520
3521 case glslang::EOpConvIntToUint64:
3522 case glslang::EOpConvInt64ToUint:
3523 case glslang::EOpConvUint64ToInt:
3524 case glslang::EOpConvUintToInt64:
3525 // OpSConvert/OpUConvert + OpBitCast
3526 switch (op) {
3527 case glslang::EOpConvIntToUint64:
3528 convOp = spv::OpSConvert;
3529 type = builder.makeIntType(64);
3530 break;
3531 case glslang::EOpConvInt64ToUint:
3532 convOp = spv::OpSConvert;
3533 type = builder.makeIntType(32);
3534 break;
3535 case glslang::EOpConvUint64ToInt:
3536 convOp = spv::OpUConvert;
3537 type = builder.makeUintType(32);
3538 break;
3539 case glslang::EOpConvUintToInt64:
3540 convOp = spv::OpUConvert;
3541 type = builder.makeUintType(64);
3542 break;
3543 default:
3544 assert(0);
3545 break;
3546 }
3547
3548 if (vectorSize > 0)
3549 type = builder.makeVectorType(type, vectorSize);
3550
3551 operand = builder.createUnaryOp(convOp, type, operand);
3552
3553 if (builder.isInSpecConstCodeGenMode()) {
3554 // Build zero scalar or vector for OpIAdd.
3555 zero = (op == glslang::EOpConvIntToUint64 ||
3556 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3557 zero = makeSmearedConstant(zero, vectorSize);
3558 // Use OpIAdd, instead of OpBitcast to do the conversion when
3559 // generating for OpSpecConstantOp instruction.
3560 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3561 }
3562 // For normal run-time conversion instruction, use OpBitcast.
3563 convOp = spv::OpBitcast;
3564 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003565 default:
3566 break;
3567 }
3568
3569 spv::Id result = 0;
3570 if (convOp == spv::OpNop)
3571 return result;
3572
3573 if (convOp == spv::OpSelect) {
3574 zero = makeSmearedConstant(zero, vectorSize);
3575 one = makeSmearedConstant(one, vectorSize);
3576 result = builder.createTriOp(convOp, destType, operand, one, zero);
3577 } else
3578 result = builder.createUnaryOp(convOp, destType, operand);
3579
John Kessenich32cfd492016-02-02 12:37:46 -07003580 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003581}
3582
3583spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3584{
3585 if (vectorSize == 0)
3586 return constant;
3587
3588 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3589 std::vector<spv::Id> components;
3590 for (int c = 0; c < vectorSize; ++c)
3591 components.push_back(constant);
3592 return builder.makeCompositeConstant(vectorTypeId, components);
3593}
3594
John Kessenich426394d2015-07-23 10:22:48 -06003595// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003596spv::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 -06003597{
3598 spv::Op opCode = spv::OpNop;
3599
3600 switch (op) {
3601 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003602 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003603 opCode = spv::OpAtomicIAdd;
3604 break;
3605 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003606 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003607 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003608 break;
3609 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003610 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003611 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003612 break;
3613 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003614 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003615 opCode = spv::OpAtomicAnd;
3616 break;
3617 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003618 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003619 opCode = spv::OpAtomicOr;
3620 break;
3621 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003622 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003623 opCode = spv::OpAtomicXor;
3624 break;
3625 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003626 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003627 opCode = spv::OpAtomicExchange;
3628 break;
3629 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003630 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003631 opCode = spv::OpAtomicCompareExchange;
3632 break;
3633 case glslang::EOpAtomicCounterIncrement:
3634 opCode = spv::OpAtomicIIncrement;
3635 break;
3636 case glslang::EOpAtomicCounterDecrement:
3637 opCode = spv::OpAtomicIDecrement;
3638 break;
3639 case glslang::EOpAtomicCounter:
3640 opCode = spv::OpAtomicLoad;
3641 break;
3642 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003643 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003644 break;
3645 }
3646
3647 // Sort out the operands
3648 // - mapping from glslang -> SPV
3649 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003650 // - compare-exchange swaps the value and comparator
3651 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003652 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3653 auto opIt = operands.begin(); // walk the glslang operands
3654 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003655 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3656 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3657 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003658 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3659 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003660 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003661 spvAtomicOperands.push_back(*(opIt + 1));
3662 spvAtomicOperands.push_back(*opIt);
3663 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003664 }
John Kessenich426394d2015-07-23 10:22:48 -06003665
John Kessenich3e60a6f2015-09-14 22:45:16 -06003666 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003667 for (; opIt != operands.end(); ++opIt)
3668 spvAtomicOperands.push_back(*opIt);
3669
3670 return builder.createOp(opCode, typeId, spvAtomicOperands);
3671}
3672
John Kessenich91cef522016-05-05 16:45:40 -06003673// Create group invocation operations.
3674spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3675{
3676 builder.addCapability(spv::CapabilityGroups);
3677
3678 std::vector<spv::Id> operands;
3679 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3680 operands.push_back(operand);
3681
3682 switch (op) {
3683 case glslang::EOpAnyInvocation:
3684 case glslang::EOpAllInvocations:
3685 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3686
3687 case glslang::EOpAllInvocationsEqual:
3688 {
3689 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3690 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3691
3692 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3693 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3694 }
3695 default:
3696 logger->missingFunctionality("invocation operation");
3697 return spv::NoResult;
3698 }
3699}
3700
John Kessenich5e4b1242015-08-06 22:53:06 -06003701spv::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 -06003702{
Rex Xu8ff43de2016-04-22 16:51:45 +08003703 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003704 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3705
John Kessenich140f3df2015-06-26 16:58:36 -06003706 spv::Op opCode = spv::OpNop;
3707 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003708 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003709 spv::Id typeId0 = 0;
3710 if (consumedOperands > 0)
3711 typeId0 = builder.getTypeId(operands[0]);
3712 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003713
3714 switch (op) {
3715 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003716 if (isFloat)
3717 libCall = spv::GLSLstd450FMin;
3718 else if (isUnsigned)
3719 libCall = spv::GLSLstd450UMin;
3720 else
3721 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003722 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003723 break;
3724 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 if (isFloat)
3729 libCall = spv::GLSLstd450FMax;
3730 else if (isUnsigned)
3731 libCall = spv::GLSLstd450UMax;
3732 else
3733 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003734 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
3739 case glslang::EOpDot:
3740 opCode = spv::OpDot;
3741 break;
3742 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003743 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
3745
3746 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003747 if (isFloat)
3748 libCall = spv::GLSLstd450FClamp;
3749 else if (isUnsigned)
3750 libCall = spv::GLSLstd450UClamp;
3751 else
3752 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003753 builder.promoteScalar(precision, operands.front(), operands[1]);
3754 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003757 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3758 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003759 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003760 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003761 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003762 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003763 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003764 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003768 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003769 break;
3770 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003772 builder.promoteScalar(precision, operands[0], operands[2]);
3773 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775
3776 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
3779 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003783 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003784 break;
3785 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003787 break;
3788 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003789 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003790 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003791 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003792 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003793 libCall = spv::GLSLstd450InterpolateAtSample;
3794 break;
3795 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003796 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003797 libCall = spv::GLSLstd450InterpolateAtOffset;
3798 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003799 case glslang::EOpAddCarry:
3800 opCode = spv::OpIAddCarry;
3801 typeId = builder.makeStructResultType(typeId0, typeId0);
3802 consumedOperands = 2;
3803 break;
3804 case glslang::EOpSubBorrow:
3805 opCode = spv::OpISubBorrow;
3806 typeId = builder.makeStructResultType(typeId0, typeId0);
3807 consumedOperands = 2;
3808 break;
3809 case glslang::EOpUMulExtended:
3810 opCode = spv::OpUMulExtended;
3811 typeId = builder.makeStructResultType(typeId0, typeId0);
3812 consumedOperands = 2;
3813 break;
3814 case glslang::EOpIMulExtended:
3815 opCode = spv::OpSMulExtended;
3816 typeId = builder.makeStructResultType(typeId0, typeId0);
3817 consumedOperands = 2;
3818 break;
3819 case glslang::EOpBitfieldExtract:
3820 if (isUnsigned)
3821 opCode = spv::OpBitFieldUExtract;
3822 else
3823 opCode = spv::OpBitFieldSExtract;
3824 break;
3825 case glslang::EOpBitfieldInsert:
3826 opCode = spv::OpBitFieldInsert;
3827 break;
3828
3829 case glslang::EOpFma:
3830 libCall = spv::GLSLstd450Fma;
3831 break;
3832 case glslang::EOpFrexp:
3833 libCall = spv::GLSLstd450FrexpStruct;
3834 if (builder.getNumComponents(operands[0]) == 1)
3835 frexpIntType = builder.makeIntegerType(32, true);
3836 else
3837 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3838 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3839 consumedOperands = 1;
3840 break;
3841 case glslang::EOpLdexp:
3842 libCall = spv::GLSLstd450Ldexp;
3843 break;
3844
Rex Xu574ab042016-04-14 16:53:07 +08003845 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003846 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003847 libCall = spv::GLSLstd450Bad;
3848 break;
3849
John Kessenich140f3df2015-06-26 16:58:36 -06003850 default:
3851 return 0;
3852 }
3853
3854 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003855 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003856 // Use an extended instruction from the standard library.
3857 // Construct the call arguments, without modifying the original operands vector.
3858 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3859 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003860 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003861 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003862 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003863 case 0:
3864 // should all be handled by visitAggregate and createNoArgOperation
3865 assert(0);
3866 return 0;
3867 case 1:
3868 // should all be handled by createUnaryOperation
3869 assert(0);
3870 return 0;
3871 case 2:
3872 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3873 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003874 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003875 // anything 3 or over doesn't have l-value operands, so all should be consumed
3876 assert(consumedOperands == operands.size());
3877 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003878 break;
3879 }
3880 }
3881
John Kessenich55e7d112015-11-15 21:33:39 -07003882 // Decode the return types that were structures
3883 switch (op) {
3884 case glslang::EOpAddCarry:
3885 case glslang::EOpSubBorrow:
3886 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3887 id = builder.createCompositeExtract(id, typeId0, 0);
3888 break;
3889 case glslang::EOpUMulExtended:
3890 case glslang::EOpIMulExtended:
3891 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3892 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3893 break;
3894 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003895 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003896 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3897 id = builder.createCompositeExtract(id, typeId0, 0);
3898 break;
3899 default:
3900 break;
3901 }
3902
John Kessenich32cfd492016-02-02 12:37:46 -07003903 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003904}
3905
3906// Intrinsics with no arguments, no return value, and no precision.
3907spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3908{
3909 // TODO: get the barrier operands correct
3910
3911 switch (op) {
3912 case glslang::EOpEmitVertex:
3913 builder.createNoResultOp(spv::OpEmitVertex);
3914 return 0;
3915 case glslang::EOpEndPrimitive:
3916 builder.createNoResultOp(spv::OpEndPrimitive);
3917 return 0;
3918 case glslang::EOpBarrier:
John Kessenich823fc652016-05-19 18:26:42 -06003919 if (glslangIntermediate->getProfile() != EEsProfile)
3920 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich5e4b1242015-08-06 22:53:06 -06003921 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003922 return 0;
3923 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003924 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003925 return 0;
3926 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003927 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003928 return 0;
3929 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003930 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003931 return 0;
3932 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003933 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003934 return 0;
3935 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003936 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003937 return 0;
3938 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003939 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003940 return 0;
3941 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003942 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003943 return 0;
3944 }
3945}
3946
3947spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3948{
John Kessenich2f273362015-07-18 22:34:27 -06003949 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003950 spv::Id id;
3951 if (symbolValues.end() != iter) {
3952 id = iter->second;
3953 return id;
3954 }
3955
3956 // it was not found, create it
3957 id = createSpvVariable(symbol);
3958 symbolValues[symbol->getId()] = id;
3959
3960 if (! symbol->getType().isStruct()) {
3961 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003962 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08003963 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003964 if (symbol->getType().getQualifier().hasSpecConstantId())
3965 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003966 if (symbol->getQualifier().hasIndex())
3967 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3968 if (symbol->getQualifier().hasComponent())
3969 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3970 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003971 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003972 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003973 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003974 if (symbol->getQualifier().hasXfbBuffer())
3975 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3976 if (symbol->getQualifier().hasXfbOffset())
3977 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3978 }
3979 }
3980
scygan2c864272016-05-18 18:09:17 +02003981 if (symbol->getQualifier().hasLocation())
3982 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07003983 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003984 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003985 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003986 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003987 }
John Kessenich140f3df2015-06-26 16:58:36 -06003988 if (symbol->getQualifier().hasSet())
3989 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003990 else if (IsDescriptorResource(symbol->getType())) {
3991 // default to 0
3992 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3993 }
John Kessenich140f3df2015-06-26 16:58:36 -06003994 if (symbol->getQualifier().hasBinding())
3995 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003996 if (symbol->getQualifier().hasAttachment())
3997 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003998 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003999 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004000 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004001 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004002 if (symbol->getQualifier().hasXfbBuffer())
4003 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4004 }
4005
Rex Xu1da878f2016-02-21 20:59:01 +08004006 if (symbol->getType().isImage()) {
4007 std::vector<spv::Decoration> memory;
4008 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4009 for (unsigned int i = 0; i < memory.size(); ++i)
4010 addDecoration(id, memory[i]);
4011 }
4012
John Kessenich140f3df2015-06-26 16:58:36 -06004013 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004014 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06004015 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07004016 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004017
John Kessenich140f3df2015-06-26 16:58:36 -06004018 return id;
4019}
4020
John Kessenich55e7d112015-11-15 21:33:39 -07004021// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004022void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4023{
4024 if (dec != spv::BadValue)
4025 builder.addDecoration(id, dec);
4026}
4027
John Kessenich55e7d112015-11-15 21:33:39 -07004028// If 'dec' is valid, add a one-operand decoration to an object
4029void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4030{
4031 if (dec != spv::BadValue)
4032 builder.addDecoration(id, dec, value);
4033}
4034
4035// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004036void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4037{
4038 if (dec != spv::BadValue)
4039 builder.addMemberDecoration(id, (unsigned)member, dec);
4040}
4041
John Kessenich92187592016-02-01 13:45:25 -07004042// If 'dec' is valid, add a one-operand decoration to a struct member
4043void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4044{
4045 if (dec != spv::BadValue)
4046 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4047}
4048
John Kessenich55e7d112015-11-15 21:33:39 -07004049// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004050// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004051//
4052// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4053//
4054// Recursively walk the nodes. The nodes form a tree whose leaves are
4055// regular constants, which themselves are trees that createSpvConstant()
4056// recursively walks. So, this function walks the "top" of the tree:
4057// - emit specialization constant-building instructions for specConstant
4058// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004059spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004060{
John Kessenich7cc0e282016-03-20 00:46:02 -06004061 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004062
qining4f4bb812016-04-03 23:55:17 -04004063 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004064 if (! node.getQualifier().specConstant) {
4065 // hand off to the non-spec-constant path
4066 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4067 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004068 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004069 nextConst, false);
4070 }
4071
4072 // We now know we have a specialization constant to build
4073
John Kessenichd94c0032016-05-30 19:29:40 -06004074 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004075 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4076 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4077 std::vector<spv::Id> dimConstId;
4078 for (int dim = 0; dim < 3; ++dim) {
4079 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4080 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4081 if (specConst)
4082 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4083 }
4084 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4085 }
4086
4087 // An AST node labelled as specialization constant should be a symbol node.
4088 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4089 if (auto* sn = node.getAsSymbolNode()) {
4090 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004091 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4092 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4093 // will set the builder into spec constant op instruction generating mode.
4094 sub_tree->traverse(this);
4095 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004096 } else if (auto* const_union_array = &sn->getConstArray()){
4097 int nextConst = 0;
4098 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004099 }
4100 }
qining4f4bb812016-04-03 23:55:17 -04004101
4102 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4103 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004104 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004105 exit(1);
4106 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004107}
4108
John Kessenich140f3df2015-06-26 16:58:36 -06004109// Use 'consts' as the flattened glslang source of scalar constants to recursively
4110// build the aggregate SPIR-V constant.
4111//
4112// If there are not enough elements present in 'consts', 0 will be substituted;
4113// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4114//
qining08408382016-03-21 09:51:37 -04004115spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004116{
4117 // vector of constants for SPIR-V
4118 std::vector<spv::Id> spvConsts;
4119
4120 // Type is used for struct and array constants
4121 spv::Id typeId = convertGlslangToSpvType(glslangType);
4122
4123 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004124 glslang::TType elementType(glslangType, 0);
4125 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004126 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004127 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004128 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004129 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004130 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004131 } else if (glslangType.getStruct()) {
4132 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4133 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004134 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004135 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004136 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4137 bool zero = nextConst >= consts.size();
4138 switch (glslangType.getBasicType()) {
4139 case glslang::EbtInt:
4140 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4141 break;
4142 case glslang::EbtUint:
4143 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4144 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004145 case glslang::EbtInt64:
4146 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4147 break;
4148 case glslang::EbtUint64:
4149 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4150 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004151 case glslang::EbtFloat:
4152 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4153 break;
4154 case glslang::EbtDouble:
4155 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4156 break;
4157 case glslang::EbtBool:
4158 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4159 break;
4160 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004161 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004162 break;
4163 }
4164 ++nextConst;
4165 }
4166 } else {
4167 // we have a non-aggregate (scalar) constant
4168 bool zero = nextConst >= consts.size();
4169 spv::Id scalar = 0;
4170 switch (glslangType.getBasicType()) {
4171 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004172 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004173 break;
4174 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004175 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004176 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004177 case glslang::EbtInt64:
4178 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4179 break;
4180 case glslang::EbtUint64:
4181 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4182 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004183 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004184 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004185 break;
4186 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004187 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004188 break;
4189 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004190 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004191 break;
4192 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004193 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004194 break;
4195 }
4196 ++nextConst;
4197 return scalar;
4198 }
4199
4200 return builder.makeCompositeConstant(typeId, spvConsts);
4201}
4202
John Kessenich7c1aa102015-10-15 13:29:11 -06004203// Return true if the node is a constant or symbol whose reading has no
4204// non-trivial observable cost or effect.
4205bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4206{
4207 // don't know what this is
4208 if (node == nullptr)
4209 return false;
4210
4211 // a constant is safe
4212 if (node->getAsConstantUnion() != nullptr)
4213 return true;
4214
4215 // not a symbol means non-trivial
4216 if (node->getAsSymbolNode() == nullptr)
4217 return false;
4218
4219 // a symbol, depends on what's being read
4220 switch (node->getType().getQualifier().storage) {
4221 case glslang::EvqTemporary:
4222 case glslang::EvqGlobal:
4223 case glslang::EvqIn:
4224 case glslang::EvqInOut:
4225 case glslang::EvqConst:
4226 case glslang::EvqConstReadOnly:
4227 case glslang::EvqUniform:
4228 return true;
4229 default:
4230 return false;
4231 }
qining25262b32016-05-06 17:25:16 -04004232}
John Kessenich7c1aa102015-10-15 13:29:11 -06004233
4234// A node is trivial if it is a single operation with no side effects.
4235// Error on the side of saying non-trivial.
4236// Return true if trivial.
4237bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4238{
4239 if (node == nullptr)
4240 return false;
4241
4242 // symbols and constants are trivial
4243 if (isTrivialLeaf(node))
4244 return true;
4245
4246 // otherwise, it needs to be a simple operation or one or two leaf nodes
4247
4248 // not a simple operation
4249 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4250 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4251 if (binaryNode == nullptr && unaryNode == nullptr)
4252 return false;
4253
4254 // not on leaf nodes
4255 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4256 return false;
4257
4258 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4259 return false;
4260 }
4261
4262 switch (node->getAsOperator()->getOp()) {
4263 case glslang::EOpLogicalNot:
4264 case glslang::EOpConvIntToBool:
4265 case glslang::EOpConvUintToBool:
4266 case glslang::EOpConvFloatToBool:
4267 case glslang::EOpConvDoubleToBool:
4268 case glslang::EOpEqual:
4269 case glslang::EOpNotEqual:
4270 case glslang::EOpLessThan:
4271 case glslang::EOpGreaterThan:
4272 case glslang::EOpLessThanEqual:
4273 case glslang::EOpGreaterThanEqual:
4274 case glslang::EOpIndexDirect:
4275 case glslang::EOpIndexDirectStruct:
4276 case glslang::EOpLogicalXor:
4277 case glslang::EOpAny:
4278 case glslang::EOpAll:
4279 return true;
4280 default:
4281 return false;
4282 }
4283}
4284
4285// Emit short-circuiting code, where 'right' is never evaluated unless
4286// the left side is true (for &&) or false (for ||).
4287spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4288{
4289 spv::Id boolTypeId = builder.makeBoolType();
4290
4291 // emit left operand
4292 builder.clearAccessChain();
4293 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004294 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004295
4296 // Operands to accumulate OpPhi operands
4297 std::vector<spv::Id> phiOperands;
4298 // accumulate left operand's phi information
4299 phiOperands.push_back(leftId);
4300 phiOperands.push_back(builder.getBuildPoint()->getId());
4301
4302 // Make the two kinds of operation symmetric with a "!"
4303 // || => emit "if (! left) result = right"
4304 // && => emit "if ( left) result = right"
4305 //
4306 // TODO: this runtime "not" for || could be avoided by adding functionality
4307 // to 'builder' to have an "else" without an "then"
4308 if (op == glslang::EOpLogicalOr)
4309 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4310
4311 // make an "if" based on the left value
4312 spv::Builder::If ifBuilder(leftId, builder);
4313
4314 // emit right operand as the "then" part of the "if"
4315 builder.clearAccessChain();
4316 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004317 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004318
4319 // accumulate left operand's phi information
4320 phiOperands.push_back(rightId);
4321 phiOperands.push_back(builder.getBuildPoint()->getId());
4322
4323 // finish the "if"
4324 ifBuilder.makeEndIf();
4325
4326 // phi together the two results
4327 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4328}
4329
John Kessenich140f3df2015-06-26 16:58:36 -06004330}; // end anonymous namespace
4331
4332namespace glslang {
4333
John Kessenich68d78fd2015-07-12 19:28:10 -06004334void GetSpirvVersion(std::string& version)
4335{
John Kessenich9e55f632015-07-15 10:03:39 -06004336 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004337 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004338 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004339 version = buf;
4340}
4341
John Kessenich140f3df2015-06-26 16:58:36 -06004342// Write SPIR-V out to a binary file
4343void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4344{
4345 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004346 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004347 for (int i = 0; i < (int)spirv.size(); ++i) {
4348 unsigned int word = spirv[i];
4349 out.write((const char*)&word, 4);
4350 }
4351 out.close();
4352}
4353
4354//
4355// Set up the glslang traversal
4356//
4357void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4358{
Lei Zhang17535f72016-05-04 15:55:59 -04004359 spv::SpvBuildLogger logger;
4360 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004361}
4362
Lei Zhang17535f72016-05-04 15:55:59 -04004363void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004364{
John Kessenich140f3df2015-06-26 16:58:36 -06004365 TIntermNode* root = intermediate.getTreeRoot();
4366
4367 if (root == 0)
4368 return;
4369
4370 glslang::GetThreadPoolAllocator().push();
4371
Lei Zhang17535f72016-05-04 15:55:59 -04004372 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004373
4374 root->traverse(&it);
4375
4376 it.dumpSpv(spirv);
4377
4378 glslang::GetThreadPoolAllocator().pop();
4379}
4380
4381}; // end namespace glslang