blob: 950f7bdd3c6e260d01a325e54a788d23c12f1a1a [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);
John Kessenichebb50532016-05-16 19:22:05 -0600112 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool member);
John Kessenich5d0fa972016-02-15 11:57:00 -0700113 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
115 spv::Id getSampledType(const glslang::TSampler&);
116 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700117 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700118 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700119 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800120 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700121 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700122 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
123 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
124 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenichebb50532016-05-16 19:22:05 -0600125 void declareClipCullCapability(const glslang::TTypeList& members, int member);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
128 void makeFunctions(const glslang::TIntermSequence&);
129 void makeGlobalInitializers(const glslang::TIntermSequence&);
130 void visitFunctions(const glslang::TIntermSequence&);
131 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800132 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600133 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
134 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600135 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
136
qining25262b32016-05-06 17:25:16 -0400137 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
138 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
139 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
140 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800141 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800143 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich91cef522016-05-05 16:45:40 -0600144 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600154 bool isTrivialLeaf(const glslang::TIntermTyped* node);
155 bool isTrivial(const glslang::TIntermTyped* node);
156 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
158 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700159 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600160 int sequenceDepth;
161
Lei Zhang17535f72016-05-04 15:55:59 -0400162 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400163
John Kessenich140f3df2015-06-26 16:58:36 -0600164 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
165 spv::Builder builder;
166 bool inMain;
167 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700168 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700169 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600170 const glslang::TIntermediate* glslangIntermediate;
171 spv::Id stdBuiltins;
172
John Kessenich2f273362015-07-18 22:34:27 -0600173 std::unordered_map<int, spv::Id> symbolValues;
174 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
175 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700176 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600177 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600178 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600179};
180
181//
182// Helper functions for translating glslang representations to SPIR-V enumerants.
183//
184
185// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700186spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600187{
John Kessenich66e2faf2016-03-12 18:34:36 -0700188 switch (source) {
189 case glslang::EShSourceGlsl:
190 switch (profile) {
191 case ENoProfile:
192 case ECoreProfile:
193 case ECompatibilityProfile:
194 return spv::SourceLanguageGLSL;
195 case EEsProfile:
196 return spv::SourceLanguageESSL;
197 default:
198 return spv::SourceLanguageUnknown;
199 }
200 case glslang::EShSourceHlsl:
201 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 default:
203 return spv::SourceLanguageUnknown;
204 }
205}
206
207// Translate glslang language (stage) to SPIR-V execution model.
208spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
209{
210 switch (stage) {
211 case EShLangVertex: return spv::ExecutionModelVertex;
212 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
213 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
214 case EShLangGeometry: return spv::ExecutionModelGeometry;
215 case EShLangFragment: return spv::ExecutionModelFragment;
216 case EShLangCompute: return spv::ExecutionModelGLCompute;
217 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600219 return spv::ExecutionModelFragment;
220 }
221}
222
223// Translate glslang type to SPIR-V storage class.
224spv::StorageClass TranslateStorageClass(const glslang::TType& type)
225{
226 if (type.getQualifier().isPipeInput())
227 return spv::StorageClassInput;
228 else if (type.getQualifier().isPipeOutput())
229 return spv::StorageClassOutput;
230 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700231 if (type.getQualifier().layoutPushConstant)
232 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 if (type.getBasicType() == glslang::EbtBlock)
234 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800235 else if (type.getBasicType() == glslang::EbtAtomicUint)
236 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 else
238 return spv::StorageClassUniformConstant;
239 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
240 } else {
241 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700242 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
243 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600244 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
245 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400246 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700247 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600248 return spv::StorageClassFunction;
249 }
250 }
251}
252
253// Translate glslang sampler type to SPIR-V dimensionality.
254spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
255{
256 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700257 case glslang::Esd1D: return spv::Dim1D;
258 case glslang::Esd2D: return spv::Dim2D;
259 case glslang::Esd3D: return spv::Dim3D;
260 case glslang::EsdCube: return spv::DimCube;
261 case glslang::EsdRect: return spv::DimRect;
262 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700263 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700265 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600266 return spv::Dim2D;
267 }
268}
269
270// Translate glslang type to SPIR-V precision decorations.
271spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
272{
273 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700274 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600275 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600276 default:
277 return spv::NoPrecision;
278 }
279}
280
281// Translate glslang type to SPIR-V block decorations.
282spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
283{
284 if (type.getBasicType() == glslang::EbtBlock) {
285 switch (type.getQualifier().storage) {
286 case glslang::EvqUniform: return spv::DecorationBlock;
287 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
288 case glslang::EvqVaryingIn: return spv::DecorationBlock;
289 case glslang::EvqVaryingOut: return spv::DecorationBlock;
290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 break;
293 }
294 }
295
296 return (spv::Decoration)spv::BadValue;
297}
298
Rex Xu1da878f2016-02-21 20:59:01 +0800299// Translate glslang type to SPIR-V memory decorations.
300void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
301{
302 if (qualifier.coherent)
303 memory.push_back(spv::DecorationCoherent);
304 if (qualifier.volatil)
305 memory.push_back(spv::DecorationVolatile);
306 if (qualifier.restrict)
307 memory.push_back(spv::DecorationRestrict);
308 if (qualifier.readonly)
309 memory.push_back(spv::DecorationNonWritable);
310 if (qualifier.writeonly)
311 memory.push_back(spv::DecorationNonReadable);
312}
313
John Kessenich140f3df2015-06-26 16:58:36 -0600314// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700315spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600316{
317 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700318 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600319 case glslang::ElmRowMajor:
320 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 default:
324 // opaque layouts don't need a majorness
325 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 }
327 } else {
328 switch (type.getBasicType()) {
329 default:
330 return (spv::Decoration)spv::BadValue;
331 break;
332 case glslang::EbtBlock:
333 switch (type.getQualifier().storage) {
334 case glslang::EvqUniform:
335 case glslang::EvqBuffer:
336 switch (type.getQualifier().layoutPacking) {
337 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
339 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600340 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 }
342 case glslang::EvqVaryingIn:
343 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700344 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return (spv::Decoration)spv::BadValue;
349 }
350 }
351 }
352}
353
354// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700355// Returns spv::Decoration(spv::BadValue) when no decoration
356// should be applied.
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
John Kessenich140f3df2015-06-26 16:58:36 -0600404// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenichebb50532016-05-16 19:22:05 -0600405spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool member)
John Kessenich140f3df2015-06-26 16:58:36 -0600406{
407 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700408 case glslang::EbvPointSize:
409 switch (glslangIntermediate->getStage()) {
410 case EShLangGeometry:
411 builder.addCapability(spv::CapabilityGeometryPointSize);
412 break;
413 case EShLangTessControl:
414 case EShLangTessEvaluation:
415 builder.addCapability(spv::CapabilityTessellationPointSize);
416 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100417 default:
418 break;
John Kessenich92187592016-02-01 13:45:25 -0700419 }
420 return spv::BuiltInPointSize;
421
John Kessenichebb50532016-05-16 19:22:05 -0600422 // These *Distance capabilities logically belong here, but if the member is declared and
423 // then never used, consumers of SPIR-V prefer the capability not be declared.
424 // They are now generated when used, rather than here when declared.
425 // Potentially, the specification should be more clear what the minimum
426 // use needed is to trigger the capability.
427 //
John Kessenich92187592016-02-01 13:45:25 -0700428 case glslang::EbvClipDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600429 if (! member)
430 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700431 return spv::BuiltInClipDistance;
432
433 case glslang::EbvCullDistance:
John Kessenichebb50532016-05-16 19:22:05 -0600434 if (! member)
435 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700436 return spv::BuiltInCullDistance;
437
438 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500439 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700440 return spv::BuiltInViewportIndex;
441
John Kessenich5e801132016-02-15 11:09:46 -0700442 case glslang::EbvSampleId:
443 builder.addCapability(spv::CapabilitySampleRateShading);
444 return spv::BuiltInSampleId;
445
446 case glslang::EbvSamplePosition:
447 builder.addCapability(spv::CapabilitySampleRateShading);
448 return spv::BuiltInSamplePosition;
449
450 case glslang::EbvSampleMask:
451 builder.addCapability(spv::CapabilitySampleRateShading);
452 return spv::BuiltInSampleMask;
453
John Kessenich140f3df2015-06-26 16:58:36 -0600454 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600455 case glslang::EbvVertexId: return spv::BuiltInVertexId;
456 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700457 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
458 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600459 case glslang::EbvBaseVertex:
460 case glslang::EbvBaseInstance:
461 case glslang::EbvDrawId:
462 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600463 logger->missingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600464 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600465 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
466 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
467 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600468 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
469 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
470 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
471 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
472 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
473 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
474 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600475 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
476 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
477 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
478 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
479 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
480 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
481 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
482 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800483 case glslang::EbvSubGroupSize:
484 case glslang::EbvSubGroupInvocation:
485 case glslang::EbvSubGroupEqMask:
486 case glslang::EbvSubGroupGeMask:
487 case glslang::EbvSubGroupGtMask:
488 case glslang::EbvSubGroupLeMask:
489 case glslang::EbvSubGroupLtMask:
490 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600491 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +0800492 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600493 default: return (spv::BuiltIn)spv::BadValue;
494 }
495}
496
Rex Xufc618912015-09-09 16:42:49 +0800497// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700498spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800499{
500 assert(type.getBasicType() == glslang::EbtSampler);
501
John Kessenich5d0fa972016-02-15 11:57:00 -0700502 // Check for capabilities
503 switch (type.getQualifier().layoutFormat) {
504 case glslang::ElfRg32f:
505 case glslang::ElfRg16f:
506 case glslang::ElfR11fG11fB10f:
507 case glslang::ElfR16f:
508 case glslang::ElfRgba16:
509 case glslang::ElfRgb10A2:
510 case glslang::ElfRg16:
511 case glslang::ElfRg8:
512 case glslang::ElfR16:
513 case glslang::ElfR8:
514 case glslang::ElfRgba16Snorm:
515 case glslang::ElfRg16Snorm:
516 case glslang::ElfRg8Snorm:
517 case glslang::ElfR16Snorm:
518 case glslang::ElfR8Snorm:
519
520 case glslang::ElfRg32i:
521 case glslang::ElfRg16i:
522 case glslang::ElfRg8i:
523 case glslang::ElfR16i:
524 case glslang::ElfR8i:
525
526 case glslang::ElfRgb10a2ui:
527 case glslang::ElfRg32ui:
528 case glslang::ElfRg16ui:
529 case glslang::ElfRg8ui:
530 case glslang::ElfR16ui:
531 case glslang::ElfR8ui:
532 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
533 break;
534
535 default:
536 break;
537 }
538
539 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800540 switch (type.getQualifier().layoutFormat) {
541 case glslang::ElfNone: return spv::ImageFormatUnknown;
542 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
543 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
544 case glslang::ElfR32f: return spv::ImageFormatR32f;
545 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
546 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
547 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
548 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
549 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
550 case glslang::ElfR16f: return spv::ImageFormatR16f;
551 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
552 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
553 case glslang::ElfRg16: return spv::ImageFormatRg16;
554 case glslang::ElfRg8: return spv::ImageFormatRg8;
555 case glslang::ElfR16: return spv::ImageFormatR16;
556 case glslang::ElfR8: return spv::ImageFormatR8;
557 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
558 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
559 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
560 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
561 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
562 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
563 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
564 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
565 case glslang::ElfR32i: return spv::ImageFormatR32i;
566 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
567 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
568 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
569 case glslang::ElfR16i: return spv::ImageFormatR16i;
570 case glslang::ElfR8i: return spv::ImageFormatR8i;
571 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
572 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
573 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
574 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
575 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
576 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
577 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
578 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
579 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
580 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
581 default: return (spv::ImageFormat)spv::BadValue;
582 }
583}
584
qining25262b32016-05-06 17:25:16 -0400585// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700586// descriptor set.
587bool IsDescriptorResource(const glslang::TType& type)
588{
John Kessenichf7497e22016-03-08 21:36:22 -0700589 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700590 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700591 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700592
593 // non block...
594 // basically samplerXXX/subpass/sampler/texture are all included
595 // if they are the global-scope-class, not the function parameter
596 // (or local, if they ever exist) class.
597 if (type.getBasicType() == glslang::EbtSampler)
598 return type.getQualifier().isUniformOrBuffer();
599
600 // None of the above.
601 return false;
602}
603
John Kesseniche0b6cad2015-12-24 10:30:13 -0700604void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
605{
606 if (child.layoutMatrix == glslang::ElmNone)
607 child.layoutMatrix = parent.layoutMatrix;
608
609 if (parent.invariant)
610 child.invariant = true;
611 if (parent.nopersp)
612 child.nopersp = true;
613 if (parent.flat)
614 child.flat = true;
615 if (parent.centroid)
616 child.centroid = true;
617 if (parent.patch)
618 child.patch = true;
619 if (parent.sample)
620 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800621 if (parent.coherent)
622 child.coherent = true;
623 if (parent.volatil)
624 child.volatil = true;
625 if (parent.restrict)
626 child.restrict = true;
627 if (parent.readonly)
628 child.readonly = true;
629 if (parent.writeonly)
630 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700631}
632
633bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
634{
John Kessenich7b9fa252016-01-21 18:56:57 -0700635 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700636 // - struct members can inherit from a struct declaration
637 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
638 // - are not part of the offset/st430/etc or row/column-major layout
qining25262b32016-05-06 17:25:16 -0400639 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700640}
641
John Kessenich140f3df2015-06-26 16:58:36 -0600642//
643// Implement the TGlslangToSpvTraverser class.
644//
645
Lei Zhang17535f72016-05-04 15:55:59 -0400646TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
647 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
648 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600649 inMain(false), mainTerminated(false), linkageOnly(false),
650 glslangIntermediate(glslangIntermediate)
651{
652 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
653
654 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700655 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600656 stdBuiltins = builder.import("GLSL.std.450");
657 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700658 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
659 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600660
661 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600662 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
663 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600664 builder.addSourceExtension(it->c_str());
665
666 // Add the top-level modes for this shader.
667
John Kessenich92187592016-02-01 13:45:25 -0700668 if (glslangIntermediate->getXfbMode()) {
669 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600670 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700671 }
John Kessenich140f3df2015-06-26 16:58:36 -0600672
673 unsigned int mode;
674 switch (glslangIntermediate->getStage()) {
675 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600676 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600677 break;
678
679 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600680 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600681 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
682 break;
683
684 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600685 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600686 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700687 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
688 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
689 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600690 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600691 }
692 if (mode != spv::BadValue)
693 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
694
John Kesseniche6903322015-10-13 16:29:02 -0600695 switch (glslangIntermediate->getVertexSpacing()) {
696 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
697 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
698 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
699 default: mode = spv::BadValue; break;
700 }
701 if (mode != spv::BadValue)
702 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
703
704 switch (glslangIntermediate->getVertexOrder()) {
705 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
706 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
707 default: mode = spv::BadValue; break;
708 }
709 if (mode != spv::BadValue)
710 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
711
712 if (glslangIntermediate->getPointMode())
713 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600714 break;
715
716 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600717 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600718 switch (glslangIntermediate->getInputPrimitive()) {
719 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
720 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
721 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700722 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600723 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
724 default: mode = spv::BadValue; break;
725 }
726 if (mode != spv::BadValue)
727 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600728
John Kessenich140f3df2015-06-26 16:58:36 -0600729 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
730
731 switch (glslangIntermediate->getOutputPrimitive()) {
732 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
733 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
734 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
735 default: mode = spv::BadValue; break;
736 }
737 if (mode != spv::BadValue)
738 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
739 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
740 break;
741
742 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600743 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600744 if (glslangIntermediate->getPixelCenterInteger())
745 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600746
John Kessenich140f3df2015-06-26 16:58:36 -0600747 if (glslangIntermediate->getOriginUpperLeft())
748 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600749 else
750 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600751
752 if (glslangIntermediate->getEarlyFragmentTests())
753 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
754
755 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600756 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
757 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
758 default: mode = spv::BadValue; break;
759 }
760 if (mode != spv::BadValue)
761 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
762
763 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
764 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600765 break;
766
767 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600768 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600769 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
770 glslangIntermediate->getLocalSize(1),
771 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600772 break;
773
774 default:
775 break;
776 }
777
778}
779
John Kessenich7ba63412015-12-20 17:37:07 -0700780// Finish everything and dump
781void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
782{
783 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100784 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
785 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700786
qiningda397332016-03-09 19:54:03 -0500787 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700788 builder.dump(out);
789}
790
John Kessenich140f3df2015-06-26 16:58:36 -0600791TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
792{
793 if (! mainTerminated) {
794 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
795 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600796 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600797 }
798}
799
800//
801// Implement the traversal functions.
802//
803// Return true from interior nodes to have the external traversal
804// continue on to children. Return false if children were
805// already processed.
806//
807
808//
qining25262b32016-05-06 17:25:16 -0400809// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600810// - uniform/input reads
811// - output writes
812// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
813// - something simple that degenerates into the last bullet
814//
815void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
816{
qining75d1d802016-04-06 14:42:01 -0400817 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
818 if (symbol->getType().getQualifier().isSpecConstant())
819 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
820
John Kessenich140f3df2015-06-26 16:58:36 -0600821 // getSymbolId() will set up all the IO decorations on the first call.
822 // Formal function parameters were mapped during makeFunctions().
823 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700824
825 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
826 if (builder.isPointer(id)) {
827 spv::StorageClass sc = builder.getStorageClass(id);
828 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
829 iOSet.insert(id);
830 }
831
832 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700833 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600834 // Prepare to generate code for the access
835
836 // L-value chains will be computed left to right. We're on the symbol now,
837 // which is the left-most part of the access chain, so now is "clear" time,
838 // followed by setting the base.
839 builder.clearAccessChain();
840
841 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700842 // except for
843 // A) "const in" arguments to a function, which are an intermediate object.
844 // See comments in handleUserFunctionCall().
845 // B) Specialization constants (normal constant don't even come in as a variable),
846 // These are also pure R-values.
847 glslang::TQualifier qualifier = symbol->getQualifier();
848 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
849 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600850 builder.setAccessChainRValue(id);
851 else
852 builder.setAccessChainLValue(id);
853 }
854}
855
856bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
857{
qining40887662016-04-03 22:20:42 -0400858 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
859 if (node->getType().getQualifier().isSpecConstant())
860 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
861
John Kessenich140f3df2015-06-26 16:58:36 -0600862 // First, handle special cases
863 switch (node->getOp()) {
864 case glslang::EOpAssign:
865 case glslang::EOpAddAssign:
866 case glslang::EOpSubAssign:
867 case glslang::EOpMulAssign:
868 case glslang::EOpVectorTimesMatrixAssign:
869 case glslang::EOpVectorTimesScalarAssign:
870 case glslang::EOpMatrixTimesScalarAssign:
871 case glslang::EOpMatrixTimesMatrixAssign:
872 case glslang::EOpDivAssign:
873 case glslang::EOpModAssign:
874 case glslang::EOpAndAssign:
875 case glslang::EOpInclusiveOrAssign:
876 case glslang::EOpExclusiveOrAssign:
877 case glslang::EOpLeftShiftAssign:
878 case glslang::EOpRightShiftAssign:
879 // A bin-op assign "a += b" means the same thing as "a = a + b"
880 // where a is evaluated before b. For a simple assignment, GLSL
881 // says to evaluate the left before the right. So, always, left
882 // node then right node.
883 {
884 // get the left l-value, save it away
885 builder.clearAccessChain();
886 node->getLeft()->traverse(this);
887 spv::Builder::AccessChain lValue = builder.getAccessChain();
888
889 // evaluate the right
890 builder.clearAccessChain();
891 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700892 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 if (node->getOp() != glslang::EOpAssign) {
895 // the left is also an r-value
896 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700897 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600898
899 // do the operation
qining25262b32016-05-06 17:25:16 -0400900 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
901 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600902 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
903 node->getType().getBasicType());
904
905 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700906 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600907 }
908
909 // store the result
910 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800911 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600912
913 // assignments are expressions having an rValue after they are evaluated...
914 builder.clearAccessChain();
915 builder.setAccessChainRValue(rValue);
916 }
917 return false;
918 case glslang::EOpIndexDirect:
919 case glslang::EOpIndexDirectStruct:
920 {
921 // Get the left part of the access chain.
922 node->getLeft()->traverse(this);
923
924 // Add the next element in the chain
925
John Kessenich55e7d112015-11-15 21:33:39 -0700926 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600927 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
928 // This may be, e.g., an anonymous block-member selection, which generally need
929 // index remapping due to hidden members in anonymous blocks.
930 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700931 assert(remapper.size() > 0);
932 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600933 }
934
935 if (! node->getLeft()->getType().isArray() &&
936 node->getLeft()->getType().isVector() &&
937 node->getOp() == glslang::EOpIndexDirect) {
938 // This is essentially a hard-coded vector swizzle of size 1,
939 // so short circuit the access-chain stuff with a swizzle.
940 std::vector<unsigned> swizzle;
941 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600942 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600943 } else {
944 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600945 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenichebb50532016-05-16 19:22:05 -0600946
947 // Add capabilities here for accessing clip/cull distance
948 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
949 declareClipCullCapability(*node->getLeft()->getType().getStruct(), index);
John Kessenich140f3df2015-06-26 16:58:36 -0600950 }
951 }
952 return false;
953 case glslang::EOpIndexIndirect:
954 {
955 // Structure or array or vector indirection.
956 // Will use native SPIR-V access-chain for struct and array indirection;
957 // matrices are arrays of vectors, so will also work for a matrix.
958 // Will use the access chain's 'component' for variable index into a vector.
959
960 // This adapter is building access chains left to right.
961 // Set up the access chain to the left.
962 node->getLeft()->traverse(this);
963
964 // save it so that computing the right side doesn't trash it
965 spv::Builder::AccessChain partial = builder.getAccessChain();
966
967 // compute the next index in the chain
968 builder.clearAccessChain();
969 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700970 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600971
972 // restore the saved access chain
973 builder.setAccessChain(partial);
974
975 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600976 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600977 else
John Kessenichfa668da2015-09-13 14:46:30 -0600978 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600979 }
980 return false;
981 case glslang::EOpVectorSwizzle:
982 {
983 node->getLeft()->traverse(this);
984 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
985 std::vector<unsigned> swizzle;
986 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
987 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600988 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600989 }
990 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600991 case glslang::EOpLogicalOr:
992 case glslang::EOpLogicalAnd:
993 {
994
995 // These may require short circuiting, but can sometimes be done as straight
996 // binary operations. The right operand must be short circuited if it has
997 // side effects, and should probably be if it is complex.
998 if (isTrivial(node->getRight()->getAsTyped()))
999 break; // handle below as a normal binary operation
1000 // otherwise, we need to do dynamic short circuiting on the right operand
1001 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1002 builder.clearAccessChain();
1003 builder.setAccessChainRValue(result);
1004 }
1005 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001006 default:
1007 break;
1008 }
1009
1010 // Assume generic binary op...
1011
John Kessenich32cfd492016-02-02 12:37:46 -07001012 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001013 builder.clearAccessChain();
1014 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001015 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001016
John Kessenich32cfd492016-02-02 12:37:46 -07001017 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001018 builder.clearAccessChain();
1019 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001020 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001021
John Kessenich32cfd492016-02-02 12:37:46 -07001022 // get result
1023 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001024 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001025 convertGlslangToSpvType(node->getType()), left, right,
1026 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001027
John Kessenich50e57562015-12-21 21:21:11 -07001028 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001029 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001030 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001031 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001032 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001033 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001034 return false;
1035 }
John Kessenich140f3df2015-06-26 16:58:36 -06001036}
1037
1038bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1039{
qining40887662016-04-03 22:20:42 -04001040 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1041 if (node->getType().getQualifier().isSpecConstant())
1042 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1043
John Kessenichfc51d282015-08-19 13:34:18 -06001044 spv::Id result = spv::NoResult;
1045
1046 // try texturing first
1047 result = createImageTextureFunctionCall(node);
1048 if (result != spv::NoResult) {
1049 builder.clearAccessChain();
1050 builder.setAccessChainRValue(result);
1051
1052 return false; // done with this node
1053 }
1054
1055 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001056
1057 if (node->getOp() == glslang::EOpArrayLength) {
1058 // Quite special; won't want to evaluate the operand.
1059
1060 // Normal .length() would have been constant folded by the front-end.
1061 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001062 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001063 assert(node->getOperand()->getType().isRuntimeSizedArray());
1064 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1065 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001066 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1067 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001068
1069 builder.clearAccessChain();
1070 builder.setAccessChainRValue(length);
1071
1072 return false;
1073 }
1074
John Kessenichfc51d282015-08-19 13:34:18 -06001075 // Start by evaluating the operand
1076
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.clearAccessChain();
1078 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001079
Rex Xufc618912015-09-09 16:42:49 +08001080 spv::Id operand = spv::NoResult;
1081
1082 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1083 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001084 node->getOp() == glslang::EOpAtomicCounter ||
1085 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001086 operand = builder.accessChainGetLValue(); // Special case l-value operands
1087 else
John Kessenich32cfd492016-02-02 12:37:46 -07001088 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001089
1090 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001091 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001092
1093 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001094 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001095 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001096
1097 // if not, then possibly an operation
1098 if (! result)
qining25262b32016-05-06 17:25:16 -04001099 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001100
1101 if (result) {
1102 builder.clearAccessChain();
1103 builder.setAccessChainRValue(result);
1104
1105 return false; // done with this node
1106 }
1107
1108 // it must be a special case, check...
1109 switch (node->getOp()) {
1110 case glslang::EOpPostIncrement:
1111 case glslang::EOpPostDecrement:
1112 case glslang::EOpPreIncrement:
1113 case glslang::EOpPreDecrement:
1114 {
1115 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001116 spv::Id one = 0;
1117 if (node->getBasicType() == glslang::EbtFloat)
1118 one = builder.makeFloatConstant(1.0F);
1119 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1120 one = builder.makeInt64Constant(1);
1121 else
1122 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001123 glslang::TOperator op;
1124 if (node->getOp() == glslang::EOpPreIncrement ||
1125 node->getOp() == glslang::EOpPostIncrement)
1126 op = glslang::EOpAdd;
1127 else
1128 op = glslang::EOpSub;
1129
qining25262b32016-05-06 17:25:16 -04001130 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1131 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001132 convertGlslangToSpvType(node->getType()), operand, one,
1133 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001134 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001135
1136 // The result of operation is always stored, but conditionally the
1137 // consumed result. The consumed result is always an r-value.
1138 builder.accessChainStore(result);
1139 builder.clearAccessChain();
1140 if (node->getOp() == glslang::EOpPreIncrement ||
1141 node->getOp() == glslang::EOpPreDecrement)
1142 builder.setAccessChainRValue(result);
1143 else
1144 builder.setAccessChainRValue(operand);
1145 }
1146
1147 return false;
1148
1149 case glslang::EOpEmitStreamVertex:
1150 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1151 return false;
1152 case glslang::EOpEndStreamPrimitive:
1153 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1154 return false;
1155
1156 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001157 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001158 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001159 }
John Kessenich140f3df2015-06-26 16:58:36 -06001160}
1161
1162bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1163{
qining27e04a02016-04-14 16:40:20 -04001164 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1165 if (node->getType().getQualifier().isSpecConstant())
1166 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1167
John Kessenichfc51d282015-08-19 13:34:18 -06001168 spv::Id result = spv::NoResult;
1169
1170 // try texturing
1171 result = createImageTextureFunctionCall(node);
1172 if (result != spv::NoResult) {
1173 builder.clearAccessChain();
1174 builder.setAccessChainRValue(result);
1175
1176 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001177 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001178 // "imageStore" is a special case, which has no result
1179 return false;
1180 }
John Kessenichfc51d282015-08-19 13:34:18 -06001181
John Kessenich140f3df2015-06-26 16:58:36 -06001182 glslang::TOperator binOp = glslang::EOpNull;
1183 bool reduceComparison = true;
1184 bool isMatrix = false;
1185 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001186 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001187
1188 assert(node->getOp());
1189
1190 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1191
1192 switch (node->getOp()) {
1193 case glslang::EOpSequence:
1194 {
1195 if (preVisit)
1196 ++sequenceDepth;
1197 else
1198 --sequenceDepth;
1199
1200 if (sequenceDepth == 1) {
1201 // If this is the parent node of all the functions, we want to see them
1202 // early, so all call points have actual SPIR-V functions to reference.
1203 // In all cases, still let the traverser visit the children for us.
1204 makeFunctions(node->getAsAggregate()->getSequence());
1205
1206 // Also, we want all globals initializers to go into the entry of main(), before
1207 // anything else gets there, so visit out of order, doing them all now.
1208 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1209
1210 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1211 // so do them manually.
1212 visitFunctions(node->getAsAggregate()->getSequence());
1213
1214 return false;
1215 }
1216
1217 return true;
1218 }
1219 case glslang::EOpLinkerObjects:
1220 {
1221 if (visit == glslang::EvPreVisit)
1222 linkageOnly = true;
1223 else
1224 linkageOnly = false;
1225
1226 return true;
1227 }
1228 case glslang::EOpComma:
1229 {
1230 // processing from left to right naturally leaves the right-most
1231 // lying around in the access chain
1232 glslang::TIntermSequence& glslangOperands = node->getSequence();
1233 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1234 glslangOperands[i]->traverse(this);
1235
1236 return false;
1237 }
1238 case glslang::EOpFunction:
1239 if (visit == glslang::EvPreVisit) {
1240 if (isShaderEntrypoint(node)) {
1241 inMain = true;
1242 builder.setBuildPoint(shaderEntry->getLastBlock());
1243 } else {
1244 handleFunctionEntry(node);
1245 }
1246 } else {
1247 if (inMain)
1248 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001249 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001250 inMain = false;
1251 }
1252
1253 return true;
1254 case glslang::EOpParameters:
1255 // Parameters will have been consumed by EOpFunction processing, but not
1256 // the body, so we still visited the function node's children, making this
1257 // child redundant.
1258 return false;
1259 case glslang::EOpFunctionCall:
1260 {
1261 if (node->isUserDefined())
1262 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001263 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1264 if (result) {
1265 builder.clearAccessChain();
1266 builder.setAccessChainRValue(result);
1267 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001268 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001269
1270 return false;
1271 }
1272 case glslang::EOpConstructMat2x2:
1273 case glslang::EOpConstructMat2x3:
1274 case glslang::EOpConstructMat2x4:
1275 case glslang::EOpConstructMat3x2:
1276 case glslang::EOpConstructMat3x3:
1277 case glslang::EOpConstructMat3x4:
1278 case glslang::EOpConstructMat4x2:
1279 case glslang::EOpConstructMat4x3:
1280 case glslang::EOpConstructMat4x4:
1281 case glslang::EOpConstructDMat2x2:
1282 case glslang::EOpConstructDMat2x3:
1283 case glslang::EOpConstructDMat2x4:
1284 case glslang::EOpConstructDMat3x2:
1285 case glslang::EOpConstructDMat3x3:
1286 case glslang::EOpConstructDMat3x4:
1287 case glslang::EOpConstructDMat4x2:
1288 case glslang::EOpConstructDMat4x3:
1289 case glslang::EOpConstructDMat4x4:
1290 isMatrix = true;
1291 // fall through
1292 case glslang::EOpConstructFloat:
1293 case glslang::EOpConstructVec2:
1294 case glslang::EOpConstructVec3:
1295 case glslang::EOpConstructVec4:
1296 case glslang::EOpConstructDouble:
1297 case glslang::EOpConstructDVec2:
1298 case glslang::EOpConstructDVec3:
1299 case glslang::EOpConstructDVec4:
1300 case glslang::EOpConstructBool:
1301 case glslang::EOpConstructBVec2:
1302 case glslang::EOpConstructBVec3:
1303 case glslang::EOpConstructBVec4:
1304 case glslang::EOpConstructInt:
1305 case glslang::EOpConstructIVec2:
1306 case glslang::EOpConstructIVec3:
1307 case glslang::EOpConstructIVec4:
1308 case glslang::EOpConstructUint:
1309 case glslang::EOpConstructUVec2:
1310 case glslang::EOpConstructUVec3:
1311 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001312 case glslang::EOpConstructInt64:
1313 case glslang::EOpConstructI64Vec2:
1314 case glslang::EOpConstructI64Vec3:
1315 case glslang::EOpConstructI64Vec4:
1316 case glslang::EOpConstructUint64:
1317 case glslang::EOpConstructU64Vec2:
1318 case glslang::EOpConstructU64Vec3:
1319 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001320 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001321 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001322 {
1323 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001324 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001325 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1326 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001327 if (node->getOp() == glslang::EOpConstructTextureSampler)
1328 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1329 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001330 std::vector<spv::Id> constituents;
1331 for (int c = 0; c < (int)arguments.size(); ++c)
1332 constituents.push_back(arguments[c]);
1333 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001334 } else if (isMatrix)
1335 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1336 else
1337 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 builder.clearAccessChain();
1340 builder.setAccessChainRValue(constructed);
1341
1342 return false;
1343 }
1344
1345 // These six are component-wise compares with component-wise results.
1346 // Forward on to createBinaryOperation(), requesting a vector result.
1347 case glslang::EOpLessThan:
1348 case glslang::EOpGreaterThan:
1349 case glslang::EOpLessThanEqual:
1350 case glslang::EOpGreaterThanEqual:
1351 case glslang::EOpVectorEqual:
1352 case glslang::EOpVectorNotEqual:
1353 {
1354 // Map the operation to a binary
1355 binOp = node->getOp();
1356 reduceComparison = false;
1357 switch (node->getOp()) {
1358 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1359 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1360 default: binOp = node->getOp(); break;
1361 }
1362
1363 break;
1364 }
1365 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001366 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001367 binOp = glslang::EOpMul;
1368 break;
1369 case glslang::EOpOuterProduct:
1370 // two vectors multiplied to make a matrix
1371 binOp = glslang::EOpOuterProduct;
1372 break;
1373 case glslang::EOpDot:
1374 {
qining25262b32016-05-06 17:25:16 -04001375 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001376 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001377 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001378 binOp = glslang::EOpMul;
1379 break;
1380 }
1381 case glslang::EOpMod:
1382 // when an aggregate, this is the floating-point mod built-in function,
1383 // which can be emitted by the one in createBinaryOperation()
1384 binOp = glslang::EOpMod;
1385 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001386 case glslang::EOpEmitVertex:
1387 case glslang::EOpEndPrimitive:
1388 case glslang::EOpBarrier:
1389 case glslang::EOpMemoryBarrier:
1390 case glslang::EOpMemoryBarrierAtomicCounter:
1391 case glslang::EOpMemoryBarrierBuffer:
1392 case glslang::EOpMemoryBarrierImage:
1393 case glslang::EOpMemoryBarrierShared:
1394 case glslang::EOpGroupMemoryBarrier:
1395 noReturnValue = true;
1396 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1397 break;
1398
John Kessenich426394d2015-07-23 10:22:48 -06001399 case glslang::EOpAtomicAdd:
1400 case glslang::EOpAtomicMin:
1401 case glslang::EOpAtomicMax:
1402 case glslang::EOpAtomicAnd:
1403 case glslang::EOpAtomicOr:
1404 case glslang::EOpAtomicXor:
1405 case glslang::EOpAtomicExchange:
1406 case glslang::EOpAtomicCompSwap:
1407 atomic = true;
1408 break;
1409
John Kessenich140f3df2015-06-26 16:58:36 -06001410 default:
1411 break;
1412 }
1413
1414 //
1415 // See if it maps to a regular operation.
1416 //
John Kessenich140f3df2015-06-26 16:58:36 -06001417 if (binOp != glslang::EOpNull) {
1418 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1419 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1420 assert(left && right);
1421
1422 builder.clearAccessChain();
1423 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001424 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001425
1426 builder.clearAccessChain();
1427 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001428 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001429
qining25262b32016-05-06 17:25:16 -04001430 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1431 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001432 left->getType().getBasicType(), reduceComparison);
1433
1434 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001435 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 builder.clearAccessChain();
1437 builder.setAccessChainRValue(result);
1438
1439 return false;
1440 }
1441
John Kessenich426394d2015-07-23 10:22:48 -06001442 //
1443 // Create the list of operands.
1444 //
John Kessenich140f3df2015-06-26 16:58:36 -06001445 glslang::TIntermSequence& glslangOperands = node->getSequence();
1446 std::vector<spv::Id> operands;
1447 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1448 builder.clearAccessChain();
1449 glslangOperands[arg]->traverse(this);
1450
1451 // special case l-value operands; there are just a few
1452 bool lvalue = false;
1453 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001454 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001455 case glslang::EOpModf:
1456 if (arg == 1)
1457 lvalue = true;
1458 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001459 case glslang::EOpInterpolateAtSample:
1460 case glslang::EOpInterpolateAtOffset:
1461 if (arg == 0)
1462 lvalue = true;
1463 break;
Rex Xud4782c12015-09-06 16:30:11 +08001464 case glslang::EOpAtomicAdd:
1465 case glslang::EOpAtomicMin:
1466 case glslang::EOpAtomicMax:
1467 case glslang::EOpAtomicAnd:
1468 case glslang::EOpAtomicOr:
1469 case glslang::EOpAtomicXor:
1470 case glslang::EOpAtomicExchange:
1471 case glslang::EOpAtomicCompSwap:
1472 if (arg == 0)
1473 lvalue = true;
1474 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001475 case glslang::EOpAddCarry:
1476 case glslang::EOpSubBorrow:
1477 if (arg == 2)
1478 lvalue = true;
1479 break;
1480 case glslang::EOpUMulExtended:
1481 case glslang::EOpIMulExtended:
1482 if (arg >= 2)
1483 lvalue = true;
1484 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001485 default:
1486 break;
1487 }
1488 if (lvalue)
1489 operands.push_back(builder.accessChainGetLValue());
1490 else
John Kessenich32cfd492016-02-02 12:37:46 -07001491 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001492 }
John Kessenich426394d2015-07-23 10:22:48 -06001493
1494 if (atomic) {
1495 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001496 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001497 } else {
1498 // Pass through to generic operations.
1499 switch (glslangOperands.size()) {
1500 case 0:
1501 result = createNoArgOperation(node->getOp());
1502 break;
1503 case 1:
qining25262b32016-05-06 17:25:16 -04001504 result = createUnaryOperation(
1505 node->getOp(), precision,
1506 TranslateNoContractionDecoration(node->getType().getQualifier()),
1507 convertGlslangToSpvType(node->getType()), operands.front(),
1508 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001509 break;
1510 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001511 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001512 break;
1513 }
John Kessenich140f3df2015-06-26 16:58:36 -06001514 }
1515
1516 if (noReturnValue)
1517 return false;
1518
1519 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001520 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001521 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001522 } else {
1523 builder.clearAccessChain();
1524 builder.setAccessChainRValue(result);
1525 return false;
1526 }
1527}
1528
1529bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1530{
1531 // This path handles both if-then-else and ?:
1532 // The if-then-else has a node type of void, while
1533 // ?: has a non-void node type
1534 spv::Id result = 0;
1535 if (node->getBasicType() != glslang::EbtVoid) {
1536 // don't handle this as just on-the-fly temporaries, because there will be two names
1537 // and better to leave SSA to later passes
1538 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1539 }
1540
1541 // emit the condition before doing anything with selection
1542 node->getCondition()->traverse(this);
1543
1544 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001545 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001546
1547 if (node->getTrueBlock()) {
1548 // emit the "then" statement
1549 node->getTrueBlock()->traverse(this);
1550 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001551 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001552 }
1553
1554 if (node->getFalseBlock()) {
1555 ifBuilder.makeBeginElse();
1556 // emit the "else" statement
1557 node->getFalseBlock()->traverse(this);
1558 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001559 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001560 }
1561
1562 ifBuilder.makeEndIf();
1563
1564 if (result) {
1565 // GLSL only has r-values as the result of a :?, but
1566 // if we have an l-value, that can be more efficient if it will
1567 // become the base of a complex r-value expression, because the
1568 // next layer copies r-values into memory to use the access-chain mechanism
1569 builder.clearAccessChain();
1570 builder.setAccessChainLValue(result);
1571 }
1572
1573 return false;
1574}
1575
1576bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1577{
1578 // emit and get the condition before doing anything with switch
1579 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001580 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001581
1582 // browse the children to sort out code segments
1583 int defaultSegment = -1;
1584 std::vector<TIntermNode*> codeSegments;
1585 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1586 std::vector<int> caseValues;
1587 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1588 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1589 TIntermNode* child = *c;
1590 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001591 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001592 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001593 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001594 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1595 } else
1596 codeSegments.push_back(child);
1597 }
1598
qining25262b32016-05-06 17:25:16 -04001599 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001600 // statements between the last case and the end of the switch statement
1601 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1602 (int)codeSegments.size() == defaultSegment)
1603 codeSegments.push_back(nullptr);
1604
1605 // make the switch statement
1606 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001607 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001608
1609 // emit all the code in the segments
1610 breakForLoop.push(false);
1611 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1612 builder.nextSwitchSegment(segmentBlocks, s);
1613 if (codeSegments[s])
1614 codeSegments[s]->traverse(this);
1615 else
1616 builder.addSwitchBreak();
1617 }
1618 breakForLoop.pop();
1619
1620 builder.endSwitch(segmentBlocks);
1621
1622 return false;
1623}
1624
1625void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1626{
1627 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001628 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001629
1630 builder.clearAccessChain();
1631 builder.setAccessChainRValue(constant);
1632}
1633
1634bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1635{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001636 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001637 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001638 // Spec requires back edges to target header blocks, and every header block
1639 // must dominate its merge block. Make a header block first to ensure these
1640 // conditions are met. By definition, it will contain OpLoopMerge, followed
1641 // by a block-ending branch. But we don't want to put any other body/test
1642 // instructions in it, since the body/test may have arbitrary instructions,
1643 // including merges of its own.
1644 builder.setBuildPoint(&blocks.head);
1645 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001646 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001647 spv::Block& test = builder.makeNewBlock();
1648 builder.createBranch(&test);
1649
1650 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001651 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001652 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001653 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001654 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1655
1656 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001657 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001658 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001659 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001660 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001661 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001662
1663 builder.setBuildPoint(&blocks.continue_target);
1664 if (node->getTerminal())
1665 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001666 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001667 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001668 builder.createBranch(&blocks.body);
1669
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001670 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001671 builder.setBuildPoint(&blocks.body);
1672 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001673 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001674 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001675 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001676
1677 builder.setBuildPoint(&blocks.continue_target);
1678 if (node->getTerminal())
1679 node->getTerminal()->traverse(this);
1680 if (node->getTest()) {
1681 node->getTest()->traverse(this);
1682 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001683 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001684 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001685 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001686 // TODO: unless there was a break/return/discard instruction
1687 // somewhere in the body, this is an infinite loop, so we should
1688 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001689 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001690 }
John Kessenich140f3df2015-06-26 16:58:36 -06001691 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001692 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001693 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001694 return false;
1695}
1696
1697bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1698{
1699 if (node->getExpression())
1700 node->getExpression()->traverse(this);
1701
1702 switch (node->getFlowOp()) {
1703 case glslang::EOpKill:
1704 builder.makeDiscard();
1705 break;
1706 case glslang::EOpBreak:
1707 if (breakForLoop.top())
1708 builder.createLoopExit();
1709 else
1710 builder.addSwitchBreak();
1711 break;
1712 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001713 builder.createLoopContinue();
1714 break;
1715 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001716 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001717 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001718 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001719 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001720
1721 builder.clearAccessChain();
1722 break;
1723
1724 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001725 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001726 break;
1727 }
1728
1729 return false;
1730}
1731
1732spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1733{
qining25262b32016-05-06 17:25:16 -04001734 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001735 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001736 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001737 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001738 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 }
1740
1741 // Now, handle actual variables
1742 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1743 spv::Id spvType = convertGlslangToSpvType(node->getType());
1744
1745 const char* name = node->getName().c_str();
1746 if (glslang::IsAnonymous(name))
1747 name = "";
1748
1749 return builder.createVariable(storageClass, spvType, name);
1750}
1751
1752// Return type Id of the sampled type.
1753spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1754{
1755 switch (sampler.type) {
1756 case glslang::EbtFloat: return builder.makeFloatType(32);
1757 case glslang::EbtInt: return builder.makeIntType(32);
1758 case glslang::EbtUint: return builder.makeUintType(32);
1759 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001760 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001761 return builder.makeFloatType(32);
1762 }
1763}
1764
John Kessenich3ac051e2015-12-20 11:29:16 -07001765// Convert from a glslang type to an SPV type, by calling into a
1766// recursive version of this function. This establishes the inherited
1767// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001768spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1769{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001770 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001771}
1772
1773// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001774// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001775spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001776{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001777 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001778
1779 switch (type.getBasicType()) {
1780 case glslang::EbtVoid:
1781 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001782 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001783 break;
1784 case glslang::EbtFloat:
1785 spvType = builder.makeFloatType(32);
1786 break;
1787 case glslang::EbtDouble:
1788 spvType = builder.makeFloatType(64);
1789 break;
1790 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001791 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1792 // a 32-bit int where non-0 means true.
1793 if (explicitLayout != glslang::ElpNone)
1794 spvType = builder.makeUintType(32);
1795 else
1796 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001797 break;
1798 case glslang::EbtInt:
1799 spvType = builder.makeIntType(32);
1800 break;
1801 case glslang::EbtUint:
1802 spvType = builder.makeUintType(32);
1803 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001804 case glslang::EbtInt64:
1805 builder.addCapability(spv::CapabilityInt64);
1806 spvType = builder.makeIntType(64);
1807 break;
1808 case glslang::EbtUint64:
1809 builder.addCapability(spv::CapabilityInt64);
1810 spvType = builder.makeUintType(64);
1811 break;
John Kessenich426394d2015-07-23 10:22:48 -06001812 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001813 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 -06001814 spvType = builder.makeUintType(32);
1815 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001816 case glslang::EbtSampler:
1817 {
1818 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001819 if (sampler.sampler) {
1820 // pure sampler
1821 spvType = builder.makeSamplerType();
1822 } else {
1823 // an image is present, make its type
1824 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1825 sampler.image ? 2 : 1, TranslateImageFormat(type));
1826 if (sampler.combined) {
1827 // already has both image and sampler, make the combined type
1828 spvType = builder.makeSampledImageType(spvType);
1829 }
John Kessenich55e7d112015-11-15 21:33:39 -07001830 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001831 }
John Kessenich140f3df2015-06-26 16:58:36 -06001832 break;
1833 case glslang::EbtStruct:
1834 case glslang::EbtBlock:
1835 {
1836 // If we've seen this struct type, return it
1837 const glslang::TTypeList* glslangStruct = type.getStruct();
1838 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001839
1840 // Try to share structs for different layouts, but not yet for other
1841 // kinds of qualification (primarily not yet including interpolant qualification).
1842 if (! HasNonLayoutQualifiers(qualifier))
1843 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1844 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001845 break;
1846
1847 // else, we haven't seen it...
1848
1849 // Create a vector of struct types for SPIR-V to consume
1850 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1851 if (type.getBasicType() == glslang::EbtBlock)
1852 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001853 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001854 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1855 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1856 if (glslangType.hiddenMember()) {
1857 ++memberDelta;
1858 if (type.getBasicType() == glslang::EbtBlock)
1859 memberRemapper[glslangStruct][i] = -1;
1860 } else {
1861 if (type.getBasicType() == glslang::EbtBlock)
1862 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001863 // modify just this child's view of the qualifier
1864 glslang::TQualifier subQualifier = glslangType.getQualifier();
1865 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001866
1867 // manually inherit location; it's more complex
1868 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1869 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1870 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001871 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001872
1873 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001874 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
1876 }
1877
1878 // Make the SPIR-V type
1879 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001880 if (! HasNonLayoutQualifiers(qualifier))
1881 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001882
1883 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001884 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001885 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001886 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1887 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1888 int member = i;
1889 if (type.getBasicType() == glslang::EbtBlock)
1890 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001891
John Kesseniche0b6cad2015-12-24 10:30:13 -07001892 // modify just this child's view of the qualifier
1893 glslang::TQualifier subQualifier = glslangType.getQualifier();
1894 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001895
John Kessenich140f3df2015-06-26 16:58:36 -06001896 // using -1 above to indicate a hidden member
1897 if (member >= 0) {
1898 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001899 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001900 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
Rex Xubbceed72016-05-21 09:40:44 +08001901 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich9af54c32016-05-17 10:24:00 -06001902 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
scygan8add1512016-05-06 16:54:54 +02001903 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
Rex Xubbceed72016-05-21 09:40:44 +08001904 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(subQualifier));
scygan8add1512016-05-06 16:54:54 +02001905 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001906 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001907
Rex Xu1da878f2016-02-21 20:59:01 +08001908 if (qualifier.storage == glslang::EvqBuffer) {
1909 std::vector<spv::Decoration> memory;
1910 TranslateMemoryDecoration(subQualifier, memory);
1911 for (unsigned int i = 0; i < memory.size(); ++i)
1912 addMemberDecoration(spvType, member, memory[i]);
1913 }
1914
John Kessenich09677482016-02-19 12:21:50 -07001915 // compute location decoration; tricky based on whether inheritance is at play
1916 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1917 // probably move to the linker stage of the front end proper, and just have the
1918 // answer sitting already distributed throughout the individual member locations.
1919 int location = -1; // will only decorate if present or inherited
John Kessenich9af54c32016-05-17 10:24:00 -06001920 if (subQualifier.hasLocation()) { // no inheritance, or override of inheritance
scygan8add1512016-05-06 16:54:54 +02001921 // struct members should not have explicit locations
1922 assert(type.getBasicType() != glslang::EbtStruct);
John Kessenich09677482016-02-19 12:21:50 -07001923 location = subQualifier.layoutLocation;
John Kessenich9af54c32016-05-17 10:24:00 -06001924 } else if (type.getBasicType() != glslang::EbtBlock) {
scygan8add1512016-05-06 16:54:54 +02001925 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
1926 // The members, and their nested types, must not themselves have Location decorations.
1927 }
John Kessenich09677482016-02-19 12:21:50 -07001928 else if (qualifier.hasLocation()) // inheritance
1929 location = qualifier.layoutLocation + locationOffset;
1930 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001931 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001932 if (location >= 0)
1933 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1934
1935 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001936 if (glslangType.getQualifier().hasComponent())
1937 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1938 if (glslangType.getQualifier().hasXfbOffset())
1939 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001940 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001941 // figure out what to do with offset, which is accumulating
1942 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001943 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001944 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001945 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001946 offset = nextOffset;
1947 }
John Kessenich140f3df2015-06-26 16:58:36 -06001948
John Kessenichf85e8062015-12-19 13:57:10 -07001949 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001950 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001951
John Kessenich140f3df2015-06-26 16:58:36 -06001952 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06001953 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn, true);
John Kessenich30669532015-08-06 22:02:24 -06001954 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001955 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001956 }
1957 }
1958
1959 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001960 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001961 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001962 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001963 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001964 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001965 }
John Kessenich140f3df2015-06-26 16:58:36 -06001966 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001967 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001968 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001969 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001970 if (type.getQualifier().hasXfbBuffer())
1971 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1972 }
1973 }
1974 break;
1975 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001976 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001977 break;
1978 }
1979
1980 if (type.isMatrix())
1981 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1982 else {
1983 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1984 if (type.getVectorSize() > 1)
1985 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1986 }
1987
1988 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001989 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1990
John Kessenichc9a80832015-09-12 12:17:44 -06001991 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001992 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001993 // We need to decorate array strides for types needing explicit layout, except blocks.
1994 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001995 // Use a dummy glslang type for querying internal strides of
1996 // arrays of arrays, but using just a one-dimensional array.
1997 glslang::TType simpleArrayType(type, 0); // deference type of the array
1998 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1999 simpleArrayType.getArraySizes().dereference();
2000
2001 // Will compute the higher-order strides here, rather than making a whole
2002 // pile of types and doing repetitive recursion on their contents.
2003 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2004 }
John Kessenichf8842e52016-01-04 19:22:56 -07002005
2006 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002007 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002008 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002009 if (stride > 0)
2010 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002011 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002012 }
2013 } else {
2014 // single-dimensional array, and don't yet have stride
2015
John Kessenichf8842e52016-01-04 19:22:56 -07002016 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002017 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2018 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002019 }
John Kessenich31ed4832015-09-09 17:51:38 -06002020
John Kessenichc9a80832015-09-12 12:17:44 -06002021 // Do the outer dimension, which might not be known for a runtime-sized array
2022 if (type.isRuntimeSizedArray()) {
2023 spvType = builder.makeRuntimeArray(spvType);
2024 } else {
2025 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002026 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002027 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002028 if (stride > 0)
2029 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002030 }
2031
2032 return spvType;
2033}
2034
John Kessenich6c292d32016-02-15 20:58:50 -07002035// Turn the expression forming the array size into an id.
2036// This is not quite trivial, because of specialization constants.
2037// Sometimes, a raw constant is turned into an Id, and sometimes
2038// a specialization constant expression is.
2039spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2040{
2041 // First, see if this is sized with a node, meaning a specialization constant:
2042 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2043 if (specNode != nullptr) {
2044 builder.clearAccessChain();
2045 specNode->traverse(this);
2046 return accessChainLoad(specNode->getAsTyped()->getType());
2047 }
qining25262b32016-05-06 17:25:16 -04002048
John Kessenich6c292d32016-02-15 20:58:50 -07002049 // Otherwise, need a compile-time (front end) size, get it:
2050 int size = arraySizes.getDimSize(dim);
2051 assert(size > 0);
2052 return builder.makeUintConstant(size);
2053}
2054
John Kessenich103bef92016-02-08 21:38:15 -07002055// Wrap the builder's accessChainLoad to:
2056// - localize handling of RelaxedPrecision
2057// - use the SPIR-V inferred type instead of another conversion of the glslang type
2058// (avoids unnecessary work and possible type punning for structures)
2059// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002060spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2061{
John Kessenich103bef92016-02-08 21:38:15 -07002062 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2063 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2064
2065 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002066 if (type.getBasicType() == glslang::EbtBool) {
2067 if (builder.isScalarType(nominalTypeId)) {
2068 // Conversion for bool
2069 spv::Id boolType = builder.makeBoolType();
2070 if (nominalTypeId != boolType)
2071 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2072 } else if (builder.isVectorType(nominalTypeId)) {
2073 // Conversion for bvec
2074 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2075 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2076 if (nominalTypeId != bvecType)
2077 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2078 }
2079 }
John Kessenich103bef92016-02-08 21:38:15 -07002080
2081 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002082}
2083
Rex Xu27253232016-02-23 17:51:09 +08002084// Wrap the builder's accessChainStore to:
2085// - do conversion of concrete to abstract type
2086void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2087{
2088 // Need to convert to abstract types when necessary
2089 if (type.getBasicType() == glslang::EbtBool) {
2090 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2091
2092 if (builder.isScalarType(nominalTypeId)) {
2093 // Conversion for bool
2094 spv::Id boolType = builder.makeBoolType();
2095 if (nominalTypeId != boolType) {
2096 spv::Id zero = builder.makeUintConstant(0);
2097 spv::Id one = builder.makeUintConstant(1);
2098 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2099 }
2100 } else if (builder.isVectorType(nominalTypeId)) {
2101 // Conversion for bvec
2102 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2103 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2104 if (nominalTypeId != bvecType) {
2105 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2106 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2107 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2108 }
2109 }
2110 }
2111
2112 builder.accessChainStore(rvalue);
2113}
2114
John Kessenichf85e8062015-12-19 13:57:10 -07002115// Decide whether or not this type should be
2116// decorated with offsets and strides, and if so
2117// whether std140 or std430 rules should be applied.
2118glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002119{
John Kessenichf85e8062015-12-19 13:57:10 -07002120 // has to be a block
2121 if (type.getBasicType() != glslang::EbtBlock)
2122 return glslang::ElpNone;
2123
2124 // has to be a uniform or buffer block
2125 if (type.getQualifier().storage != glslang::EvqUniform &&
2126 type.getQualifier().storage != glslang::EvqBuffer)
2127 return glslang::ElpNone;
2128
2129 // return the layout to use
2130 switch (type.getQualifier().layoutPacking) {
2131 case glslang::ElpStd140:
2132 case glslang::ElpStd430:
2133 return type.getQualifier().layoutPacking;
2134 default:
2135 return glslang::ElpNone;
2136 }
John Kessenich31ed4832015-09-09 17:51:38 -06002137}
2138
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002139// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002140int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002141{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002142 int size;
John Kessenich49987892015-12-29 17:11:44 -07002143 int stride;
2144 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002145
2146 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002147}
2148
John Kessenich49987892015-12-29 17:11:44 -07002149// 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 -07002150// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002151int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002152{
John Kessenich49987892015-12-29 17:11:44 -07002153 glslang::TType elementType;
2154 elementType.shallowCopy(matrixType);
2155 elementType.clearArraySizes();
2156
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002157 int size;
John Kessenich49987892015-12-29 17:11:44 -07002158 int stride;
2159 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2160
2161 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002162}
2163
John Kessenich5e4b1242015-08-06 22:53:06 -06002164// Given a member type of a struct, realign the current offset for it, and compute
2165// the next (not yet aligned) offset for the next member, which will get aligned
2166// on the next call.
2167// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2168// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2169// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002170void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002171 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002172{
2173 // this will get a positive value when deemed necessary
2174 nextOffset = -1;
2175
John Kessenich5e4b1242015-08-06 22:53:06 -06002176 // override anything in currentOffset with user-set offset
2177 if (memberType.getQualifier().hasOffset())
2178 currentOffset = memberType.getQualifier().layoutOffset;
2179
2180 // It could be that current linker usage in glslang updated all the layoutOffset,
2181 // in which case the following code does not matter. But, that's not quite right
2182 // once cross-compilation unit GLSL validation is done, as the original user
2183 // settings are needed in layoutOffset, and then the following will come into play.
2184
John Kessenichf85e8062015-12-19 13:57:10 -07002185 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002186 if (! memberType.getQualifier().hasOffset())
2187 currentOffset = -1;
2188
2189 return;
2190 }
2191
John Kessenichf85e8062015-12-19 13:57:10 -07002192 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002193 if (currentOffset < 0)
2194 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002195
John Kessenich5e4b1242015-08-06 22:53:06 -06002196 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2197 // but possibly not yet correctly aligned.
2198
2199 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002200 int dummyStride;
2201 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002202 glslang::RoundToPow2(currentOffset, memberAlignment);
2203 nextOffset = currentOffset + memberSize;
2204}
2205
John Kessenichebb50532016-05-16 19:22:05 -06002206void TGlslangToSpvTraverser::declareClipCullCapability(const glslang::TTypeList& members, int member)
2207{
2208 if (members[member].type->getQualifier().builtIn == glslang::EbvClipDistance)
2209 builder.addCapability(spv::CapabilityClipDistance);
2210 if (members[member].type->getQualifier().builtIn == glslang::EbvCullDistance)
2211 builder.addCapability(spv::CapabilityCullDistance);
2212}
2213
John Kessenich140f3df2015-06-26 16:58:36 -06002214bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2215{
John Kessenich4d65ee32016-03-12 18:17:47 -07002216 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002217 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002218 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002219}
2220
2221// Make all the functions, skeletally, without actually visiting their bodies.
2222void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2223{
2224 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2225 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2226 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2227 continue;
2228
2229 // We're on a user function. Set up the basic interface for the function now,
2230 // so that it's available to call.
2231 // Translating the body will happen later.
2232 //
qining25262b32016-05-06 17:25:16 -04002233 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002234 // function. What it is an address of varies:
2235 //
2236 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2237 // so that write needs to be to a copy, hence the address of a copy works.
2238 //
2239 // - "const in" parameters can just be the r-value, as no writes need occur.
2240 //
2241 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2242 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2243
2244 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002245 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002246 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2247
2248 for (int p = 0; p < (int)parameters.size(); ++p) {
2249 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2250 spv::Id typeId = convertGlslangToSpvType(paramType);
2251 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2252 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2253 else
2254 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002255 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002256 paramTypes.push_back(typeId);
2257 }
2258
2259 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002260 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2261 convertGlslangToSpvType(glslFunction->getType()),
2262 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002263
2264 // Track function to emit/call later
2265 functionMap[glslFunction->getName().c_str()] = function;
2266
2267 // Set the parameter id's
2268 for (int p = 0; p < (int)parameters.size(); ++p) {
2269 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2270 // give a name too
2271 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2272 }
2273 }
2274}
2275
2276// Process all the initializers, while skipping the functions and link objects
2277void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2278{
2279 builder.setBuildPoint(shaderEntry->getLastBlock());
2280 for (int i = 0; i < (int)initializers.size(); ++i) {
2281 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2282 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2283
2284 // We're on a top-level node that's not a function. Treat as an initializer, whose
2285 // code goes into the beginning of main.
2286 initializer->traverse(this);
2287 }
2288 }
2289}
2290
2291// Process all the functions, while skipping initializers.
2292void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2293{
2294 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2295 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2296 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2297 node->traverse(this);
2298 }
2299}
2300
2301void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2302{
qining25262b32016-05-06 17:25:16 -04002303 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002304 // that called makeFunctions().
2305 spv::Function* function = functionMap[node->getName().c_str()];
2306 spv::Block* functionBlock = function->getEntryBlock();
2307 builder.setBuildPoint(functionBlock);
2308}
2309
Rex Xu04db3f52015-09-16 11:44:02 +08002310void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002311{
Rex Xufc618912015-09-09 16:42:49 +08002312 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002313
2314 glslang::TSampler sampler = {};
2315 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002316 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002317 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2318 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2319 }
2320
John Kessenich140f3df2015-06-26 16:58:36 -06002321 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2322 builder.clearAccessChain();
2323 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002324
2325 // Special case l-value operands
2326 bool lvalue = false;
2327 switch (node.getOp()) {
2328 case glslang::EOpImageAtomicAdd:
2329 case glslang::EOpImageAtomicMin:
2330 case glslang::EOpImageAtomicMax:
2331 case glslang::EOpImageAtomicAnd:
2332 case glslang::EOpImageAtomicOr:
2333 case glslang::EOpImageAtomicXor:
2334 case glslang::EOpImageAtomicExchange:
2335 case glslang::EOpImageAtomicCompSwap:
2336 if (i == 0)
2337 lvalue = true;
2338 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002339 case glslang::EOpSparseImageLoad:
2340 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2341 lvalue = true;
2342 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002343 case glslang::EOpSparseTexture:
2344 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2345 lvalue = true;
2346 break;
2347 case glslang::EOpSparseTextureClamp:
2348 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2349 lvalue = true;
2350 break;
2351 case glslang::EOpSparseTextureLod:
2352 case glslang::EOpSparseTextureOffset:
2353 if (i == 3)
2354 lvalue = true;
2355 break;
2356 case glslang::EOpSparseTextureFetch:
2357 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2358 lvalue = true;
2359 break;
2360 case glslang::EOpSparseTextureFetchOffset:
2361 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2362 lvalue = true;
2363 break;
2364 case glslang::EOpSparseTextureLodOffset:
2365 case glslang::EOpSparseTextureGrad:
2366 case glslang::EOpSparseTextureOffsetClamp:
2367 if (i == 4)
2368 lvalue = true;
2369 break;
2370 case glslang::EOpSparseTextureGradOffset:
2371 case glslang::EOpSparseTextureGradClamp:
2372 if (i == 5)
2373 lvalue = true;
2374 break;
2375 case glslang::EOpSparseTextureGradOffsetClamp:
2376 if (i == 6)
2377 lvalue = true;
2378 break;
2379 case glslang::EOpSparseTextureGather:
2380 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2381 lvalue = true;
2382 break;
2383 case glslang::EOpSparseTextureGatherOffset:
2384 case glslang::EOpSparseTextureGatherOffsets:
2385 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2386 lvalue = true;
2387 break;
Rex Xufc618912015-09-09 16:42:49 +08002388 default:
2389 break;
2390 }
2391
Rex Xu6b86d492015-09-16 17:48:22 +08002392 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002393 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002394 else
John Kessenich32cfd492016-02-02 12:37:46 -07002395 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002396 }
2397}
2398
John Kessenichfc51d282015-08-19 13:34:18 -06002399void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002400{
John Kessenichfc51d282015-08-19 13:34:18 -06002401 builder.clearAccessChain();
2402 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002403 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002404}
John Kessenich140f3df2015-06-26 16:58:36 -06002405
John Kessenichfc51d282015-08-19 13:34:18 -06002406spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2407{
Rex Xufc618912015-09-09 16:42:49 +08002408 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002409 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002410 }
2411
John Kessenichfc51d282015-08-19 13:34:18 -06002412 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002413 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2414 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2415 std::vector<spv::Id> arguments;
2416 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002417 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002418 else
2419 translateArguments(*node->getAsUnaryNode(), arguments);
2420 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2421
2422 spv::Builder::TextureParameters params = { };
2423 params.sampler = arguments[0];
2424
Rex Xu04db3f52015-09-16 11:44:02 +08002425 glslang::TCrackedTextureOp cracked;
2426 node->crackTexture(sampler, cracked);
2427
John Kessenichfc51d282015-08-19 13:34:18 -06002428 // Check for queries
2429 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002430 // a sampled image needs to have the image extracted first
2431 if (builder.isSampledImage(params.sampler))
2432 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002433 switch (node->getOp()) {
2434 case glslang::EOpImageQuerySize:
2435 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002436 if (arguments.size() > 1) {
2437 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002438 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002439 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002440 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002441 case glslang::EOpImageQuerySamples:
2442 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002443 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002444 case glslang::EOpTextureQueryLod:
2445 params.coords = arguments[1];
2446 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2447 case glslang::EOpTextureQueryLevels:
2448 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002449 case glslang::EOpSparseTexelsResident:
2450 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002451 default:
2452 assert(0);
2453 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 }
John Kessenich140f3df2015-06-26 16:58:36 -06002455 }
2456
Rex Xufc618912015-09-09 16:42:49 +08002457 // Check for image functions other than queries
2458 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002459 std::vector<spv::Id> operands;
2460 auto opIt = arguments.begin();
2461 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002462
2463 // Handle subpass operations
2464 // TODO: GLSL should change to have the "MS" only on the type rather than the
2465 // built-in function.
2466 if (cracked.subpass) {
2467 // add on the (0,0) coordinate
2468 spv::Id zero = builder.makeIntConstant(0);
2469 std::vector<spv::Id> comps;
2470 comps.push_back(zero);
2471 comps.push_back(zero);
2472 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2473 if (sampler.ms) {
2474 operands.push_back(spv::ImageOperandsSampleMask);
2475 operands.push_back(*(opIt++));
2476 }
2477 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2478 }
2479
John Kessenich56bab042015-09-16 10:54:31 -06002480 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002481 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002482 if (sampler.ms) {
2483 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002484 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002485 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002486 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2487 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002488 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002489 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002490 if (sampler.ms) {
2491 operands.push_back(*(opIt + 1));
2492 operands.push_back(spv::ImageOperandsSampleMask);
2493 operands.push_back(*opIt);
2494 } else
2495 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002496 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002497 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2498 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002499 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002500 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2501 builder.addCapability(spv::CapabilitySparseResidency);
2502 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2503 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2504
2505 if (sampler.ms) {
2506 operands.push_back(spv::ImageOperandsSampleMask);
2507 operands.push_back(*opIt++);
2508 }
2509
2510 // Create the return type that was a special structure
2511 spv::Id texelOut = *opIt;
2512 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2513 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2514 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2515
2516 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2517
2518 // Decode the return type
2519 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2520 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002521 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002522 // Process image atomic operations
2523
2524 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2525 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002526 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002527
Rex Xufc618912015-09-09 16:42:49 +08002528 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002529 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002530
2531 std::vector<spv::Id> operands;
2532 operands.push_back(pointer);
2533 for (; opIt != arguments.end(); ++opIt)
2534 operands.push_back(*opIt);
2535
Rex Xu04db3f52015-09-16 11:44:02 +08002536 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002537 }
2538 }
2539
2540 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002541 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002542 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2543
John Kessenichfc51d282015-08-19 13:34:18 -06002544 // check for bias argument
2545 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002546 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002547 int nonBiasArgCount = 2;
2548 if (cracked.offset)
2549 ++nonBiasArgCount;
2550 if (cracked.grad)
2551 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002552 if (cracked.lodClamp)
2553 ++nonBiasArgCount;
2554 if (sparse)
2555 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002556
2557 if ((int)arguments.size() > nonBiasArgCount)
2558 bias = true;
2559 }
2560
John Kessenichfc51d282015-08-19 13:34:18 -06002561 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002562
John Kessenichfc51d282015-08-19 13:34:18 -06002563 params.coords = arguments[1];
2564 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002565 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002566
2567 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002568 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002569 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002570 ++extraArgs;
2571 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002572 params.Dref = arguments[2];
2573 ++extraArgs;
2574 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002575 std::vector<spv::Id> indexes;
2576 int comp;
2577 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002578 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002579 else
2580 comp = builder.getNumComponents(params.coords) - 1;
2581 indexes.push_back(comp);
2582 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2583 }
2584 if (cracked.lod) {
2585 params.lod = arguments[2];
2586 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002587 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2588 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2589 noImplicitLod = true;
2590 }
2591 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002592 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002593 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002594 }
2595 if (cracked.grad) {
2596 params.gradX = arguments[2 + extraArgs];
2597 params.gradY = arguments[3 + extraArgs];
2598 extraArgs += 2;
2599 }
John Kessenich55e7d112015-11-15 21:33:39 -07002600 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002601 params.offset = arguments[2 + extraArgs];
2602 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002603 } else if (cracked.offsets) {
2604 params.offsets = arguments[2 + extraArgs];
2605 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002606 }
Rex Xu48edadf2015-12-31 16:11:41 +08002607 if (cracked.lodClamp) {
2608 params.lodClamp = arguments[2 + extraArgs];
2609 ++extraArgs;
2610 }
2611 if (sparse) {
2612 params.texelOut = arguments[2 + extraArgs];
2613 ++extraArgs;
2614 }
John Kessenichfc51d282015-08-19 13:34:18 -06002615 if (bias) {
2616 params.bias = arguments[2 + extraArgs];
2617 ++extraArgs;
2618 }
John Kessenich55e7d112015-11-15 21:33:39 -07002619 if (cracked.gather && ! sampler.shadow) {
2620 // default component is 0, if missing, otherwise an argument
2621 if (2 + extraArgs < (int)arguments.size()) {
2622 params.comp = arguments[2 + extraArgs];
2623 ++extraArgs;
2624 } else {
2625 params.comp = builder.makeIntConstant(0);
2626 }
2627 }
John Kessenichfc51d282015-08-19 13:34:18 -06002628
John Kessenich019f08f2016-02-15 15:40:42 -07002629 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002630}
2631
2632spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2633{
2634 // Grab the function's pointer from the previously created function
2635 spv::Function* function = functionMap[node->getName().c_str()];
2636 if (! function)
2637 return 0;
2638
2639 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2640 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2641
2642 // See comments in makeFunctions() for details about the semantics for parameter passing.
2643 //
2644 // These imply we need a four step process:
2645 // 1. Evaluate the arguments
2646 // 2. Allocate and make copies of in, out, and inout arguments
2647 // 3. Make the call
2648 // 4. Copy back the results
2649
2650 // 1. Evaluate the arguments
2651 std::vector<spv::Builder::AccessChain> lValues;
2652 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002653 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002654 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2655 // build l-value
2656 builder.clearAccessChain();
2657 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002658 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002659 // keep outputs as l-values, evaluate input-only as r-values
2660 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2661 // save l-value
2662 lValues.push_back(builder.getAccessChain());
2663 } else {
2664 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002665 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002666 }
2667 }
2668
2669 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2670 // copy the original into that space.
2671 //
2672 // Also, build up the list of actual arguments to pass in for the call
2673 int lValueCount = 0;
2674 int rValueCount = 0;
2675 std::vector<spv::Id> spvArgs;
2676 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2677 spv::Id arg;
2678 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2679 // need space to hold the copy
2680 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2681 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2682 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2683 // need to copy the input into output space
2684 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002685 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002686 builder.createStore(copy, arg);
2687 }
2688 ++lValueCount;
2689 } else {
2690 arg = rValues[rValueCount];
2691 ++rValueCount;
2692 }
2693 spvArgs.push_back(arg);
2694 }
2695
2696 // 3. Make the call.
2697 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002698 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002699
2700 // 4. Copy back out an "out" arguments.
2701 lValueCount = 0;
2702 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2703 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2704 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2705 spv::Id copy = builder.createLoad(spvArgs[a]);
2706 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002707 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002708 }
2709 ++lValueCount;
2710 }
2711 }
2712
2713 return result;
2714}
2715
2716// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002717spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2718 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002719 spv::Id typeId, spv::Id left, spv::Id right,
2720 glslang::TBasicType typeProxy, bool reduceComparison)
2721{
Rex Xu8ff43de2016-04-22 16:51:45 +08002722 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002723 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002724 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002725
2726 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002727 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002728 bool comparison = false;
2729
2730 switch (op) {
2731 case glslang::EOpAdd:
2732 case glslang::EOpAddAssign:
2733 if (isFloat)
2734 binOp = spv::OpFAdd;
2735 else
2736 binOp = spv::OpIAdd;
2737 break;
2738 case glslang::EOpSub:
2739 case glslang::EOpSubAssign:
2740 if (isFloat)
2741 binOp = spv::OpFSub;
2742 else
2743 binOp = spv::OpISub;
2744 break;
2745 case glslang::EOpMul:
2746 case glslang::EOpMulAssign:
2747 if (isFloat)
2748 binOp = spv::OpFMul;
2749 else
2750 binOp = spv::OpIMul;
2751 break;
2752 case glslang::EOpVectorTimesScalar:
2753 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002754 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002755 if (builder.isVector(right))
2756 std::swap(left, right);
2757 assert(builder.isScalar(right));
2758 needMatchingVectors = false;
2759 binOp = spv::OpVectorTimesScalar;
2760 } else
2761 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002762 break;
2763 case glslang::EOpVectorTimesMatrix:
2764 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002765 binOp = spv::OpVectorTimesMatrix;
2766 break;
2767 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002768 binOp = spv::OpMatrixTimesVector;
2769 break;
2770 case glslang::EOpMatrixTimesScalar:
2771 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002772 binOp = spv::OpMatrixTimesScalar;
2773 break;
2774 case glslang::EOpMatrixTimesMatrix:
2775 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002776 binOp = spv::OpMatrixTimesMatrix;
2777 break;
2778 case glslang::EOpOuterProduct:
2779 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002780 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002781 break;
2782
2783 case glslang::EOpDiv:
2784 case glslang::EOpDivAssign:
2785 if (isFloat)
2786 binOp = spv::OpFDiv;
2787 else if (isUnsigned)
2788 binOp = spv::OpUDiv;
2789 else
2790 binOp = spv::OpSDiv;
2791 break;
2792 case glslang::EOpMod:
2793 case glslang::EOpModAssign:
2794 if (isFloat)
2795 binOp = spv::OpFMod;
2796 else if (isUnsigned)
2797 binOp = spv::OpUMod;
2798 else
2799 binOp = spv::OpSMod;
2800 break;
2801 case glslang::EOpRightShift:
2802 case glslang::EOpRightShiftAssign:
2803 if (isUnsigned)
2804 binOp = spv::OpShiftRightLogical;
2805 else
2806 binOp = spv::OpShiftRightArithmetic;
2807 break;
2808 case glslang::EOpLeftShift:
2809 case glslang::EOpLeftShiftAssign:
2810 binOp = spv::OpShiftLeftLogical;
2811 break;
2812 case glslang::EOpAnd:
2813 case glslang::EOpAndAssign:
2814 binOp = spv::OpBitwiseAnd;
2815 break;
2816 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002817 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002818 binOp = spv::OpLogicalAnd;
2819 break;
2820 case glslang::EOpInclusiveOr:
2821 case glslang::EOpInclusiveOrAssign:
2822 binOp = spv::OpBitwiseOr;
2823 break;
2824 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002825 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002826 binOp = spv::OpLogicalOr;
2827 break;
2828 case glslang::EOpExclusiveOr:
2829 case glslang::EOpExclusiveOrAssign:
2830 binOp = spv::OpBitwiseXor;
2831 break;
2832 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002833 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002834 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002835 break;
2836
2837 case glslang::EOpLessThan:
2838 case glslang::EOpGreaterThan:
2839 case glslang::EOpLessThanEqual:
2840 case glslang::EOpGreaterThanEqual:
2841 case glslang::EOpEqual:
2842 case glslang::EOpNotEqual:
2843 case glslang::EOpVectorEqual:
2844 case glslang::EOpVectorNotEqual:
2845 comparison = true;
2846 break;
2847 default:
2848 break;
2849 }
2850
John Kessenich7c1aa102015-10-15 13:29:11 -06002851 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002852 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002853 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002854 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04002855 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002856
2857 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002858 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002859 builder.promoteScalar(precision, left, right);
2860
qining25262b32016-05-06 17:25:16 -04002861 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2862 addDecoration(result, noContraction);
2863 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002864 }
2865
2866 if (! comparison)
2867 return 0;
2868
John Kessenich7c1aa102015-10-15 13:29:11 -06002869 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002870
2871 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2872 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2873
John Kessenich22118352015-12-21 20:54:09 -07002874 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002875 }
2876
2877 switch (op) {
2878 case glslang::EOpLessThan:
2879 if (isFloat)
2880 binOp = spv::OpFOrdLessThan;
2881 else if (isUnsigned)
2882 binOp = spv::OpULessThan;
2883 else
2884 binOp = spv::OpSLessThan;
2885 break;
2886 case glslang::EOpGreaterThan:
2887 if (isFloat)
2888 binOp = spv::OpFOrdGreaterThan;
2889 else if (isUnsigned)
2890 binOp = spv::OpUGreaterThan;
2891 else
2892 binOp = spv::OpSGreaterThan;
2893 break;
2894 case glslang::EOpLessThanEqual:
2895 if (isFloat)
2896 binOp = spv::OpFOrdLessThanEqual;
2897 else if (isUnsigned)
2898 binOp = spv::OpULessThanEqual;
2899 else
2900 binOp = spv::OpSLessThanEqual;
2901 break;
2902 case glslang::EOpGreaterThanEqual:
2903 if (isFloat)
2904 binOp = spv::OpFOrdGreaterThanEqual;
2905 else if (isUnsigned)
2906 binOp = spv::OpUGreaterThanEqual;
2907 else
2908 binOp = spv::OpSGreaterThanEqual;
2909 break;
2910 case glslang::EOpEqual:
2911 case glslang::EOpVectorEqual:
2912 if (isFloat)
2913 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002914 else if (isBool)
2915 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002916 else
2917 binOp = spv::OpIEqual;
2918 break;
2919 case glslang::EOpNotEqual:
2920 case glslang::EOpVectorNotEqual:
2921 if (isFloat)
2922 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002923 else if (isBool)
2924 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002925 else
2926 binOp = spv::OpINotEqual;
2927 break;
2928 default:
2929 break;
2930 }
2931
qining25262b32016-05-06 17:25:16 -04002932 if (binOp != spv::OpNop) {
2933 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
2934 addDecoration(result, noContraction);
2935 return builder.setPrecision(result, precision);
2936 }
John Kessenich140f3df2015-06-26 16:58:36 -06002937
2938 return 0;
2939}
2940
John Kessenich04bb8a02015-12-12 12:28:14 -07002941//
2942// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2943// These can be any of:
2944//
2945// matrix * scalar
2946// scalar * matrix
2947// matrix * matrix linear algebraic
2948// matrix * vector
2949// vector * matrix
2950// matrix * matrix componentwise
2951// matrix op matrix op in {+, -, /}
2952// matrix op scalar op in {+, -, /}
2953// scalar op matrix op in {+, -, /}
2954//
qining25262b32016-05-06 17:25:16 -04002955spv::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 -07002956{
2957 bool firstClass = true;
2958
2959 // First, handle first-class matrix operations (* and matrix/scalar)
2960 switch (op) {
2961 case spv::OpFDiv:
2962 if (builder.isMatrix(left) && builder.isScalar(right)) {
2963 // turn matrix / scalar into a multiply...
2964 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2965 op = spv::OpMatrixTimesScalar;
2966 } else
2967 firstClass = false;
2968 break;
2969 case spv::OpMatrixTimesScalar:
2970 if (builder.isMatrix(right))
2971 std::swap(left, right);
2972 assert(builder.isScalar(right));
2973 break;
2974 case spv::OpVectorTimesMatrix:
2975 assert(builder.isVector(left));
2976 assert(builder.isMatrix(right));
2977 break;
2978 case spv::OpMatrixTimesVector:
2979 assert(builder.isMatrix(left));
2980 assert(builder.isVector(right));
2981 break;
2982 case spv::OpMatrixTimesMatrix:
2983 assert(builder.isMatrix(left));
2984 assert(builder.isMatrix(right));
2985 break;
2986 default:
2987 firstClass = false;
2988 break;
2989 }
2990
qining25262b32016-05-06 17:25:16 -04002991 if (firstClass) {
2992 spv::Id result = builder.createBinOp(op, typeId, left, right);
2993 addDecoration(result, noContraction);
2994 return builder.setPrecision(result, precision);
2995 }
John Kessenich04bb8a02015-12-12 12:28:14 -07002996
2997 // Handle component-wise +, -, *, and / for all combinations of type.
2998 // The result type of all of them is the same type as the (a) matrix operand.
2999 // The algorithm is to:
3000 // - break the matrix(es) into vectors
3001 // - smear any scalar to a vector
3002 // - do vector operations
3003 // - make a matrix out the vector results
3004 switch (op) {
3005 case spv::OpFAdd:
3006 case spv::OpFSub:
3007 case spv::OpFDiv:
3008 case spv::OpFMul:
3009 {
3010 // one time set up...
3011 bool leftMat = builder.isMatrix(left);
3012 bool rightMat = builder.isMatrix(right);
3013 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3014 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3015 spv::Id scalarType = builder.getScalarTypeId(typeId);
3016 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3017 std::vector<spv::Id> results;
3018 spv::Id smearVec = spv::NoResult;
3019 if (builder.isScalar(left))
3020 smearVec = builder.smearScalar(precision, left, vecType);
3021 else if (builder.isScalar(right))
3022 smearVec = builder.smearScalar(precision, right, vecType);
3023
3024 // do each vector op
3025 for (unsigned int c = 0; c < numCols; ++c) {
3026 std::vector<unsigned int> indexes;
3027 indexes.push_back(c);
3028 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3029 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003030 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3031 addDecoration(result, noContraction);
3032 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003033 }
3034
3035 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003036 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003037 }
3038 default:
3039 assert(0);
3040 return spv::NoResult;
3041 }
3042}
3043
qining25262b32016-05-06 17:25:16 -04003044spv::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 -06003045{
3046 spv::Op unaryOp = spv::OpNop;
3047 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003048 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003049 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003050
3051 switch (op) {
3052 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003053 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003054 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003055 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003056 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003057 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003058 unaryOp = spv::OpSNegate;
3059 break;
3060
3061 case glslang::EOpLogicalNot:
3062 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003063 unaryOp = spv::OpLogicalNot;
3064 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003065 case glslang::EOpBitwiseNot:
3066 unaryOp = spv::OpNot;
3067 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003068
John Kessenich140f3df2015-06-26 16:58:36 -06003069 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003070 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003071 break;
3072 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003073 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003074 break;
3075 case glslang::EOpTranspose:
3076 unaryOp = spv::OpTranspose;
3077 break;
3078
3079 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003080 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003081 break;
3082 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003083 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003084 break;
3085 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 break;
3088 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003089 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003090 break;
3091 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003095 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
3097 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003098 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003099 break;
3100 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003101 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003102 break;
3103
3104 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003105 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003106 break;
3107 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003108 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003109 break;
3110 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003111 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003112 break;
3113 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003114 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003115 break;
3116 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003118 break;
3119 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122
3123 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003124 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003125 break;
3126 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003127 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003128 break;
3129
3130 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003131 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003132 break;
3133 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003134 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003135 break;
3136 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003137 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 break;
3139 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003140 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003141 break;
3142 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003143 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003144 break;
3145 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003146 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003147 break;
3148
3149 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003150 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003151 break;
3152 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 break;
3155 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003156 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003157 break;
3158 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003159 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003160 break;
3161 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003162 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167
3168 case glslang::EOpIsNan:
3169 unaryOp = spv::OpIsNan;
3170 break;
3171 case glslang::EOpIsInf:
3172 unaryOp = spv::OpIsInf;
3173 break;
3174
Rex Xucbc426e2015-12-15 16:03:10 +08003175 case glslang::EOpFloatBitsToInt:
3176 case glslang::EOpFloatBitsToUint:
3177 case glslang::EOpIntBitsToFloat:
3178 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003179 case glslang::EOpDoubleBitsToInt64:
3180 case glslang::EOpDoubleBitsToUint64:
3181 case glslang::EOpInt64BitsToDouble:
3182 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003183 unaryOp = spv::OpBitcast;
3184 break;
3185
John Kessenich140f3df2015-06-26 16:58:36 -06003186 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003187 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003188 break;
3189 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
3195 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003196 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003197 break;
3198 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003200 break;
3201 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003202 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003204 case glslang::EOpPackSnorm4x8:
3205 libCall = spv::GLSLstd450PackSnorm4x8;
3206 break;
3207 case glslang::EOpUnpackSnorm4x8:
3208 libCall = spv::GLSLstd450UnpackSnorm4x8;
3209 break;
3210 case glslang::EOpPackUnorm4x8:
3211 libCall = spv::GLSLstd450PackUnorm4x8;
3212 break;
3213 case glslang::EOpUnpackUnorm4x8:
3214 libCall = spv::GLSLstd450UnpackUnorm4x8;
3215 break;
3216 case glslang::EOpPackDouble2x32:
3217 libCall = spv::GLSLstd450PackDouble2x32;
3218 break;
3219 case glslang::EOpUnpackDouble2x32:
3220 libCall = spv::GLSLstd450UnpackDouble2x32;
3221 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003222
Rex Xu8ff43de2016-04-22 16:51:45 +08003223 case glslang::EOpPackInt2x32:
3224 case glslang::EOpUnpackInt2x32:
3225 case glslang::EOpPackUint2x32:
3226 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003227 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003228 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3229 break;
3230
John Kessenich140f3df2015-06-26 16:58:36 -06003231 case glslang::EOpDPdx:
3232 unaryOp = spv::OpDPdx;
3233 break;
3234 case glslang::EOpDPdy:
3235 unaryOp = spv::OpDPdy;
3236 break;
3237 case glslang::EOpFwidth:
3238 unaryOp = spv::OpFwidth;
3239 break;
3240 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003241 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003242 unaryOp = spv::OpDPdxFine;
3243 break;
3244 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003245 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003246 unaryOp = spv::OpDPdyFine;
3247 break;
3248 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003249 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003250 unaryOp = spv::OpFwidthFine;
3251 break;
3252 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003253 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003254 unaryOp = spv::OpDPdxCoarse;
3255 break;
3256 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003257 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003258 unaryOp = spv::OpDPdyCoarse;
3259 break;
3260 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003261 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003262 unaryOp = spv::OpFwidthCoarse;
3263 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003264 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003265 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003266 libCall = spv::GLSLstd450InterpolateAtCentroid;
3267 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003268 case glslang::EOpAny:
3269 unaryOp = spv::OpAny;
3270 break;
3271 case glslang::EOpAll:
3272 unaryOp = spv::OpAll;
3273 break;
3274
3275 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003276 if (isFloat)
3277 libCall = spv::GLSLstd450FAbs;
3278 else
3279 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003280 break;
3281 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003282 if (isFloat)
3283 libCall = spv::GLSLstd450FSign;
3284 else
3285 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003286 break;
3287
John Kessenichfc51d282015-08-19 13:34:18 -06003288 case glslang::EOpAtomicCounterIncrement:
3289 case glslang::EOpAtomicCounterDecrement:
3290 case glslang::EOpAtomicCounter:
3291 {
3292 // Handle all of the atomics in one place, in createAtomicOperation()
3293 std::vector<spv::Id> operands;
3294 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003295 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003296 }
3297
John Kessenichfc51d282015-08-19 13:34:18 -06003298 case glslang::EOpBitFieldReverse:
3299 unaryOp = spv::OpBitReverse;
3300 break;
3301 case glslang::EOpBitCount:
3302 unaryOp = spv::OpBitCount;
3303 break;
3304 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003305 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003306 break;
3307 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003308 if (isUnsigned)
3309 libCall = spv::GLSLstd450FindUMsb;
3310 else
3311 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003312 break;
3313
Rex Xu574ab042016-04-14 16:53:07 +08003314 case glslang::EOpBallot:
3315 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003316 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003317 libCall = spv::GLSLstd450Bad;
3318 break;
3319
Rex Xu338b1852016-05-05 20:38:33 +08003320 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003321 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003322 case glslang::EOpAllInvocationsEqual:
John Kessenich91cef522016-05-05 16:45:40 -06003323 return createInvocationsOperation(op, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003324
John Kessenich140f3df2015-06-26 16:58:36 -06003325 default:
3326 return 0;
3327 }
3328
3329 spv::Id id;
3330 if (libCall >= 0) {
3331 std::vector<spv::Id> args;
3332 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003333 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003334 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003335 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003336 }
John Kessenich140f3df2015-06-26 16:58:36 -06003337
qining25262b32016-05-06 17:25:16 -04003338 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003339 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003340}
3341
John Kessenich7a53f762016-01-20 11:19:27 -07003342// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003343spv::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 -07003344{
3345 // Handle unary operations vector by vector.
3346 // The result type is the same type as the original type.
3347 // The algorithm is to:
3348 // - break the matrix into vectors
3349 // - apply the operation to each vector
3350 // - make a matrix out the vector results
3351
3352 // get the types sorted out
3353 int numCols = builder.getNumColumns(operand);
3354 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003355 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3356 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003357 std::vector<spv::Id> results;
3358
3359 // do each vector op
3360 for (int c = 0; c < numCols; ++c) {
3361 std::vector<unsigned int> indexes;
3362 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003363 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3364 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3365 addDecoration(destVec, noContraction);
3366 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003367 }
3368
3369 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003370 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003371}
3372
Rex Xu73e3ce72016-04-27 18:48:17 +08003373spv::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 -06003374{
3375 spv::Op convOp = spv::OpNop;
3376 spv::Id zero = 0;
3377 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003378 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003379
3380 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3381
3382 switch (op) {
3383 case glslang::EOpConvIntToBool:
3384 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003385 case glslang::EOpConvInt64ToBool:
3386 case glslang::EOpConvUint64ToBool:
3387 zero = (op == glslang::EOpConvInt64ToBool ||
3388 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003389 zero = makeSmearedConstant(zero, vectorSize);
3390 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3391
3392 case glslang::EOpConvFloatToBool:
3393 zero = builder.makeFloatConstant(0.0F);
3394 zero = makeSmearedConstant(zero, vectorSize);
3395 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3396
3397 case glslang::EOpConvDoubleToBool:
3398 zero = builder.makeDoubleConstant(0.0);
3399 zero = makeSmearedConstant(zero, vectorSize);
3400 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3401
3402 case glslang::EOpConvBoolToFloat:
3403 convOp = spv::OpSelect;
3404 zero = builder.makeFloatConstant(0.0);
3405 one = builder.makeFloatConstant(1.0);
3406 break;
3407 case glslang::EOpConvBoolToDouble:
3408 convOp = spv::OpSelect;
3409 zero = builder.makeDoubleConstant(0.0);
3410 one = builder.makeDoubleConstant(1.0);
3411 break;
3412 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003413 case glslang::EOpConvBoolToInt64:
3414 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3415 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003416 convOp = spv::OpSelect;
3417 break;
3418 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003419 case glslang::EOpConvBoolToUint64:
3420 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3421 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003422 convOp = spv::OpSelect;
3423 break;
3424
3425 case glslang::EOpConvIntToFloat:
3426 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003427 case glslang::EOpConvInt64ToFloat:
3428 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003429 convOp = spv::OpConvertSToF;
3430 break;
3431
3432 case glslang::EOpConvUintToFloat:
3433 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003434 case glslang::EOpConvUint64ToFloat:
3435 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003436 convOp = spv::OpConvertUToF;
3437 break;
3438
3439 case glslang::EOpConvDoubleToFloat:
3440 case glslang::EOpConvFloatToDouble:
3441 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003442 if (builder.isMatrixType(destType))
3443 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003444 break;
3445
3446 case glslang::EOpConvFloatToInt:
3447 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003448 case glslang::EOpConvFloatToInt64:
3449 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003450 convOp = spv::OpConvertFToS;
3451 break;
3452
3453 case glslang::EOpConvUintToInt:
3454 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003455 case glslang::EOpConvUint64ToInt64:
3456 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003457 if (builder.isInSpecConstCodeGenMode()) {
3458 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003459 zero = (op == glslang::EOpConvUintToInt64 ||
3460 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003461 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003462 // Use OpIAdd, instead of OpBitcast to do the conversion when
3463 // generating for OpSpecConstantOp instruction.
3464 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3465 }
3466 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003467 convOp = spv::OpBitcast;
3468 break;
3469
3470 case glslang::EOpConvFloatToUint:
3471 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003472 case glslang::EOpConvFloatToUint64:
3473 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003474 convOp = spv::OpConvertFToU;
3475 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003476
3477 case glslang::EOpConvIntToInt64:
3478 case glslang::EOpConvInt64ToInt:
3479 convOp = spv::OpSConvert;
3480 break;
3481
3482 case glslang::EOpConvUintToUint64:
3483 case glslang::EOpConvUint64ToUint:
3484 convOp = spv::OpUConvert;
3485 break;
3486
3487 case glslang::EOpConvIntToUint64:
3488 case glslang::EOpConvInt64ToUint:
3489 case glslang::EOpConvUint64ToInt:
3490 case glslang::EOpConvUintToInt64:
3491 // OpSConvert/OpUConvert + OpBitCast
3492 switch (op) {
3493 case glslang::EOpConvIntToUint64:
3494 convOp = spv::OpSConvert;
3495 type = builder.makeIntType(64);
3496 break;
3497 case glslang::EOpConvInt64ToUint:
3498 convOp = spv::OpSConvert;
3499 type = builder.makeIntType(32);
3500 break;
3501 case glslang::EOpConvUint64ToInt:
3502 convOp = spv::OpUConvert;
3503 type = builder.makeUintType(32);
3504 break;
3505 case glslang::EOpConvUintToInt64:
3506 convOp = spv::OpUConvert;
3507 type = builder.makeUintType(64);
3508 break;
3509 default:
3510 assert(0);
3511 break;
3512 }
3513
3514 if (vectorSize > 0)
3515 type = builder.makeVectorType(type, vectorSize);
3516
3517 operand = builder.createUnaryOp(convOp, type, operand);
3518
3519 if (builder.isInSpecConstCodeGenMode()) {
3520 // Build zero scalar or vector for OpIAdd.
3521 zero = (op == glslang::EOpConvIntToUint64 ||
3522 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3523 zero = makeSmearedConstant(zero, vectorSize);
3524 // Use OpIAdd, instead of OpBitcast to do the conversion when
3525 // generating for OpSpecConstantOp instruction.
3526 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3527 }
3528 // For normal run-time conversion instruction, use OpBitcast.
3529 convOp = spv::OpBitcast;
3530 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003531 default:
3532 break;
3533 }
3534
3535 spv::Id result = 0;
3536 if (convOp == spv::OpNop)
3537 return result;
3538
3539 if (convOp == spv::OpSelect) {
3540 zero = makeSmearedConstant(zero, vectorSize);
3541 one = makeSmearedConstant(one, vectorSize);
3542 result = builder.createTriOp(convOp, destType, operand, one, zero);
3543 } else
3544 result = builder.createUnaryOp(convOp, destType, operand);
3545
John Kessenich32cfd492016-02-02 12:37:46 -07003546 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003547}
3548
3549spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3550{
3551 if (vectorSize == 0)
3552 return constant;
3553
3554 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3555 std::vector<spv::Id> components;
3556 for (int c = 0; c < vectorSize; ++c)
3557 components.push_back(constant);
3558 return builder.makeCompositeConstant(vectorTypeId, components);
3559}
3560
John Kessenich426394d2015-07-23 10:22:48 -06003561// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003562spv::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 -06003563{
3564 spv::Op opCode = spv::OpNop;
3565
3566 switch (op) {
3567 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003568 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003569 opCode = spv::OpAtomicIAdd;
3570 break;
3571 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003572 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003573 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003574 break;
3575 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003576 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003577 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003578 break;
3579 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003580 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003581 opCode = spv::OpAtomicAnd;
3582 break;
3583 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003584 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003585 opCode = spv::OpAtomicOr;
3586 break;
3587 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003588 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003589 opCode = spv::OpAtomicXor;
3590 break;
3591 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003592 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003593 opCode = spv::OpAtomicExchange;
3594 break;
3595 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003596 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003597 opCode = spv::OpAtomicCompareExchange;
3598 break;
3599 case glslang::EOpAtomicCounterIncrement:
3600 opCode = spv::OpAtomicIIncrement;
3601 break;
3602 case glslang::EOpAtomicCounterDecrement:
3603 opCode = spv::OpAtomicIDecrement;
3604 break;
3605 case glslang::EOpAtomicCounter:
3606 opCode = spv::OpAtomicLoad;
3607 break;
3608 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003609 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003610 break;
3611 }
3612
3613 // Sort out the operands
3614 // - mapping from glslang -> SPV
3615 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003616 // - compare-exchange swaps the value and comparator
3617 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003618 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3619 auto opIt = operands.begin(); // walk the glslang operands
3620 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003621 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3622 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3623 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003624 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3625 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003626 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003627 spvAtomicOperands.push_back(*(opIt + 1));
3628 spvAtomicOperands.push_back(*opIt);
3629 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003630 }
John Kessenich426394d2015-07-23 10:22:48 -06003631
John Kessenich3e60a6f2015-09-14 22:45:16 -06003632 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003633 for (; opIt != operands.end(); ++opIt)
3634 spvAtomicOperands.push_back(*opIt);
3635
3636 return builder.createOp(opCode, typeId, spvAtomicOperands);
3637}
3638
John Kessenich91cef522016-05-05 16:45:40 -06003639// Create group invocation operations.
3640spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand)
3641{
3642 builder.addCapability(spv::CapabilityGroups);
3643
3644 std::vector<spv::Id> operands;
3645 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
3646 operands.push_back(operand);
3647
3648 switch (op) {
3649 case glslang::EOpAnyInvocation:
3650 case glslang::EOpAllInvocations:
3651 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3652
3653 case glslang::EOpAllInvocationsEqual:
3654 {
3655 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3656 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3657
3658 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3659 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3660 }
3661 default:
3662 logger->missingFunctionality("invocation operation");
3663 return spv::NoResult;
3664 }
3665}
3666
John Kessenich5e4b1242015-08-06 22:53:06 -06003667spv::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 -06003668{
Rex Xu8ff43de2016-04-22 16:51:45 +08003669 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003670 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3671
John Kessenich140f3df2015-06-26 16:58:36 -06003672 spv::Op opCode = spv::OpNop;
3673 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003674 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003675 spv::Id typeId0 = 0;
3676 if (consumedOperands > 0)
3677 typeId0 = builder.getTypeId(operands[0]);
3678 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003679
3680 switch (op) {
3681 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003682 if (isFloat)
3683 libCall = spv::GLSLstd450FMin;
3684 else if (isUnsigned)
3685 libCall = spv::GLSLstd450UMin;
3686 else
3687 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003688 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003689 break;
3690 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003691 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003692 break;
3693 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003694 if (isFloat)
3695 libCall = spv::GLSLstd450FMax;
3696 else if (isUnsigned)
3697 libCall = spv::GLSLstd450UMax;
3698 else
3699 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003700 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003703 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003704 break;
3705 case glslang::EOpDot:
3706 opCode = spv::OpDot;
3707 break;
3708 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003709 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711
3712 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003713 if (isFloat)
3714 libCall = spv::GLSLstd450FClamp;
3715 else if (isUnsigned)
3716 libCall = spv::GLSLstd450UClamp;
3717 else
3718 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003719 builder.promoteScalar(precision, operands.front(), operands[1]);
3720 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003721 break;
3722 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003723 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3724 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003725 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003726 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003727 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003728 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003729 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003730 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003733 libCall = spv::GLSLstd450Step;
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::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003738 builder.promoteScalar(precision, operands[0], operands[2]);
3739 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003740 break;
3741
3742 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003743 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
3745 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003746 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
3748 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003749 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003750 break;
3751 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003752 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003757 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003758 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003759 libCall = spv::GLSLstd450InterpolateAtSample;
3760 break;
3761 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003762 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003763 libCall = spv::GLSLstd450InterpolateAtOffset;
3764 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003765 case glslang::EOpAddCarry:
3766 opCode = spv::OpIAddCarry;
3767 typeId = builder.makeStructResultType(typeId0, typeId0);
3768 consumedOperands = 2;
3769 break;
3770 case glslang::EOpSubBorrow:
3771 opCode = spv::OpISubBorrow;
3772 typeId = builder.makeStructResultType(typeId0, typeId0);
3773 consumedOperands = 2;
3774 break;
3775 case glslang::EOpUMulExtended:
3776 opCode = spv::OpUMulExtended;
3777 typeId = builder.makeStructResultType(typeId0, typeId0);
3778 consumedOperands = 2;
3779 break;
3780 case glslang::EOpIMulExtended:
3781 opCode = spv::OpSMulExtended;
3782 typeId = builder.makeStructResultType(typeId0, typeId0);
3783 consumedOperands = 2;
3784 break;
3785 case glslang::EOpBitfieldExtract:
3786 if (isUnsigned)
3787 opCode = spv::OpBitFieldUExtract;
3788 else
3789 opCode = spv::OpBitFieldSExtract;
3790 break;
3791 case glslang::EOpBitfieldInsert:
3792 opCode = spv::OpBitFieldInsert;
3793 break;
3794
3795 case glslang::EOpFma:
3796 libCall = spv::GLSLstd450Fma;
3797 break;
3798 case glslang::EOpFrexp:
3799 libCall = spv::GLSLstd450FrexpStruct;
3800 if (builder.getNumComponents(operands[0]) == 1)
3801 frexpIntType = builder.makeIntegerType(32, true);
3802 else
3803 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3804 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3805 consumedOperands = 1;
3806 break;
3807 case glslang::EOpLdexp:
3808 libCall = spv::GLSLstd450Ldexp;
3809 break;
3810
Rex Xu574ab042016-04-14 16:53:07 +08003811 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003812 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003813 libCall = spv::GLSLstd450Bad;
3814 break;
3815
John Kessenich140f3df2015-06-26 16:58:36 -06003816 default:
3817 return 0;
3818 }
3819
3820 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003821 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003822 // Use an extended instruction from the standard library.
3823 // Construct the call arguments, without modifying the original operands vector.
3824 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3825 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003826 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003827 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003828 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003829 case 0:
3830 // should all be handled by visitAggregate and createNoArgOperation
3831 assert(0);
3832 return 0;
3833 case 1:
3834 // should all be handled by createUnaryOperation
3835 assert(0);
3836 return 0;
3837 case 2:
3838 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3839 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003840 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003841 // anything 3 or over doesn't have l-value operands, so all should be consumed
3842 assert(consumedOperands == operands.size());
3843 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845 }
3846 }
3847
John Kessenich55e7d112015-11-15 21:33:39 -07003848 // Decode the return types that were structures
3849 switch (op) {
3850 case glslang::EOpAddCarry:
3851 case glslang::EOpSubBorrow:
3852 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3853 id = builder.createCompositeExtract(id, typeId0, 0);
3854 break;
3855 case glslang::EOpUMulExtended:
3856 case glslang::EOpIMulExtended:
3857 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3858 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3859 break;
3860 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003861 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003862 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3863 id = builder.createCompositeExtract(id, typeId0, 0);
3864 break;
3865 default:
3866 break;
3867 }
3868
John Kessenich32cfd492016-02-02 12:37:46 -07003869 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003870}
3871
3872// Intrinsics with no arguments, no return value, and no precision.
3873spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3874{
3875 // TODO: get the barrier operands correct
3876
3877 switch (op) {
3878 case glslang::EOpEmitVertex:
3879 builder.createNoResultOp(spv::OpEmitVertex);
3880 return 0;
3881 case glslang::EOpEndPrimitive:
3882 builder.createNoResultOp(spv::OpEndPrimitive);
3883 return 0;
3884 case glslang::EOpBarrier:
John Kessenich823fc652016-05-19 18:26:42 -06003885 if (glslangIntermediate->getProfile() != EEsProfile)
3886 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich5e4b1242015-08-06 22:53:06 -06003887 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003888 return 0;
3889 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003890 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003891 return 0;
3892 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003893 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003894 return 0;
3895 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003896 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003897 return 0;
3898 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003899 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003900 return 0;
3901 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003902 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003903 return 0;
3904 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003905 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003906 return 0;
3907 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003908 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003909 return 0;
3910 }
3911}
3912
3913spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3914{
John Kessenich2f273362015-07-18 22:34:27 -06003915 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003916 spv::Id id;
3917 if (symbolValues.end() != iter) {
3918 id = iter->second;
3919 return id;
3920 }
3921
3922 // it was not found, create it
3923 id = createSpvVariable(symbol);
3924 symbolValues[symbol->getId()] = id;
3925
3926 if (! symbol->getType().isStruct()) {
3927 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003928 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08003929 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003930 if (symbol->getType().getQualifier().hasSpecConstantId())
3931 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003932 if (symbol->getQualifier().hasIndex())
3933 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3934 if (symbol->getQualifier().hasComponent())
3935 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3936 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003937 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003938 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003939 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003940 if (symbol->getQualifier().hasXfbBuffer())
3941 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3942 if (symbol->getQualifier().hasXfbOffset())
3943 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3944 }
3945 }
3946
scygan2c864272016-05-18 18:09:17 +02003947 if (symbol->getQualifier().hasLocation())
3948 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07003949 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003950 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003951 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003952 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003953 }
John Kessenich140f3df2015-06-26 16:58:36 -06003954 if (symbol->getQualifier().hasSet())
3955 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003956 else if (IsDescriptorResource(symbol->getType())) {
3957 // default to 0
3958 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3959 }
John Kessenich140f3df2015-06-26 16:58:36 -06003960 if (symbol->getQualifier().hasBinding())
3961 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003962 if (symbol->getQualifier().hasAttachment())
3963 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003964 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003965 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003966 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003967 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003968 if (symbol->getQualifier().hasXfbBuffer())
3969 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3970 }
3971
Rex Xu1da878f2016-02-21 20:59:01 +08003972 if (symbol->getType().isImage()) {
3973 std::vector<spv::Decoration> memory;
3974 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3975 for (unsigned int i = 0; i < memory.size(); ++i)
3976 addDecoration(id, memory[i]);
3977 }
3978
John Kessenich140f3df2015-06-26 16:58:36 -06003979 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06003980 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich5e4b1242015-08-06 22:53:06 -06003981 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003982 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003983
John Kessenich140f3df2015-06-26 16:58:36 -06003984 return id;
3985}
3986
John Kessenich55e7d112015-11-15 21:33:39 -07003987// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003988void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3989{
3990 if (dec != spv::BadValue)
3991 builder.addDecoration(id, dec);
3992}
3993
John Kessenich55e7d112015-11-15 21:33:39 -07003994// If 'dec' is valid, add a one-operand decoration to an object
3995void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3996{
3997 if (dec != spv::BadValue)
3998 builder.addDecoration(id, dec, value);
3999}
4000
4001// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004002void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4003{
4004 if (dec != spv::BadValue)
4005 builder.addMemberDecoration(id, (unsigned)member, dec);
4006}
4007
John Kessenich92187592016-02-01 13:45:25 -07004008// If 'dec' is valid, add a one-operand decoration to a struct member
4009void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4010{
4011 if (dec != spv::BadValue)
4012 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4013}
4014
John Kessenich55e7d112015-11-15 21:33:39 -07004015// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004016// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004017//
4018// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4019//
4020// Recursively walk the nodes. The nodes form a tree whose leaves are
4021// regular constants, which themselves are trees that createSpvConstant()
4022// recursively walks. So, this function walks the "top" of the tree:
4023// - emit specialization constant-building instructions for specConstant
4024// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004025spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004026{
John Kessenich7cc0e282016-03-20 00:46:02 -06004027 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004028
qining4f4bb812016-04-03 23:55:17 -04004029 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004030 if (! node.getQualifier().specConstant) {
4031 // hand off to the non-spec-constant path
4032 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4033 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004034 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004035 nextConst, false);
4036 }
4037
4038 // We now know we have a specialization constant to build
4039
qining4f4bb812016-04-03 23:55:17 -04004040 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
4041 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4042 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4043 std::vector<spv::Id> dimConstId;
4044 for (int dim = 0; dim < 3; ++dim) {
4045 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4046 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4047 if (specConst)
4048 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4049 }
4050 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4051 }
4052
4053 // An AST node labelled as specialization constant should be a symbol node.
4054 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4055 if (auto* sn = node.getAsSymbolNode()) {
4056 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004057 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4058 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4059 // will set the builder into spec constant op instruction generating mode.
4060 sub_tree->traverse(this);
4061 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004062 } else if (auto* const_union_array = &sn->getConstArray()){
4063 int nextConst = 0;
4064 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004065 }
4066 }
qining4f4bb812016-04-03 23:55:17 -04004067
4068 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4069 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004070 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004071 exit(1);
4072 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004073}
4074
John Kessenich140f3df2015-06-26 16:58:36 -06004075// Use 'consts' as the flattened glslang source of scalar constants to recursively
4076// build the aggregate SPIR-V constant.
4077//
4078// If there are not enough elements present in 'consts', 0 will be substituted;
4079// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4080//
qining08408382016-03-21 09:51:37 -04004081spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004082{
4083 // vector of constants for SPIR-V
4084 std::vector<spv::Id> spvConsts;
4085
4086 // Type is used for struct and array constants
4087 spv::Id typeId = convertGlslangToSpvType(glslangType);
4088
4089 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004090 glslang::TType elementType(glslangType, 0);
4091 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004092 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004093 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004094 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004095 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004096 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004097 } else if (glslangType.getStruct()) {
4098 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4099 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004100 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004101 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004102 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4103 bool zero = nextConst >= consts.size();
4104 switch (glslangType.getBasicType()) {
4105 case glslang::EbtInt:
4106 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4107 break;
4108 case glslang::EbtUint:
4109 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4110 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004111 case glslang::EbtInt64:
4112 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4113 break;
4114 case glslang::EbtUint64:
4115 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4116 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 case glslang::EbtFloat:
4118 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4119 break;
4120 case glslang::EbtDouble:
4121 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4122 break;
4123 case glslang::EbtBool:
4124 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4125 break;
4126 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004127 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004128 break;
4129 }
4130 ++nextConst;
4131 }
4132 } else {
4133 // we have a non-aggregate (scalar) constant
4134 bool zero = nextConst >= consts.size();
4135 spv::Id scalar = 0;
4136 switch (glslangType.getBasicType()) {
4137 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004138 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004141 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004142 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004143 case glslang::EbtInt64:
4144 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4145 break;
4146 case glslang::EbtUint64:
4147 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4148 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004149 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004150 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004151 break;
4152 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004153 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004154 break;
4155 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004156 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004157 break;
4158 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004159 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004160 break;
4161 }
4162 ++nextConst;
4163 return scalar;
4164 }
4165
4166 return builder.makeCompositeConstant(typeId, spvConsts);
4167}
4168
John Kessenich7c1aa102015-10-15 13:29:11 -06004169// Return true if the node is a constant or symbol whose reading has no
4170// non-trivial observable cost or effect.
4171bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4172{
4173 // don't know what this is
4174 if (node == nullptr)
4175 return false;
4176
4177 // a constant is safe
4178 if (node->getAsConstantUnion() != nullptr)
4179 return true;
4180
4181 // not a symbol means non-trivial
4182 if (node->getAsSymbolNode() == nullptr)
4183 return false;
4184
4185 // a symbol, depends on what's being read
4186 switch (node->getType().getQualifier().storage) {
4187 case glslang::EvqTemporary:
4188 case glslang::EvqGlobal:
4189 case glslang::EvqIn:
4190 case glslang::EvqInOut:
4191 case glslang::EvqConst:
4192 case glslang::EvqConstReadOnly:
4193 case glslang::EvqUniform:
4194 return true;
4195 default:
4196 return false;
4197 }
qining25262b32016-05-06 17:25:16 -04004198}
John Kessenich7c1aa102015-10-15 13:29:11 -06004199
4200// A node is trivial if it is a single operation with no side effects.
4201// Error on the side of saying non-trivial.
4202// Return true if trivial.
4203bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4204{
4205 if (node == nullptr)
4206 return false;
4207
4208 // symbols and constants are trivial
4209 if (isTrivialLeaf(node))
4210 return true;
4211
4212 // otherwise, it needs to be a simple operation or one or two leaf nodes
4213
4214 // not a simple operation
4215 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4216 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4217 if (binaryNode == nullptr && unaryNode == nullptr)
4218 return false;
4219
4220 // not on leaf nodes
4221 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4222 return false;
4223
4224 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4225 return false;
4226 }
4227
4228 switch (node->getAsOperator()->getOp()) {
4229 case glslang::EOpLogicalNot:
4230 case glslang::EOpConvIntToBool:
4231 case glslang::EOpConvUintToBool:
4232 case glslang::EOpConvFloatToBool:
4233 case glslang::EOpConvDoubleToBool:
4234 case glslang::EOpEqual:
4235 case glslang::EOpNotEqual:
4236 case glslang::EOpLessThan:
4237 case glslang::EOpGreaterThan:
4238 case glslang::EOpLessThanEqual:
4239 case glslang::EOpGreaterThanEqual:
4240 case glslang::EOpIndexDirect:
4241 case glslang::EOpIndexDirectStruct:
4242 case glslang::EOpLogicalXor:
4243 case glslang::EOpAny:
4244 case glslang::EOpAll:
4245 return true;
4246 default:
4247 return false;
4248 }
4249}
4250
4251// Emit short-circuiting code, where 'right' is never evaluated unless
4252// the left side is true (for &&) or false (for ||).
4253spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4254{
4255 spv::Id boolTypeId = builder.makeBoolType();
4256
4257 // emit left operand
4258 builder.clearAccessChain();
4259 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004260 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004261
4262 // Operands to accumulate OpPhi operands
4263 std::vector<spv::Id> phiOperands;
4264 // accumulate left operand's phi information
4265 phiOperands.push_back(leftId);
4266 phiOperands.push_back(builder.getBuildPoint()->getId());
4267
4268 // Make the two kinds of operation symmetric with a "!"
4269 // || => emit "if (! left) result = right"
4270 // && => emit "if ( left) result = right"
4271 //
4272 // TODO: this runtime "not" for || could be avoided by adding functionality
4273 // to 'builder' to have an "else" without an "then"
4274 if (op == glslang::EOpLogicalOr)
4275 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4276
4277 // make an "if" based on the left value
4278 spv::Builder::If ifBuilder(leftId, builder);
4279
4280 // emit right operand as the "then" part of the "if"
4281 builder.clearAccessChain();
4282 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004283 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004284
4285 // accumulate left operand's phi information
4286 phiOperands.push_back(rightId);
4287 phiOperands.push_back(builder.getBuildPoint()->getId());
4288
4289 // finish the "if"
4290 ifBuilder.makeEndIf();
4291
4292 // phi together the two results
4293 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4294}
4295
John Kessenich140f3df2015-06-26 16:58:36 -06004296}; // end anonymous namespace
4297
4298namespace glslang {
4299
John Kessenich68d78fd2015-07-12 19:28:10 -06004300void GetSpirvVersion(std::string& version)
4301{
John Kessenich9e55f632015-07-15 10:03:39 -06004302 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004303 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004304 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004305 version = buf;
4306}
4307
John Kessenich140f3df2015-06-26 16:58:36 -06004308// Write SPIR-V out to a binary file
4309void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4310{
4311 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004312 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004313 for (int i = 0; i < (int)spirv.size(); ++i) {
4314 unsigned int word = spirv[i];
4315 out.write((const char*)&word, 4);
4316 }
4317 out.close();
4318}
4319
4320//
4321// Set up the glslang traversal
4322//
4323void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4324{
Lei Zhang17535f72016-05-04 15:55:59 -04004325 spv::SpvBuildLogger logger;
4326 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004327}
4328
Lei Zhang17535f72016-05-04 15:55:59 -04004329void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004330{
John Kessenich140f3df2015-06-26 16:58:36 -06004331 TIntermNode* root = intermediate.getTreeRoot();
4332
4333 if (root == 0)
4334 return;
4335
4336 glslang::GetThreadPoolAllocator().push();
4337
Lei Zhang17535f72016-05-04 15:55:59 -04004338 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004339
4340 root->traverse(&it);
4341
4342 it.dumpSpv(spirv);
4343
4344 glslang::GetThreadPoolAllocator().pop();
4345}
4346
4347}; // end namespace glslang