blob: 62383cc13b0a394243b7905dd3a44d6d35fd16ad [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//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
88}
89
John Kessenich140f3df2015-06-26 16:58:36 -060090//
91// The main holder of information for translating glslang to SPIR-V.
92//
93// Derives from the AST walking base class.
94//
95class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
96public:
97 TGlslangToSpvTraverser(const glslang::TIntermediate*);
98 virtual ~TGlslangToSpvTraverser();
99
100 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
101 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
102 void visitConstantUnion(glslang::TIntermConstantUnion*);
103 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
104 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
105 void visitSymbol(glslang::TIntermSymbol* symbol);
106 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
107 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
108 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
109
John Kessenich7ba63412015-12-20 17:37:07 -0700110 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112protected:
John Kessenich5e801132016-02-15 11:09:46 -0700113 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -0700114 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -0700115 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600116 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
117 spv::Id getSampledType(const glslang::TSampler&);
118 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700119 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700120 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700121 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800122 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700123 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700124 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
125 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
126 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
129 void makeFunctions(const glslang::TIntermSequence&);
130 void makeGlobalInitializers(const glslang::TIntermSequence&);
131 void visitFunctions(const glslang::TIntermSequence&);
132 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800133 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600134 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
135 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600136 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
137
138 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700139 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800140 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700141 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
143 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800144 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
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
162 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
163 spv::Builder builder;
164 bool inMain;
165 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700166 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 -0700167 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600168 const glslang::TIntermediate* glslangIntermediate;
169 spv::Id stdBuiltins;
170
John Kessenich2f273362015-07-18 22:34:27 -0600171 std::unordered_map<int, spv::Id> symbolValues;
172 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
173 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700174 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600175 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 -0600176 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600177};
178
179//
180// Helper functions for translating glslang representations to SPIR-V enumerants.
181//
182
183// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700184spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600185{
John Kessenich66e2faf2016-03-12 18:34:36 -0700186 switch (source) {
187 case glslang::EShSourceGlsl:
188 switch (profile) {
189 case ENoProfile:
190 case ECoreProfile:
191 case ECompatibilityProfile:
192 return spv::SourceLanguageGLSL;
193 case EEsProfile:
194 return spv::SourceLanguageESSL;
195 default:
196 return spv::SourceLanguageUnknown;
197 }
198 case glslang::EShSourceHlsl:
199 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600200 default:
201 return spv::SourceLanguageUnknown;
202 }
203}
204
205// Translate glslang language (stage) to SPIR-V execution model.
206spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
207{
208 switch (stage) {
209 case EShLangVertex: return spv::ExecutionModelVertex;
210 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
211 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
212 case EShLangGeometry: return spv::ExecutionModelGeometry;
213 case EShLangFragment: return spv::ExecutionModelFragment;
214 case EShLangCompute: return spv::ExecutionModelGLCompute;
215 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700216 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600217 return spv::ExecutionModelFragment;
218 }
219}
220
221// Translate glslang type to SPIR-V storage class.
222spv::StorageClass TranslateStorageClass(const glslang::TType& type)
223{
224 if (type.getQualifier().isPipeInput())
225 return spv::StorageClassInput;
226 else if (type.getQualifier().isPipeOutput())
227 return spv::StorageClassOutput;
228 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700229 if (type.getQualifier().layoutPushConstant)
230 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600231 if (type.getBasicType() == glslang::EbtBlock)
232 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800233 else if (type.getBasicType() == glslang::EbtAtomicUint)
234 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 else
236 return spv::StorageClassUniformConstant;
237 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
238 } else {
239 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700240 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
241 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600242 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
243 case glslang::EvqTemporary: return spv::StorageClassFunction;
244 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700245 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600246 return spv::StorageClassFunction;
247 }
248 }
249}
250
251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
268// Translate glslang type to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
270{
271 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
279// Translate glslang type to SPIR-V block decorations.
280spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
281{
282 if (type.getBasicType() == glslang::EbtBlock) {
283 switch (type.getQualifier().storage) {
284 case glslang::EvqUniform: return spv::DecorationBlock;
285 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
286 case glslang::EvqVaryingIn: return spv::DecorationBlock;
287 case glslang::EvqVaryingOut: return spv::DecorationBlock;
288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 break;
291 }
292 }
293
294 return (spv::Decoration)spv::BadValue;
295}
296
Rex Xu1da878f2016-02-21 20:59:01 +0800297// Translate glslang type to SPIR-V memory decorations.
298void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
299{
300 if (qualifier.coherent)
301 memory.push_back(spv::DecorationCoherent);
302 if (qualifier.volatil)
303 memory.push_back(spv::DecorationVolatile);
304 if (qualifier.restrict)
305 memory.push_back(spv::DecorationRestrict);
306 if (qualifier.readonly)
307 memory.push_back(spv::DecorationNonWritable);
308 if (qualifier.writeonly)
309 memory.push_back(spv::DecorationNonReadable);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700313spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600314{
315 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700316 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600317 case glslang::ElmRowMajor:
318 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700319 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600320 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 default:
322 // opaque layouts don't need a majorness
323 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600324 }
325 } else {
326 switch (type.getBasicType()) {
327 default:
328 return (spv::Decoration)spv::BadValue;
329 break;
330 case glslang::EbtBlock:
331 switch (type.getQualifier().storage) {
332 case glslang::EvqUniform:
333 case glslang::EvqBuffer:
334 switch (type.getQualifier().layoutPacking) {
335 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600336 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
337 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600338 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600339 }
340 case glslang::EvqVaryingIn:
341 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700342 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600343 return (spv::Decoration)spv::BadValue;
344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 return (spv::Decoration)spv::BadValue;
347 }
348 }
349 }
350}
351
352// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700353// Returns spv::Decoration(spv::BadValue) when no decoration
354// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700355spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600356{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700357 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700358 // Smooth decoration doesn't exist in SPIR-V 1.0
359 return (spv::Decoration)spv::BadValue;
360 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700361 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700363 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600364 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700365 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600366 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700369 else if (qualifier.sample) {
370 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600371 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700372 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600373 return (spv::Decoration)spv::BadValue;
374}
375
John Kessenich92187592016-02-01 13:45:25 -0700376// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700377spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600378{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationInvariant;
381 else
382 return (spv::Decoration)spv::BadValue;
383}
384
385// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700386spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600387{
388 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700389 case glslang::EbvPointSize:
390 switch (glslangIntermediate->getStage()) {
391 case EShLangGeometry:
392 builder.addCapability(spv::CapabilityGeometryPointSize);
393 break;
394 case EShLangTessControl:
395 case EShLangTessEvaluation:
396 builder.addCapability(spv::CapabilityTessellationPointSize);
397 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100398 default:
399 break;
John Kessenich92187592016-02-01 13:45:25 -0700400 }
401 return spv::BuiltInPointSize;
402
403 case glslang::EbvClipDistance:
404 builder.addCapability(spv::CapabilityClipDistance);
405 return spv::BuiltInClipDistance;
406
407 case glslang::EbvCullDistance:
408 builder.addCapability(spv::CapabilityCullDistance);
409 return spv::BuiltInCullDistance;
410
411 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500412 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700413 return spv::BuiltInViewportIndex;
414
John Kessenich5e801132016-02-15 11:09:46 -0700415 case glslang::EbvSampleId:
416 builder.addCapability(spv::CapabilitySampleRateShading);
417 return spv::BuiltInSampleId;
418
419 case glslang::EbvSamplePosition:
420 builder.addCapability(spv::CapabilitySampleRateShading);
421 return spv::BuiltInSamplePosition;
422
423 case glslang::EbvSampleMask:
424 builder.addCapability(spv::CapabilitySampleRateShading);
425 return spv::BuiltInSampleMask;
426
John Kessenich140f3df2015-06-26 16:58:36 -0600427 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600428 case glslang::EbvVertexId: return spv::BuiltInVertexId;
429 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700430 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
431 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600432 case glslang::EbvBaseVertex:
433 case glslang::EbvBaseInstance:
434 case glslang::EbvDrawId:
435 // TODO: Add SPIR-V builtin ID.
Rex Xu574ab042016-04-14 16:53:07 +0800436 spv::MissingFunctionality("shader draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600437 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600438 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
439 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
440 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600441 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
442 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
443 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
444 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
445 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
446 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
447 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600448 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
449 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
450 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
451 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
452 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
453 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
454 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
455 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800456 case glslang::EbvSubGroupSize:
457 case glslang::EbvSubGroupInvocation:
458 case glslang::EbvSubGroupEqMask:
459 case glslang::EbvSubGroupGeMask:
460 case glslang::EbvSubGroupGtMask:
461 case glslang::EbvSubGroupLeMask:
462 case glslang::EbvSubGroupLtMask:
463 // TODO: Add SPIR-V builtin ID.
464 spv::MissingFunctionality("shader ballot");
465 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600466 default: return (spv::BuiltIn)spv::BadValue;
467 }
468}
469
Rex Xufc618912015-09-09 16:42:49 +0800470// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700471spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800472{
473 assert(type.getBasicType() == glslang::EbtSampler);
474
John Kessenich5d0fa972016-02-15 11:57:00 -0700475 // Check for capabilities
476 switch (type.getQualifier().layoutFormat) {
477 case glslang::ElfRg32f:
478 case glslang::ElfRg16f:
479 case glslang::ElfR11fG11fB10f:
480 case glslang::ElfR16f:
481 case glslang::ElfRgba16:
482 case glslang::ElfRgb10A2:
483 case glslang::ElfRg16:
484 case glslang::ElfRg8:
485 case glslang::ElfR16:
486 case glslang::ElfR8:
487 case glslang::ElfRgba16Snorm:
488 case glslang::ElfRg16Snorm:
489 case glslang::ElfRg8Snorm:
490 case glslang::ElfR16Snorm:
491 case glslang::ElfR8Snorm:
492
493 case glslang::ElfRg32i:
494 case glslang::ElfRg16i:
495 case glslang::ElfRg8i:
496 case glslang::ElfR16i:
497 case glslang::ElfR8i:
498
499 case glslang::ElfRgb10a2ui:
500 case glslang::ElfRg32ui:
501 case glslang::ElfRg16ui:
502 case glslang::ElfRg8ui:
503 case glslang::ElfR16ui:
504 case glslang::ElfR8ui:
505 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
506 break;
507
508 default:
509 break;
510 }
511
512 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800513 switch (type.getQualifier().layoutFormat) {
514 case glslang::ElfNone: return spv::ImageFormatUnknown;
515 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
516 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
517 case glslang::ElfR32f: return spv::ImageFormatR32f;
518 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
519 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
520 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
521 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
522 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
523 case glslang::ElfR16f: return spv::ImageFormatR16f;
524 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
525 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
526 case glslang::ElfRg16: return spv::ImageFormatRg16;
527 case glslang::ElfRg8: return spv::ImageFormatRg8;
528 case glslang::ElfR16: return spv::ImageFormatR16;
529 case glslang::ElfR8: return spv::ImageFormatR8;
530 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
531 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
532 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
533 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
534 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
535 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
536 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
537 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
538 case glslang::ElfR32i: return spv::ImageFormatR32i;
539 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
540 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
541 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
542 case glslang::ElfR16i: return spv::ImageFormatR16i;
543 case glslang::ElfR8i: return spv::ImageFormatR8i;
544 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
545 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
546 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
547 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
548 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
549 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
550 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
551 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
552 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
553 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
554 default: return (spv::ImageFormat)spv::BadValue;
555 }
556}
557
John Kessenich6c292d32016-02-15 20:58:50 -0700558// Return whether or not the given type is something that should be tied to a
559// descriptor set.
560bool IsDescriptorResource(const glslang::TType& type)
561{
John Kessenichf7497e22016-03-08 21:36:22 -0700562 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700563 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700564 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700565
566 // non block...
567 // basically samplerXXX/subpass/sampler/texture are all included
568 // if they are the global-scope-class, not the function parameter
569 // (or local, if they ever exist) class.
570 if (type.getBasicType() == glslang::EbtSampler)
571 return type.getQualifier().isUniformOrBuffer();
572
573 // None of the above.
574 return false;
575}
576
John Kesseniche0b6cad2015-12-24 10:30:13 -0700577void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
578{
579 if (child.layoutMatrix == glslang::ElmNone)
580 child.layoutMatrix = parent.layoutMatrix;
581
582 if (parent.invariant)
583 child.invariant = true;
584 if (parent.nopersp)
585 child.nopersp = true;
586 if (parent.flat)
587 child.flat = true;
588 if (parent.centroid)
589 child.centroid = true;
590 if (parent.patch)
591 child.patch = true;
592 if (parent.sample)
593 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800594 if (parent.coherent)
595 child.coherent = true;
596 if (parent.volatil)
597 child.volatil = true;
598 if (parent.restrict)
599 child.restrict = true;
600 if (parent.readonly)
601 child.readonly = true;
602 if (parent.writeonly)
603 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700604}
605
606bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
607{
John Kessenich7b9fa252016-01-21 18:56:57 -0700608 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700609 // - struct members can inherit from a struct declaration
610 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
611 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700612 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700613}
614
John Kessenich140f3df2015-06-26 16:58:36 -0600615//
616// Implement the TGlslangToSpvTraverser class.
617//
618
619TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
620 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700621 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600622 inMain(false), mainTerminated(false), linkageOnly(false),
623 glslangIntermediate(glslangIntermediate)
624{
625 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
626
627 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700628 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600629 stdBuiltins = builder.import("GLSL.std.450");
630 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700631 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
632 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600633
634 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600635 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
636 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600637 builder.addSourceExtension(it->c_str());
638
639 // Add the top-level modes for this shader.
640
John Kessenich92187592016-02-01 13:45:25 -0700641 if (glslangIntermediate->getXfbMode()) {
642 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600643 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700644 }
John Kessenich140f3df2015-06-26 16:58:36 -0600645
646 unsigned int mode;
647 switch (glslangIntermediate->getStage()) {
648 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600649 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600650 break;
651
652 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600653 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600654 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
655 break;
656
657 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600658 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600659 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700660 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
661 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
662 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600663 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600664 }
665 if (mode != spv::BadValue)
666 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
667
John Kesseniche6903322015-10-13 16:29:02 -0600668 switch (glslangIntermediate->getVertexSpacing()) {
669 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
670 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
671 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
672 default: mode = spv::BadValue; break;
673 }
674 if (mode != spv::BadValue)
675 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
676
677 switch (glslangIntermediate->getVertexOrder()) {
678 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
679 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
680 default: mode = spv::BadValue; break;
681 }
682 if (mode != spv::BadValue)
683 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
684
685 if (glslangIntermediate->getPointMode())
686 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600687 break;
688
689 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600690 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600691 switch (glslangIntermediate->getInputPrimitive()) {
692 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
693 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
694 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700695 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600696 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
697 default: mode = spv::BadValue; break;
698 }
699 if (mode != spv::BadValue)
700 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600701
John Kessenich140f3df2015-06-26 16:58:36 -0600702 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
703
704 switch (glslangIntermediate->getOutputPrimitive()) {
705 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
706 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
707 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
708 default: mode = spv::BadValue; break;
709 }
710 if (mode != spv::BadValue)
711 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
712 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
713 break;
714
715 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600716 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600717 if (glslangIntermediate->getPixelCenterInteger())
718 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600719
John Kessenich140f3df2015-06-26 16:58:36 -0600720 if (glslangIntermediate->getOriginUpperLeft())
721 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600722 else
723 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600724
725 if (glslangIntermediate->getEarlyFragmentTests())
726 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
727
728 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600729 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
730 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
731 default: mode = spv::BadValue; break;
732 }
733 if (mode != spv::BadValue)
734 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
735
736 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
737 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600738 break;
739
740 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600741 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600742 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
743 glslangIntermediate->getLocalSize(1),
744 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600745 break;
746
747 default:
748 break;
749 }
750
751}
752
John Kessenich7ba63412015-12-20 17:37:07 -0700753// Finish everything and dump
754void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
755{
756 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100757 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
758 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700759
qiningda397332016-03-09 19:54:03 -0500760 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700761 builder.dump(out);
762}
763
John Kessenich140f3df2015-06-26 16:58:36 -0600764TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
765{
766 if (! mainTerminated) {
767 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
768 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600769 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600770 }
771}
772
773//
774// Implement the traversal functions.
775//
776// Return true from interior nodes to have the external traversal
777// continue on to children. Return false if children were
778// already processed.
779//
780
781//
782// Symbols can turn into
783// - uniform/input reads
784// - output writes
785// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
786// - something simple that degenerates into the last bullet
787//
788void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
789{
qining75d1d802016-04-06 14:42:01 -0400790 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
791 if (symbol->getType().getQualifier().isSpecConstant())
792 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
793
John Kessenich140f3df2015-06-26 16:58:36 -0600794 // getSymbolId() will set up all the IO decorations on the first call.
795 // Formal function parameters were mapped during makeFunctions().
796 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700797
798 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
799 if (builder.isPointer(id)) {
800 spv::StorageClass sc = builder.getStorageClass(id);
801 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
802 iOSet.insert(id);
803 }
804
805 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700806 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600807 // Prepare to generate code for the access
808
809 // L-value chains will be computed left to right. We're on the symbol now,
810 // which is the left-most part of the access chain, so now is "clear" time,
811 // followed by setting the base.
812 builder.clearAccessChain();
813
814 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700815 // except for
816 // A) "const in" arguments to a function, which are an intermediate object.
817 // See comments in handleUserFunctionCall().
818 // B) Specialization constants (normal constant don't even come in as a variable),
819 // These are also pure R-values.
820 glslang::TQualifier qualifier = symbol->getQualifier();
821 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
822 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600823 builder.setAccessChainRValue(id);
824 else
825 builder.setAccessChainLValue(id);
826 }
827}
828
829bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
830{
qining40887662016-04-03 22:20:42 -0400831 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
832 if (node->getType().getQualifier().isSpecConstant())
833 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
834
John Kessenich140f3df2015-06-26 16:58:36 -0600835 // First, handle special cases
836 switch (node->getOp()) {
837 case glslang::EOpAssign:
838 case glslang::EOpAddAssign:
839 case glslang::EOpSubAssign:
840 case glslang::EOpMulAssign:
841 case glslang::EOpVectorTimesMatrixAssign:
842 case glslang::EOpVectorTimesScalarAssign:
843 case glslang::EOpMatrixTimesScalarAssign:
844 case glslang::EOpMatrixTimesMatrixAssign:
845 case glslang::EOpDivAssign:
846 case glslang::EOpModAssign:
847 case glslang::EOpAndAssign:
848 case glslang::EOpInclusiveOrAssign:
849 case glslang::EOpExclusiveOrAssign:
850 case glslang::EOpLeftShiftAssign:
851 case glslang::EOpRightShiftAssign:
852 // A bin-op assign "a += b" means the same thing as "a = a + b"
853 // where a is evaluated before b. For a simple assignment, GLSL
854 // says to evaluate the left before the right. So, always, left
855 // node then right node.
856 {
857 // get the left l-value, save it away
858 builder.clearAccessChain();
859 node->getLeft()->traverse(this);
860 spv::Builder::AccessChain lValue = builder.getAccessChain();
861
862 // evaluate the right
863 builder.clearAccessChain();
864 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700865 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600866
867 if (node->getOp() != glslang::EOpAssign) {
868 // the left is also an r-value
869 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700870 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600871
872 // do the operation
873 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
874 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
875 node->getType().getBasicType());
876
877 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700878 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 }
880
881 // store the result
882 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800883 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600884
885 // assignments are expressions having an rValue after they are evaluated...
886 builder.clearAccessChain();
887 builder.setAccessChainRValue(rValue);
888 }
889 return false;
890 case glslang::EOpIndexDirect:
891 case glslang::EOpIndexDirectStruct:
892 {
893 // Get the left part of the access chain.
894 node->getLeft()->traverse(this);
895
896 // Add the next element in the chain
897
John Kessenich55e7d112015-11-15 21:33:39 -0700898 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600899 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
900 // This may be, e.g., an anonymous block-member selection, which generally need
901 // index remapping due to hidden members in anonymous blocks.
902 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700903 assert(remapper.size() > 0);
904 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600905 }
906
907 if (! node->getLeft()->getType().isArray() &&
908 node->getLeft()->getType().isVector() &&
909 node->getOp() == glslang::EOpIndexDirect) {
910 // This is essentially a hard-coded vector swizzle of size 1,
911 // so short circuit the access-chain stuff with a swizzle.
912 std::vector<unsigned> swizzle;
913 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600914 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600915 } else {
916 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600917 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600918 }
919 }
920 return false;
921 case glslang::EOpIndexIndirect:
922 {
923 // Structure or array or vector indirection.
924 // Will use native SPIR-V access-chain for struct and array indirection;
925 // matrices are arrays of vectors, so will also work for a matrix.
926 // Will use the access chain's 'component' for variable index into a vector.
927
928 // This adapter is building access chains left to right.
929 // Set up the access chain to the left.
930 node->getLeft()->traverse(this);
931
932 // save it so that computing the right side doesn't trash it
933 spv::Builder::AccessChain partial = builder.getAccessChain();
934
935 // compute the next index in the chain
936 builder.clearAccessChain();
937 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700938 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600939
940 // restore the saved access chain
941 builder.setAccessChain(partial);
942
943 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600944 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600945 else
John Kessenichfa668da2015-09-13 14:46:30 -0600946 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948 return false;
949 case glslang::EOpVectorSwizzle:
950 {
951 node->getLeft()->traverse(this);
952 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
953 std::vector<unsigned> swizzle;
954 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
955 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600956 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600957 }
958 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600959 case glslang::EOpLogicalOr:
960 case glslang::EOpLogicalAnd:
961 {
962
963 // These may require short circuiting, but can sometimes be done as straight
964 // binary operations. The right operand must be short circuited if it has
965 // side effects, and should probably be if it is complex.
966 if (isTrivial(node->getRight()->getAsTyped()))
967 break; // handle below as a normal binary operation
968 // otherwise, we need to do dynamic short circuiting on the right operand
969 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
970 builder.clearAccessChain();
971 builder.setAccessChainRValue(result);
972 }
973 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600974 default:
975 break;
976 }
977
978 // Assume generic binary op...
979
John Kessenich32cfd492016-02-02 12:37:46 -0700980 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600981 builder.clearAccessChain();
982 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700983 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600984
John Kessenich32cfd492016-02-02 12:37:46 -0700985 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600986 builder.clearAccessChain();
987 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700988 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600989
John Kessenich32cfd492016-02-02 12:37:46 -0700990 // get result
991 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
992 convertGlslangToSpvType(node->getType()), left, right,
993 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600994
John Kessenich50e57562015-12-21 21:21:11 -0700995 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600996 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700997 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700998 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600999 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001000 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001001 return false;
1002 }
John Kessenich140f3df2015-06-26 16:58:36 -06001003}
1004
1005bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1006{
qining40887662016-04-03 22:20:42 -04001007 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1008 if (node->getType().getQualifier().isSpecConstant())
1009 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1010
John Kessenichfc51d282015-08-19 13:34:18 -06001011 spv::Id result = spv::NoResult;
1012
1013 // try texturing first
1014 result = createImageTextureFunctionCall(node);
1015 if (result != spv::NoResult) {
1016 builder.clearAccessChain();
1017 builder.setAccessChainRValue(result);
1018
1019 return false; // done with this node
1020 }
1021
1022 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001023
1024 if (node->getOp() == glslang::EOpArrayLength) {
1025 // Quite special; won't want to evaluate the operand.
1026
1027 // Normal .length() would have been constant folded by the front-end.
1028 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001029 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001030 assert(node->getOperand()->getType().isRuntimeSizedArray());
1031 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1032 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001033 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1034 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001035
1036 builder.clearAccessChain();
1037 builder.setAccessChainRValue(length);
1038
1039 return false;
1040 }
1041
John Kessenichfc51d282015-08-19 13:34:18 -06001042 // Start by evaluating the operand
1043
John Kessenich140f3df2015-06-26 16:58:36 -06001044 builder.clearAccessChain();
1045 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001046
Rex Xufc618912015-09-09 16:42:49 +08001047 spv::Id operand = spv::NoResult;
1048
1049 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1050 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001051 node->getOp() == glslang::EOpAtomicCounter ||
1052 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001053 operand = builder.accessChainGetLValue(); // Special case l-value operands
1054 else
John Kessenich32cfd492016-02-02 12:37:46 -07001055 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001056
1057 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1058
1059 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001060 if (! result)
1061 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001062
1063 // if not, then possibly an operation
1064 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001065 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001066
1067 if (result) {
1068 builder.clearAccessChain();
1069 builder.setAccessChainRValue(result);
1070
1071 return false; // done with this node
1072 }
1073
1074 // it must be a special case, check...
1075 switch (node->getOp()) {
1076 case glslang::EOpPostIncrement:
1077 case glslang::EOpPostDecrement:
1078 case glslang::EOpPreIncrement:
1079 case glslang::EOpPreDecrement:
1080 {
1081 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001082 spv::Id one = 0;
1083 if (node->getBasicType() == glslang::EbtFloat)
1084 one = builder.makeFloatConstant(1.0F);
1085 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1086 one = builder.makeInt64Constant(1);
1087 else
1088 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001089 glslang::TOperator op;
1090 if (node->getOp() == glslang::EOpPreIncrement ||
1091 node->getOp() == glslang::EOpPostIncrement)
1092 op = glslang::EOpAdd;
1093 else
1094 op = glslang::EOpSub;
1095
1096 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001097 convertGlslangToSpvType(node->getType()), operand, one,
1098 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001099 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001100
1101 // The result of operation is always stored, but conditionally the
1102 // consumed result. The consumed result is always an r-value.
1103 builder.accessChainStore(result);
1104 builder.clearAccessChain();
1105 if (node->getOp() == glslang::EOpPreIncrement ||
1106 node->getOp() == glslang::EOpPreDecrement)
1107 builder.setAccessChainRValue(result);
1108 else
1109 builder.setAccessChainRValue(operand);
1110 }
1111
1112 return false;
1113
1114 case glslang::EOpEmitStreamVertex:
1115 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1116 return false;
1117 case glslang::EOpEndStreamPrimitive:
1118 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1119 return false;
1120
1121 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001122 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001123 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001124 }
John Kessenich140f3df2015-06-26 16:58:36 -06001125}
1126
1127bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1128{
qining27e04a02016-04-14 16:40:20 -04001129 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1130 if (node->getType().getQualifier().isSpecConstant())
1131 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1132
John Kessenichfc51d282015-08-19 13:34:18 -06001133 spv::Id result = spv::NoResult;
1134
1135 // try texturing
1136 result = createImageTextureFunctionCall(node);
1137 if (result != spv::NoResult) {
1138 builder.clearAccessChain();
1139 builder.setAccessChainRValue(result);
1140
1141 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001142 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001143 // "imageStore" is a special case, which has no result
1144 return false;
1145 }
John Kessenichfc51d282015-08-19 13:34:18 -06001146
John Kessenich140f3df2015-06-26 16:58:36 -06001147 glslang::TOperator binOp = glslang::EOpNull;
1148 bool reduceComparison = true;
1149 bool isMatrix = false;
1150 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001151 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001152
1153 assert(node->getOp());
1154
1155 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1156
1157 switch (node->getOp()) {
1158 case glslang::EOpSequence:
1159 {
1160 if (preVisit)
1161 ++sequenceDepth;
1162 else
1163 --sequenceDepth;
1164
1165 if (sequenceDepth == 1) {
1166 // If this is the parent node of all the functions, we want to see them
1167 // early, so all call points have actual SPIR-V functions to reference.
1168 // In all cases, still let the traverser visit the children for us.
1169 makeFunctions(node->getAsAggregate()->getSequence());
1170
1171 // Also, we want all globals initializers to go into the entry of main(), before
1172 // anything else gets there, so visit out of order, doing them all now.
1173 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1174
1175 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1176 // so do them manually.
1177 visitFunctions(node->getAsAggregate()->getSequence());
1178
1179 return false;
1180 }
1181
1182 return true;
1183 }
1184 case glslang::EOpLinkerObjects:
1185 {
1186 if (visit == glslang::EvPreVisit)
1187 linkageOnly = true;
1188 else
1189 linkageOnly = false;
1190
1191 return true;
1192 }
1193 case glslang::EOpComma:
1194 {
1195 // processing from left to right naturally leaves the right-most
1196 // lying around in the access chain
1197 glslang::TIntermSequence& glslangOperands = node->getSequence();
1198 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1199 glslangOperands[i]->traverse(this);
1200
1201 return false;
1202 }
1203 case glslang::EOpFunction:
1204 if (visit == glslang::EvPreVisit) {
1205 if (isShaderEntrypoint(node)) {
1206 inMain = true;
1207 builder.setBuildPoint(shaderEntry->getLastBlock());
1208 } else {
1209 handleFunctionEntry(node);
1210 }
1211 } else {
1212 if (inMain)
1213 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001214 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001215 inMain = false;
1216 }
1217
1218 return true;
1219 case glslang::EOpParameters:
1220 // Parameters will have been consumed by EOpFunction processing, but not
1221 // the body, so we still visited the function node's children, making this
1222 // child redundant.
1223 return false;
1224 case glslang::EOpFunctionCall:
1225 {
1226 if (node->isUserDefined())
1227 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001228 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1229 if (result) {
1230 builder.clearAccessChain();
1231 builder.setAccessChainRValue(result);
1232 } else
1233 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001234
1235 return false;
1236 }
1237 case glslang::EOpConstructMat2x2:
1238 case glslang::EOpConstructMat2x3:
1239 case glslang::EOpConstructMat2x4:
1240 case glslang::EOpConstructMat3x2:
1241 case glslang::EOpConstructMat3x3:
1242 case glslang::EOpConstructMat3x4:
1243 case glslang::EOpConstructMat4x2:
1244 case glslang::EOpConstructMat4x3:
1245 case glslang::EOpConstructMat4x4:
1246 case glslang::EOpConstructDMat2x2:
1247 case glslang::EOpConstructDMat2x3:
1248 case glslang::EOpConstructDMat2x4:
1249 case glslang::EOpConstructDMat3x2:
1250 case glslang::EOpConstructDMat3x3:
1251 case glslang::EOpConstructDMat3x4:
1252 case glslang::EOpConstructDMat4x2:
1253 case glslang::EOpConstructDMat4x3:
1254 case glslang::EOpConstructDMat4x4:
1255 isMatrix = true;
1256 // fall through
1257 case glslang::EOpConstructFloat:
1258 case glslang::EOpConstructVec2:
1259 case glslang::EOpConstructVec3:
1260 case glslang::EOpConstructVec4:
1261 case glslang::EOpConstructDouble:
1262 case glslang::EOpConstructDVec2:
1263 case glslang::EOpConstructDVec3:
1264 case glslang::EOpConstructDVec4:
1265 case glslang::EOpConstructBool:
1266 case glslang::EOpConstructBVec2:
1267 case glslang::EOpConstructBVec3:
1268 case glslang::EOpConstructBVec4:
1269 case glslang::EOpConstructInt:
1270 case glslang::EOpConstructIVec2:
1271 case glslang::EOpConstructIVec3:
1272 case glslang::EOpConstructIVec4:
1273 case glslang::EOpConstructUint:
1274 case glslang::EOpConstructUVec2:
1275 case glslang::EOpConstructUVec3:
1276 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001277 case glslang::EOpConstructInt64:
1278 case glslang::EOpConstructI64Vec2:
1279 case glslang::EOpConstructI64Vec3:
1280 case glslang::EOpConstructI64Vec4:
1281 case glslang::EOpConstructUint64:
1282 case glslang::EOpConstructU64Vec2:
1283 case glslang::EOpConstructU64Vec3:
1284 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001285 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001286 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001287 {
1288 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001289 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001290 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1291 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001292 if (node->getOp() == glslang::EOpConstructTextureSampler)
1293 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1294 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001295 std::vector<spv::Id> constituents;
1296 for (int c = 0; c < (int)arguments.size(); ++c)
1297 constituents.push_back(arguments[c]);
1298 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001299 } else if (isMatrix)
1300 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1301 else
1302 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001303
1304 builder.clearAccessChain();
1305 builder.setAccessChainRValue(constructed);
1306
1307 return false;
1308 }
1309
1310 // These six are component-wise compares with component-wise results.
1311 // Forward on to createBinaryOperation(), requesting a vector result.
1312 case glslang::EOpLessThan:
1313 case glslang::EOpGreaterThan:
1314 case glslang::EOpLessThanEqual:
1315 case glslang::EOpGreaterThanEqual:
1316 case glslang::EOpVectorEqual:
1317 case glslang::EOpVectorNotEqual:
1318 {
1319 // Map the operation to a binary
1320 binOp = node->getOp();
1321 reduceComparison = false;
1322 switch (node->getOp()) {
1323 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1324 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1325 default: binOp = node->getOp(); break;
1326 }
1327
1328 break;
1329 }
1330 case glslang::EOpMul:
1331 // compontent-wise matrix multiply
1332 binOp = glslang::EOpMul;
1333 break;
1334 case glslang::EOpOuterProduct:
1335 // two vectors multiplied to make a matrix
1336 binOp = glslang::EOpOuterProduct;
1337 break;
1338 case glslang::EOpDot:
1339 {
1340 // for scalar dot product, use multiply
1341 glslang::TIntermSequence& glslangOperands = node->getSequence();
1342 if (! glslangOperands[0]->getAsTyped()->isVector())
1343 binOp = glslang::EOpMul;
1344 break;
1345 }
1346 case glslang::EOpMod:
1347 // when an aggregate, this is the floating-point mod built-in function,
1348 // which can be emitted by the one in createBinaryOperation()
1349 binOp = glslang::EOpMod;
1350 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001351 case glslang::EOpEmitVertex:
1352 case glslang::EOpEndPrimitive:
1353 case glslang::EOpBarrier:
1354 case glslang::EOpMemoryBarrier:
1355 case glslang::EOpMemoryBarrierAtomicCounter:
1356 case glslang::EOpMemoryBarrierBuffer:
1357 case glslang::EOpMemoryBarrierImage:
1358 case glslang::EOpMemoryBarrierShared:
1359 case glslang::EOpGroupMemoryBarrier:
1360 noReturnValue = true;
1361 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1362 break;
1363
John Kessenich426394d2015-07-23 10:22:48 -06001364 case glslang::EOpAtomicAdd:
1365 case glslang::EOpAtomicMin:
1366 case glslang::EOpAtomicMax:
1367 case glslang::EOpAtomicAnd:
1368 case glslang::EOpAtomicOr:
1369 case glslang::EOpAtomicXor:
1370 case glslang::EOpAtomicExchange:
1371 case glslang::EOpAtomicCompSwap:
1372 atomic = true;
1373 break;
1374
John Kessenich140f3df2015-06-26 16:58:36 -06001375 default:
1376 break;
1377 }
1378
1379 //
1380 // See if it maps to a regular operation.
1381 //
John Kessenich140f3df2015-06-26 16:58:36 -06001382 if (binOp != glslang::EOpNull) {
1383 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1384 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1385 assert(left && right);
1386
1387 builder.clearAccessChain();
1388 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001389 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001390
1391 builder.clearAccessChain();
1392 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001393 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001394
1395 result = createBinaryOperation(binOp, precision,
1396 convertGlslangToSpvType(node->getType()), leftId, rightId,
1397 left->getType().getBasicType(), reduceComparison);
1398
1399 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001400 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001401 builder.clearAccessChain();
1402 builder.setAccessChainRValue(result);
1403
1404 return false;
1405 }
1406
John Kessenich426394d2015-07-23 10:22:48 -06001407 //
1408 // Create the list of operands.
1409 //
John Kessenich140f3df2015-06-26 16:58:36 -06001410 glslang::TIntermSequence& glslangOperands = node->getSequence();
1411 std::vector<spv::Id> operands;
1412 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1413 builder.clearAccessChain();
1414 glslangOperands[arg]->traverse(this);
1415
1416 // special case l-value operands; there are just a few
1417 bool lvalue = false;
1418 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001419 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001420 case glslang::EOpModf:
1421 if (arg == 1)
1422 lvalue = true;
1423 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001424 case glslang::EOpInterpolateAtSample:
1425 case glslang::EOpInterpolateAtOffset:
1426 if (arg == 0)
1427 lvalue = true;
1428 break;
Rex Xud4782c12015-09-06 16:30:11 +08001429 case glslang::EOpAtomicAdd:
1430 case glslang::EOpAtomicMin:
1431 case glslang::EOpAtomicMax:
1432 case glslang::EOpAtomicAnd:
1433 case glslang::EOpAtomicOr:
1434 case glslang::EOpAtomicXor:
1435 case glslang::EOpAtomicExchange:
1436 case glslang::EOpAtomicCompSwap:
1437 if (arg == 0)
1438 lvalue = true;
1439 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001440 case glslang::EOpAddCarry:
1441 case glslang::EOpSubBorrow:
1442 if (arg == 2)
1443 lvalue = true;
1444 break;
1445 case glslang::EOpUMulExtended:
1446 case glslang::EOpIMulExtended:
1447 if (arg >= 2)
1448 lvalue = true;
1449 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001450 default:
1451 break;
1452 }
1453 if (lvalue)
1454 operands.push_back(builder.accessChainGetLValue());
1455 else
John Kessenich32cfd492016-02-02 12:37:46 -07001456 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001457 }
John Kessenich426394d2015-07-23 10:22:48 -06001458
1459 if (atomic) {
1460 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001461 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001462 } else {
1463 // Pass through to generic operations.
1464 switch (glslangOperands.size()) {
1465 case 0:
1466 result = createNoArgOperation(node->getOp());
1467 break;
1468 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001469 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001470 break;
1471 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001472 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001473 break;
1474 }
John Kessenich140f3df2015-06-26 16:58:36 -06001475 }
1476
1477 if (noReturnValue)
1478 return false;
1479
1480 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001481 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001482 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001483 } else {
1484 builder.clearAccessChain();
1485 builder.setAccessChainRValue(result);
1486 return false;
1487 }
1488}
1489
1490bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1491{
1492 // This path handles both if-then-else and ?:
1493 // The if-then-else has a node type of void, while
1494 // ?: has a non-void node type
1495 spv::Id result = 0;
1496 if (node->getBasicType() != glslang::EbtVoid) {
1497 // don't handle this as just on-the-fly temporaries, because there will be two names
1498 // and better to leave SSA to later passes
1499 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1500 }
1501
1502 // emit the condition before doing anything with selection
1503 node->getCondition()->traverse(this);
1504
1505 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001506 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001507
1508 if (node->getTrueBlock()) {
1509 // emit the "then" statement
1510 node->getTrueBlock()->traverse(this);
1511 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001512 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001513 }
1514
1515 if (node->getFalseBlock()) {
1516 ifBuilder.makeBeginElse();
1517 // emit the "else" statement
1518 node->getFalseBlock()->traverse(this);
1519 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001520 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001521 }
1522
1523 ifBuilder.makeEndIf();
1524
1525 if (result) {
1526 // GLSL only has r-values as the result of a :?, but
1527 // if we have an l-value, that can be more efficient if it will
1528 // become the base of a complex r-value expression, because the
1529 // next layer copies r-values into memory to use the access-chain mechanism
1530 builder.clearAccessChain();
1531 builder.setAccessChainLValue(result);
1532 }
1533
1534 return false;
1535}
1536
1537bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1538{
1539 // emit and get the condition before doing anything with switch
1540 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001541 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001542
1543 // browse the children to sort out code segments
1544 int defaultSegment = -1;
1545 std::vector<TIntermNode*> codeSegments;
1546 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1547 std::vector<int> caseValues;
1548 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1549 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1550 TIntermNode* child = *c;
1551 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001552 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001553 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001554 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001555 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1556 } else
1557 codeSegments.push_back(child);
1558 }
1559
1560 // handle the case where the last code segment is missing, due to no code
1561 // statements between the last case and the end of the switch statement
1562 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1563 (int)codeSegments.size() == defaultSegment)
1564 codeSegments.push_back(nullptr);
1565
1566 // make the switch statement
1567 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001568 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001569
1570 // emit all the code in the segments
1571 breakForLoop.push(false);
1572 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1573 builder.nextSwitchSegment(segmentBlocks, s);
1574 if (codeSegments[s])
1575 codeSegments[s]->traverse(this);
1576 else
1577 builder.addSwitchBreak();
1578 }
1579 breakForLoop.pop();
1580
1581 builder.endSwitch(segmentBlocks);
1582
1583 return false;
1584}
1585
1586void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1587{
1588 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001589 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001590
1591 builder.clearAccessChain();
1592 builder.setAccessChainRValue(constant);
1593}
1594
1595bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1596{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001597 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001598 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001599 // Spec requires back edges to target header blocks, and every header block
1600 // must dominate its merge block. Make a header block first to ensure these
1601 // conditions are met. By definition, it will contain OpLoopMerge, followed
1602 // by a block-ending branch. But we don't want to put any other body/test
1603 // instructions in it, since the body/test may have arbitrary instructions,
1604 // including merges of its own.
1605 builder.setBuildPoint(&blocks.head);
1606 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001607 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001608 spv::Block& test = builder.makeNewBlock();
1609 builder.createBranch(&test);
1610
1611 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001612 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001613 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001614 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001615 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1616
1617 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001618 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001619 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001620 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001621 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001622 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001623
1624 builder.setBuildPoint(&blocks.continue_target);
1625 if (node->getTerminal())
1626 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001627 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001628 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001629 builder.createBranch(&blocks.body);
1630
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001631 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001632 builder.setBuildPoint(&blocks.body);
1633 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001634 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001635 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001636 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001637
1638 builder.setBuildPoint(&blocks.continue_target);
1639 if (node->getTerminal())
1640 node->getTerminal()->traverse(this);
1641 if (node->getTest()) {
1642 node->getTest()->traverse(this);
1643 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001644 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001645 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001646 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001647 // TODO: unless there was a break/return/discard instruction
1648 // somewhere in the body, this is an infinite loop, so we should
1649 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001650 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001651 }
John Kessenich140f3df2015-06-26 16:58:36 -06001652 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001653 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001654 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001655 return false;
1656}
1657
1658bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1659{
1660 if (node->getExpression())
1661 node->getExpression()->traverse(this);
1662
1663 switch (node->getFlowOp()) {
1664 case glslang::EOpKill:
1665 builder.makeDiscard();
1666 break;
1667 case glslang::EOpBreak:
1668 if (breakForLoop.top())
1669 builder.createLoopExit();
1670 else
1671 builder.addSwitchBreak();
1672 break;
1673 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001674 builder.createLoopContinue();
1675 break;
1676 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001677 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001678 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001679 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001680 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001681
1682 builder.clearAccessChain();
1683 break;
1684
1685 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001686 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001687 break;
1688 }
1689
1690 return false;
1691}
1692
1693spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1694{
1695 // First, steer off constants, which are not SPIR-V variables, but
1696 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001697 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001698 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001699 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 }
1701
1702 // Now, handle actual variables
1703 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1704 spv::Id spvType = convertGlslangToSpvType(node->getType());
1705
1706 const char* name = node->getName().c_str();
1707 if (glslang::IsAnonymous(name))
1708 name = "";
1709
1710 return builder.createVariable(storageClass, spvType, name);
1711}
1712
1713// Return type Id of the sampled type.
1714spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1715{
1716 switch (sampler.type) {
1717 case glslang::EbtFloat: return builder.makeFloatType(32);
1718 case glslang::EbtInt: return builder.makeIntType(32);
1719 case glslang::EbtUint: return builder.makeUintType(32);
1720 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001721 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001722 return builder.makeFloatType(32);
1723 }
1724}
1725
John Kessenich3ac051e2015-12-20 11:29:16 -07001726// Convert from a glslang type to an SPV type, by calling into a
1727// recursive version of this function. This establishes the inherited
1728// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001729spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1730{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001731 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001732}
1733
1734// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001735// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001736spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001737{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001738 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001739
1740 switch (type.getBasicType()) {
1741 case glslang::EbtVoid:
1742 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001743 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001744 break;
1745 case glslang::EbtFloat:
1746 spvType = builder.makeFloatType(32);
1747 break;
1748 case glslang::EbtDouble:
1749 spvType = builder.makeFloatType(64);
1750 break;
1751 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001752 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1753 // a 32-bit int where non-0 means true.
1754 if (explicitLayout != glslang::ElpNone)
1755 spvType = builder.makeUintType(32);
1756 else
1757 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001758 break;
1759 case glslang::EbtInt:
1760 spvType = builder.makeIntType(32);
1761 break;
1762 case glslang::EbtUint:
1763 spvType = builder.makeUintType(32);
1764 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001765 case glslang::EbtInt64:
1766 builder.addCapability(spv::CapabilityInt64);
1767 spvType = builder.makeIntType(64);
1768 break;
1769 case glslang::EbtUint64:
1770 builder.addCapability(spv::CapabilityInt64);
1771 spvType = builder.makeUintType(64);
1772 break;
John Kessenich426394d2015-07-23 10:22:48 -06001773 case glslang::EbtAtomicUint:
1774 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1775 spvType = builder.makeUintType(32);
1776 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001777 case glslang::EbtSampler:
1778 {
1779 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001780 if (sampler.sampler) {
1781 // pure sampler
1782 spvType = builder.makeSamplerType();
1783 } else {
1784 // an image is present, make its type
1785 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1786 sampler.image ? 2 : 1, TranslateImageFormat(type));
1787 if (sampler.combined) {
1788 // already has both image and sampler, make the combined type
1789 spvType = builder.makeSampledImageType(spvType);
1790 }
John Kessenich55e7d112015-11-15 21:33:39 -07001791 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001792 }
John Kessenich140f3df2015-06-26 16:58:36 -06001793 break;
1794 case glslang::EbtStruct:
1795 case glslang::EbtBlock:
1796 {
1797 // If we've seen this struct type, return it
1798 const glslang::TTypeList* glslangStruct = type.getStruct();
1799 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001800
1801 // Try to share structs for different layouts, but not yet for other
1802 // kinds of qualification (primarily not yet including interpolant qualification).
1803 if (! HasNonLayoutQualifiers(qualifier))
1804 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1805 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001806 break;
1807
1808 // else, we haven't seen it...
1809
1810 // Create a vector of struct types for SPIR-V to consume
1811 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1812 if (type.getBasicType() == glslang::EbtBlock)
1813 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001814 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001815 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1816 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1817 if (glslangType.hiddenMember()) {
1818 ++memberDelta;
1819 if (type.getBasicType() == glslang::EbtBlock)
1820 memberRemapper[glslangStruct][i] = -1;
1821 } else {
1822 if (type.getBasicType() == glslang::EbtBlock)
1823 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001824 // modify just this child's view of the qualifier
1825 glslang::TQualifier subQualifier = glslangType.getQualifier();
1826 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001827
1828 // manually inherit location; it's more complex
1829 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1830 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1831 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001832 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001833
1834 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001835 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001836 }
1837 }
1838
1839 // Make the SPIR-V type
1840 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001841 if (! HasNonLayoutQualifiers(qualifier))
1842 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001843
1844 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001845 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001846 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001847 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1848 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1849 int member = i;
1850 if (type.getBasicType() == glslang::EbtBlock)
1851 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001852
John Kesseniche0b6cad2015-12-24 10:30:13 -07001853 // modify just this child's view of the qualifier
1854 glslang::TQualifier subQualifier = glslangType.getQualifier();
1855 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001856
John Kessenich140f3df2015-06-26 16:58:36 -06001857 // using -1 above to indicate a hidden member
1858 if (member >= 0) {
1859 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001860 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001861 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001862 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1863 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001864
Rex Xu1da878f2016-02-21 20:59:01 +08001865 if (qualifier.storage == glslang::EvqBuffer) {
1866 std::vector<spv::Decoration> memory;
1867 TranslateMemoryDecoration(subQualifier, memory);
1868 for (unsigned int i = 0; i < memory.size(); ++i)
1869 addMemberDecoration(spvType, member, memory[i]);
1870 }
1871
John Kessenich09677482016-02-19 12:21:50 -07001872 // compute location decoration; tricky based on whether inheritance is at play
1873 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1874 // probably move to the linker stage of the front end proper, and just have the
1875 // answer sitting already distributed throughout the individual member locations.
1876 int location = -1; // will only decorate if present or inherited
1877 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1878 location = subQualifier.layoutLocation;
1879 else if (qualifier.hasLocation()) // inheritance
1880 location = qualifier.layoutLocation + locationOffset;
1881 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001882 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001883 if (location >= 0)
1884 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1885
1886 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001887 if (glslangType.getQualifier().hasComponent())
1888 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1889 if (glslangType.getQualifier().hasXfbOffset())
1890 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001891 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001892 // figure out what to do with offset, which is accumulating
1893 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001894 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001895 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001896 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001897 offset = nextOffset;
1898 }
John Kessenich140f3df2015-06-26 16:58:36 -06001899
John Kessenichf85e8062015-12-19 13:57:10 -07001900 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001901 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001902
John Kessenich140f3df2015-06-26 16:58:36 -06001903 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001904 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1905 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001906 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001907 }
1908 }
1909
1910 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001911 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001912 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001913 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001914 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001915 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001916 }
John Kessenich140f3df2015-06-26 16:58:36 -06001917 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001918 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001919 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001920 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001921 if (type.getQualifier().hasXfbBuffer())
1922 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1923 }
1924 }
1925 break;
1926 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001927 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001928 break;
1929 }
1930
1931 if (type.isMatrix())
1932 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1933 else {
1934 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1935 if (type.getVectorSize() > 1)
1936 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1937 }
1938
1939 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001940 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1941
John Kessenichc9a80832015-09-12 12:17:44 -06001942 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001943 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001944 // We need to decorate array strides for types needing explicit layout, except blocks.
1945 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001946 // Use a dummy glslang type for querying internal strides of
1947 // arrays of arrays, but using just a one-dimensional array.
1948 glslang::TType simpleArrayType(type, 0); // deference type of the array
1949 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1950 simpleArrayType.getArraySizes().dereference();
1951
1952 // Will compute the higher-order strides here, rather than making a whole
1953 // pile of types and doing repetitive recursion on their contents.
1954 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1955 }
John Kessenichf8842e52016-01-04 19:22:56 -07001956
1957 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001958 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001959 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001960 if (stride > 0)
1961 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001962 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001963 }
1964 } else {
1965 // single-dimensional array, and don't yet have stride
1966
John Kessenichf8842e52016-01-04 19:22:56 -07001967 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001968 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1969 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001970 }
John Kessenich31ed4832015-09-09 17:51:38 -06001971
John Kessenichc9a80832015-09-12 12:17:44 -06001972 // Do the outer dimension, which might not be known for a runtime-sized array
1973 if (type.isRuntimeSizedArray()) {
1974 spvType = builder.makeRuntimeArray(spvType);
1975 } else {
1976 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001977 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001978 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001979 if (stride > 0)
1980 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001981 }
1982
1983 return spvType;
1984}
1985
John Kessenich6c292d32016-02-15 20:58:50 -07001986// Turn the expression forming the array size into an id.
1987// This is not quite trivial, because of specialization constants.
1988// Sometimes, a raw constant is turned into an Id, and sometimes
1989// a specialization constant expression is.
1990spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1991{
1992 // First, see if this is sized with a node, meaning a specialization constant:
1993 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1994 if (specNode != nullptr) {
1995 builder.clearAccessChain();
1996 specNode->traverse(this);
1997 return accessChainLoad(specNode->getAsTyped()->getType());
1998 }
1999
2000 // Otherwise, need a compile-time (front end) size, get it:
2001 int size = arraySizes.getDimSize(dim);
2002 assert(size > 0);
2003 return builder.makeUintConstant(size);
2004}
2005
John Kessenich103bef92016-02-08 21:38:15 -07002006// Wrap the builder's accessChainLoad to:
2007// - localize handling of RelaxedPrecision
2008// - use the SPIR-V inferred type instead of another conversion of the glslang type
2009// (avoids unnecessary work and possible type punning for structures)
2010// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002011spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2012{
John Kessenich103bef92016-02-08 21:38:15 -07002013 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2014 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2015
2016 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002017 if (type.getBasicType() == glslang::EbtBool) {
2018 if (builder.isScalarType(nominalTypeId)) {
2019 // Conversion for bool
2020 spv::Id boolType = builder.makeBoolType();
2021 if (nominalTypeId != boolType)
2022 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2023 } else if (builder.isVectorType(nominalTypeId)) {
2024 // Conversion for bvec
2025 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2026 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2027 if (nominalTypeId != bvecType)
2028 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2029 }
2030 }
John Kessenich103bef92016-02-08 21:38:15 -07002031
2032 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002033}
2034
Rex Xu27253232016-02-23 17:51:09 +08002035// Wrap the builder's accessChainStore to:
2036// - do conversion of concrete to abstract type
2037void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2038{
2039 // Need to convert to abstract types when necessary
2040 if (type.getBasicType() == glslang::EbtBool) {
2041 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2042
2043 if (builder.isScalarType(nominalTypeId)) {
2044 // Conversion for bool
2045 spv::Id boolType = builder.makeBoolType();
2046 if (nominalTypeId != boolType) {
2047 spv::Id zero = builder.makeUintConstant(0);
2048 spv::Id one = builder.makeUintConstant(1);
2049 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2050 }
2051 } else if (builder.isVectorType(nominalTypeId)) {
2052 // Conversion for bvec
2053 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2054 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2055 if (nominalTypeId != bvecType) {
2056 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2057 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2058 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2059 }
2060 }
2061 }
2062
2063 builder.accessChainStore(rvalue);
2064}
2065
John Kessenichf85e8062015-12-19 13:57:10 -07002066// Decide whether or not this type should be
2067// decorated with offsets and strides, and if so
2068// whether std140 or std430 rules should be applied.
2069glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002070{
John Kessenichf85e8062015-12-19 13:57:10 -07002071 // has to be a block
2072 if (type.getBasicType() != glslang::EbtBlock)
2073 return glslang::ElpNone;
2074
2075 // has to be a uniform or buffer block
2076 if (type.getQualifier().storage != glslang::EvqUniform &&
2077 type.getQualifier().storage != glslang::EvqBuffer)
2078 return glslang::ElpNone;
2079
2080 // return the layout to use
2081 switch (type.getQualifier().layoutPacking) {
2082 case glslang::ElpStd140:
2083 case glslang::ElpStd430:
2084 return type.getQualifier().layoutPacking;
2085 default:
2086 return glslang::ElpNone;
2087 }
John Kessenich31ed4832015-09-09 17:51:38 -06002088}
2089
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002090// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002091int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002092{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002093 int size;
John Kessenich49987892015-12-29 17:11:44 -07002094 int stride;
2095 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002096
2097 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002098}
2099
John Kessenich49987892015-12-29 17:11:44 -07002100// 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 -07002101// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002102int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002103{
John Kessenich49987892015-12-29 17:11:44 -07002104 glslang::TType elementType;
2105 elementType.shallowCopy(matrixType);
2106 elementType.clearArraySizes();
2107
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002108 int size;
John Kessenich49987892015-12-29 17:11:44 -07002109 int stride;
2110 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2111
2112 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002113}
2114
John Kessenich5e4b1242015-08-06 22:53:06 -06002115// Given a member type of a struct, realign the current offset for it, and compute
2116// the next (not yet aligned) offset for the next member, which will get aligned
2117// on the next call.
2118// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2119// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2120// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002121void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002122 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002123{
2124 // this will get a positive value when deemed necessary
2125 nextOffset = -1;
2126
John Kessenich5e4b1242015-08-06 22:53:06 -06002127 // override anything in currentOffset with user-set offset
2128 if (memberType.getQualifier().hasOffset())
2129 currentOffset = memberType.getQualifier().layoutOffset;
2130
2131 // It could be that current linker usage in glslang updated all the layoutOffset,
2132 // in which case the following code does not matter. But, that's not quite right
2133 // once cross-compilation unit GLSL validation is done, as the original user
2134 // settings are needed in layoutOffset, and then the following will come into play.
2135
John Kessenichf85e8062015-12-19 13:57:10 -07002136 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002137 if (! memberType.getQualifier().hasOffset())
2138 currentOffset = -1;
2139
2140 return;
2141 }
2142
John Kessenichf85e8062015-12-19 13:57:10 -07002143 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002144 if (currentOffset < 0)
2145 currentOffset = 0;
2146
2147 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2148 // but possibly not yet correctly aligned.
2149
2150 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002151 int dummyStride;
2152 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002153 glslang::RoundToPow2(currentOffset, memberAlignment);
2154 nextOffset = currentOffset + memberSize;
2155}
2156
John Kessenich140f3df2015-06-26 16:58:36 -06002157bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2158{
John Kessenich4d65ee32016-03-12 18:17:47 -07002159 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002160 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002161 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002162}
2163
2164// Make all the functions, skeletally, without actually visiting their bodies.
2165void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2166{
2167 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2168 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2169 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2170 continue;
2171
2172 // We're on a user function. Set up the basic interface for the function now,
2173 // so that it's available to call.
2174 // Translating the body will happen later.
2175 //
2176 // Typically (except for a "const in" parameter), an address will be passed to the
2177 // function. What it is an address of varies:
2178 //
2179 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2180 // so that write needs to be to a copy, hence the address of a copy works.
2181 //
2182 // - "const in" parameters can just be the r-value, as no writes need occur.
2183 //
2184 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2185 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2186
2187 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002188 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002189 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2190
2191 for (int p = 0; p < (int)parameters.size(); ++p) {
2192 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2193 spv::Id typeId = convertGlslangToSpvType(paramType);
2194 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2195 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2196 else
2197 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002198 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002199 paramTypes.push_back(typeId);
2200 }
2201
2202 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002203 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2204 convertGlslangToSpvType(glslFunction->getType()),
2205 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002206
2207 // Track function to emit/call later
2208 functionMap[glslFunction->getName().c_str()] = function;
2209
2210 // Set the parameter id's
2211 for (int p = 0; p < (int)parameters.size(); ++p) {
2212 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2213 // give a name too
2214 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2215 }
2216 }
2217}
2218
2219// Process all the initializers, while skipping the functions and link objects
2220void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2221{
2222 builder.setBuildPoint(shaderEntry->getLastBlock());
2223 for (int i = 0; i < (int)initializers.size(); ++i) {
2224 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2225 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2226
2227 // We're on a top-level node that's not a function. Treat as an initializer, whose
2228 // code goes into the beginning of main.
2229 initializer->traverse(this);
2230 }
2231 }
2232}
2233
2234// Process all the functions, while skipping initializers.
2235void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2236{
2237 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2238 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2239 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2240 node->traverse(this);
2241 }
2242}
2243
2244void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2245{
2246 // SPIR-V functions should already be in the functionMap from the prepass
2247 // that called makeFunctions().
2248 spv::Function* function = functionMap[node->getName().c_str()];
2249 spv::Block* functionBlock = function->getEntryBlock();
2250 builder.setBuildPoint(functionBlock);
2251}
2252
Rex Xu04db3f52015-09-16 11:44:02 +08002253void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002254{
Rex Xufc618912015-09-09 16:42:49 +08002255 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002256
2257 glslang::TSampler sampler = {};
2258 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002259 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002260 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2261 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2262 }
2263
John Kessenich140f3df2015-06-26 16:58:36 -06002264 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2265 builder.clearAccessChain();
2266 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002267
2268 // Special case l-value operands
2269 bool lvalue = false;
2270 switch (node.getOp()) {
2271 case glslang::EOpImageAtomicAdd:
2272 case glslang::EOpImageAtomicMin:
2273 case glslang::EOpImageAtomicMax:
2274 case glslang::EOpImageAtomicAnd:
2275 case glslang::EOpImageAtomicOr:
2276 case glslang::EOpImageAtomicXor:
2277 case glslang::EOpImageAtomicExchange:
2278 case glslang::EOpImageAtomicCompSwap:
2279 if (i == 0)
2280 lvalue = true;
2281 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002282 case glslang::EOpSparseImageLoad:
2283 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2284 lvalue = true;
2285 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002286 case glslang::EOpSparseTexture:
2287 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2288 lvalue = true;
2289 break;
2290 case glslang::EOpSparseTextureClamp:
2291 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2292 lvalue = true;
2293 break;
2294 case glslang::EOpSparseTextureLod:
2295 case glslang::EOpSparseTextureOffset:
2296 if (i == 3)
2297 lvalue = true;
2298 break;
2299 case glslang::EOpSparseTextureFetch:
2300 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2301 lvalue = true;
2302 break;
2303 case glslang::EOpSparseTextureFetchOffset:
2304 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2305 lvalue = true;
2306 break;
2307 case glslang::EOpSparseTextureLodOffset:
2308 case glslang::EOpSparseTextureGrad:
2309 case glslang::EOpSparseTextureOffsetClamp:
2310 if (i == 4)
2311 lvalue = true;
2312 break;
2313 case glslang::EOpSparseTextureGradOffset:
2314 case glslang::EOpSparseTextureGradClamp:
2315 if (i == 5)
2316 lvalue = true;
2317 break;
2318 case glslang::EOpSparseTextureGradOffsetClamp:
2319 if (i == 6)
2320 lvalue = true;
2321 break;
2322 case glslang::EOpSparseTextureGather:
2323 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2324 lvalue = true;
2325 break;
2326 case glslang::EOpSparseTextureGatherOffset:
2327 case glslang::EOpSparseTextureGatherOffsets:
2328 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2329 lvalue = true;
2330 break;
Rex Xufc618912015-09-09 16:42:49 +08002331 default:
2332 break;
2333 }
2334
Rex Xu6b86d492015-09-16 17:48:22 +08002335 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002336 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002337 else
John Kessenich32cfd492016-02-02 12:37:46 -07002338 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002339 }
2340}
2341
John Kessenichfc51d282015-08-19 13:34:18 -06002342void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002343{
John Kessenichfc51d282015-08-19 13:34:18 -06002344 builder.clearAccessChain();
2345 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002346 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002347}
John Kessenich140f3df2015-06-26 16:58:36 -06002348
John Kessenichfc51d282015-08-19 13:34:18 -06002349spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2350{
Rex Xufc618912015-09-09 16:42:49 +08002351 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002352 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002353 }
2354
John Kessenichfc51d282015-08-19 13:34:18 -06002355 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002356 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2357 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2358 std::vector<spv::Id> arguments;
2359 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002360 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002361 else
2362 translateArguments(*node->getAsUnaryNode(), arguments);
2363 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2364
2365 spv::Builder::TextureParameters params = { };
2366 params.sampler = arguments[0];
2367
Rex Xu04db3f52015-09-16 11:44:02 +08002368 glslang::TCrackedTextureOp cracked;
2369 node->crackTexture(sampler, cracked);
2370
John Kessenichfc51d282015-08-19 13:34:18 -06002371 // Check for queries
2372 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002373 // a sampled image needs to have the image extracted first
2374 if (builder.isSampledImage(params.sampler))
2375 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002376 switch (node->getOp()) {
2377 case glslang::EOpImageQuerySize:
2378 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002379 if (arguments.size() > 1) {
2380 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002381 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002382 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002383 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002384 case glslang::EOpImageQuerySamples:
2385 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002386 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002387 case glslang::EOpTextureQueryLod:
2388 params.coords = arguments[1];
2389 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2390 case glslang::EOpTextureQueryLevels:
2391 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002392 case glslang::EOpSparseTexelsResident:
2393 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002394 default:
2395 assert(0);
2396 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002397 }
John Kessenich140f3df2015-06-26 16:58:36 -06002398 }
2399
Rex Xufc618912015-09-09 16:42:49 +08002400 // Check for image functions other than queries
2401 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002402 std::vector<spv::Id> operands;
2403 auto opIt = arguments.begin();
2404 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002405
2406 // Handle subpass operations
2407 // TODO: GLSL should change to have the "MS" only on the type rather than the
2408 // built-in function.
2409 if (cracked.subpass) {
2410 // add on the (0,0) coordinate
2411 spv::Id zero = builder.makeIntConstant(0);
2412 std::vector<spv::Id> comps;
2413 comps.push_back(zero);
2414 comps.push_back(zero);
2415 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2416 if (sampler.ms) {
2417 operands.push_back(spv::ImageOperandsSampleMask);
2418 operands.push_back(*(opIt++));
2419 }
2420 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2421 }
2422
John Kessenich56bab042015-09-16 10:54:31 -06002423 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002424 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002425 if (sampler.ms) {
2426 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002427 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002428 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002429 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2430 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002431 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002432 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002433 if (sampler.ms) {
2434 operands.push_back(*(opIt + 1));
2435 operands.push_back(spv::ImageOperandsSampleMask);
2436 operands.push_back(*opIt);
2437 } else
2438 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002439 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002440 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2441 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002442 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002443 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2444 builder.addCapability(spv::CapabilitySparseResidency);
2445 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2446 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2447
2448 if (sampler.ms) {
2449 operands.push_back(spv::ImageOperandsSampleMask);
2450 operands.push_back(*opIt++);
2451 }
2452
2453 // Create the return type that was a special structure
2454 spv::Id texelOut = *opIt;
2455 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2456 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2457 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2458
2459 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2460
2461 // Decode the return type
2462 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2463 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002464 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002465 // Process image atomic operations
2466
2467 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2468 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002469 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002470
Rex Xufc618912015-09-09 16:42:49 +08002471 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002472 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002473
2474 std::vector<spv::Id> operands;
2475 operands.push_back(pointer);
2476 for (; opIt != arguments.end(); ++opIt)
2477 operands.push_back(*opIt);
2478
Rex Xu04db3f52015-09-16 11:44:02 +08002479 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002480 }
2481 }
2482
2483 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002484 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002485 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2486
John Kessenichfc51d282015-08-19 13:34:18 -06002487 // check for bias argument
2488 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002489 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002490 int nonBiasArgCount = 2;
2491 if (cracked.offset)
2492 ++nonBiasArgCount;
2493 if (cracked.grad)
2494 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002495 if (cracked.lodClamp)
2496 ++nonBiasArgCount;
2497 if (sparse)
2498 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002499
2500 if ((int)arguments.size() > nonBiasArgCount)
2501 bias = true;
2502 }
2503
John Kessenichfc51d282015-08-19 13:34:18 -06002504 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002505
John Kessenichfc51d282015-08-19 13:34:18 -06002506 params.coords = arguments[1];
2507 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002508 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002509
2510 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002511 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002512 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002513 ++extraArgs;
2514 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002515 params.Dref = arguments[2];
2516 ++extraArgs;
2517 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002518 std::vector<spv::Id> indexes;
2519 int comp;
2520 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002521 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002522 else
2523 comp = builder.getNumComponents(params.coords) - 1;
2524 indexes.push_back(comp);
2525 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2526 }
2527 if (cracked.lod) {
2528 params.lod = arguments[2];
2529 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002530 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2531 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2532 noImplicitLod = true;
2533 }
2534 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002535 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002536 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002537 }
2538 if (cracked.grad) {
2539 params.gradX = arguments[2 + extraArgs];
2540 params.gradY = arguments[3 + extraArgs];
2541 extraArgs += 2;
2542 }
John Kessenich55e7d112015-11-15 21:33:39 -07002543 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002544 params.offset = arguments[2 + extraArgs];
2545 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002546 } else if (cracked.offsets) {
2547 params.offsets = arguments[2 + extraArgs];
2548 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002549 }
Rex Xu48edadf2015-12-31 16:11:41 +08002550 if (cracked.lodClamp) {
2551 params.lodClamp = arguments[2 + extraArgs];
2552 ++extraArgs;
2553 }
2554 if (sparse) {
2555 params.texelOut = arguments[2 + extraArgs];
2556 ++extraArgs;
2557 }
John Kessenichfc51d282015-08-19 13:34:18 -06002558 if (bias) {
2559 params.bias = arguments[2 + extraArgs];
2560 ++extraArgs;
2561 }
John Kessenich55e7d112015-11-15 21:33:39 -07002562 if (cracked.gather && ! sampler.shadow) {
2563 // default component is 0, if missing, otherwise an argument
2564 if (2 + extraArgs < (int)arguments.size()) {
2565 params.comp = arguments[2 + extraArgs];
2566 ++extraArgs;
2567 } else {
2568 params.comp = builder.makeIntConstant(0);
2569 }
2570 }
John Kessenichfc51d282015-08-19 13:34:18 -06002571
John Kessenich019f08f2016-02-15 15:40:42 -07002572 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002573}
2574
2575spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2576{
2577 // Grab the function's pointer from the previously created function
2578 spv::Function* function = functionMap[node->getName().c_str()];
2579 if (! function)
2580 return 0;
2581
2582 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2583 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2584
2585 // See comments in makeFunctions() for details about the semantics for parameter passing.
2586 //
2587 // These imply we need a four step process:
2588 // 1. Evaluate the arguments
2589 // 2. Allocate and make copies of in, out, and inout arguments
2590 // 3. Make the call
2591 // 4. Copy back the results
2592
2593 // 1. Evaluate the arguments
2594 std::vector<spv::Builder::AccessChain> lValues;
2595 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002596 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002597 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2598 // build l-value
2599 builder.clearAccessChain();
2600 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002601 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002602 // keep outputs as l-values, evaluate input-only as r-values
2603 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2604 // save l-value
2605 lValues.push_back(builder.getAccessChain());
2606 } else {
2607 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002608 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002609 }
2610 }
2611
2612 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2613 // copy the original into that space.
2614 //
2615 // Also, build up the list of actual arguments to pass in for the call
2616 int lValueCount = 0;
2617 int rValueCount = 0;
2618 std::vector<spv::Id> spvArgs;
2619 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2620 spv::Id arg;
2621 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2622 // need space to hold the copy
2623 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2624 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2625 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2626 // need to copy the input into output space
2627 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002628 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002629 builder.createStore(copy, arg);
2630 }
2631 ++lValueCount;
2632 } else {
2633 arg = rValues[rValueCount];
2634 ++rValueCount;
2635 }
2636 spvArgs.push_back(arg);
2637 }
2638
2639 // 3. Make the call.
2640 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002641 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002642
2643 // 4. Copy back out an "out" arguments.
2644 lValueCount = 0;
2645 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2646 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2647 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2648 spv::Id copy = builder.createLoad(spvArgs[a]);
2649 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002650 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002651 }
2652 ++lValueCount;
2653 }
2654 }
2655
2656 return result;
2657}
2658
2659// Translate AST operation to SPV operation, already having SPV-based operands/types.
2660spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2661 spv::Id typeId, spv::Id left, spv::Id right,
2662 glslang::TBasicType typeProxy, bool reduceComparison)
2663{
Rex Xu8ff43de2016-04-22 16:51:45 +08002664 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002665 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002666 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002667
2668 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002669 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002670 bool comparison = false;
2671
2672 switch (op) {
2673 case glslang::EOpAdd:
2674 case glslang::EOpAddAssign:
2675 if (isFloat)
2676 binOp = spv::OpFAdd;
2677 else
2678 binOp = spv::OpIAdd;
2679 break;
2680 case glslang::EOpSub:
2681 case glslang::EOpSubAssign:
2682 if (isFloat)
2683 binOp = spv::OpFSub;
2684 else
2685 binOp = spv::OpISub;
2686 break;
2687 case glslang::EOpMul:
2688 case glslang::EOpMulAssign:
2689 if (isFloat)
2690 binOp = spv::OpFMul;
2691 else
2692 binOp = spv::OpIMul;
2693 break;
2694 case glslang::EOpVectorTimesScalar:
2695 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002696 if (isFloat) {
2697 if (builder.isVector(right))
2698 std::swap(left, right);
2699 assert(builder.isScalar(right));
2700 needMatchingVectors = false;
2701 binOp = spv::OpVectorTimesScalar;
2702 } else
2703 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002704 break;
2705 case glslang::EOpVectorTimesMatrix:
2706 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002707 binOp = spv::OpVectorTimesMatrix;
2708 break;
2709 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002710 binOp = spv::OpMatrixTimesVector;
2711 break;
2712 case glslang::EOpMatrixTimesScalar:
2713 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002714 binOp = spv::OpMatrixTimesScalar;
2715 break;
2716 case glslang::EOpMatrixTimesMatrix:
2717 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002718 binOp = spv::OpMatrixTimesMatrix;
2719 break;
2720 case glslang::EOpOuterProduct:
2721 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002722 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002723 break;
2724
2725 case glslang::EOpDiv:
2726 case glslang::EOpDivAssign:
2727 if (isFloat)
2728 binOp = spv::OpFDiv;
2729 else if (isUnsigned)
2730 binOp = spv::OpUDiv;
2731 else
2732 binOp = spv::OpSDiv;
2733 break;
2734 case glslang::EOpMod:
2735 case glslang::EOpModAssign:
2736 if (isFloat)
2737 binOp = spv::OpFMod;
2738 else if (isUnsigned)
2739 binOp = spv::OpUMod;
2740 else
2741 binOp = spv::OpSMod;
2742 break;
2743 case glslang::EOpRightShift:
2744 case glslang::EOpRightShiftAssign:
2745 if (isUnsigned)
2746 binOp = spv::OpShiftRightLogical;
2747 else
2748 binOp = spv::OpShiftRightArithmetic;
2749 break;
2750 case glslang::EOpLeftShift:
2751 case glslang::EOpLeftShiftAssign:
2752 binOp = spv::OpShiftLeftLogical;
2753 break;
2754 case glslang::EOpAnd:
2755 case glslang::EOpAndAssign:
2756 binOp = spv::OpBitwiseAnd;
2757 break;
2758 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002759 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002760 binOp = spv::OpLogicalAnd;
2761 break;
2762 case glslang::EOpInclusiveOr:
2763 case glslang::EOpInclusiveOrAssign:
2764 binOp = spv::OpBitwiseOr;
2765 break;
2766 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002767 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002768 binOp = spv::OpLogicalOr;
2769 break;
2770 case glslang::EOpExclusiveOr:
2771 case glslang::EOpExclusiveOrAssign:
2772 binOp = spv::OpBitwiseXor;
2773 break;
2774 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002775 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002776 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002777 break;
2778
2779 case glslang::EOpLessThan:
2780 case glslang::EOpGreaterThan:
2781 case glslang::EOpLessThanEqual:
2782 case glslang::EOpGreaterThanEqual:
2783 case glslang::EOpEqual:
2784 case glslang::EOpNotEqual:
2785 case glslang::EOpVectorEqual:
2786 case glslang::EOpVectorNotEqual:
2787 comparison = true;
2788 break;
2789 default:
2790 break;
2791 }
2792
John Kessenich7c1aa102015-10-15 13:29:11 -06002793 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002794 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002795 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002796 if (builder.isMatrix(left) || builder.isMatrix(right))
2797 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002798
2799 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002800 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002801 builder.promoteScalar(precision, left, right);
2802
John Kessenich32cfd492016-02-02 12:37:46 -07002803 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002804 }
2805
2806 if (! comparison)
2807 return 0;
2808
John Kessenich7c1aa102015-10-15 13:29:11 -06002809 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002810
2811 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2812 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2813
John Kessenich22118352015-12-21 20:54:09 -07002814 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002815 }
2816
2817 switch (op) {
2818 case glslang::EOpLessThan:
2819 if (isFloat)
2820 binOp = spv::OpFOrdLessThan;
2821 else if (isUnsigned)
2822 binOp = spv::OpULessThan;
2823 else
2824 binOp = spv::OpSLessThan;
2825 break;
2826 case glslang::EOpGreaterThan:
2827 if (isFloat)
2828 binOp = spv::OpFOrdGreaterThan;
2829 else if (isUnsigned)
2830 binOp = spv::OpUGreaterThan;
2831 else
2832 binOp = spv::OpSGreaterThan;
2833 break;
2834 case glslang::EOpLessThanEqual:
2835 if (isFloat)
2836 binOp = spv::OpFOrdLessThanEqual;
2837 else if (isUnsigned)
2838 binOp = spv::OpULessThanEqual;
2839 else
2840 binOp = spv::OpSLessThanEqual;
2841 break;
2842 case glslang::EOpGreaterThanEqual:
2843 if (isFloat)
2844 binOp = spv::OpFOrdGreaterThanEqual;
2845 else if (isUnsigned)
2846 binOp = spv::OpUGreaterThanEqual;
2847 else
2848 binOp = spv::OpSGreaterThanEqual;
2849 break;
2850 case glslang::EOpEqual:
2851 case glslang::EOpVectorEqual:
2852 if (isFloat)
2853 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002854 else if (isBool)
2855 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002856 else
2857 binOp = spv::OpIEqual;
2858 break;
2859 case glslang::EOpNotEqual:
2860 case glslang::EOpVectorNotEqual:
2861 if (isFloat)
2862 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002863 else if (isBool)
2864 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002865 else
2866 binOp = spv::OpINotEqual;
2867 break;
2868 default:
2869 break;
2870 }
2871
John Kessenich32cfd492016-02-02 12:37:46 -07002872 if (binOp != spv::OpNop)
2873 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002874
2875 return 0;
2876}
2877
John Kessenich04bb8a02015-12-12 12:28:14 -07002878//
2879// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2880// These can be any of:
2881//
2882// matrix * scalar
2883// scalar * matrix
2884// matrix * matrix linear algebraic
2885// matrix * vector
2886// vector * matrix
2887// matrix * matrix componentwise
2888// matrix op matrix op in {+, -, /}
2889// matrix op scalar op in {+, -, /}
2890// scalar op matrix op in {+, -, /}
2891//
2892spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2893{
2894 bool firstClass = true;
2895
2896 // First, handle first-class matrix operations (* and matrix/scalar)
2897 switch (op) {
2898 case spv::OpFDiv:
2899 if (builder.isMatrix(left) && builder.isScalar(right)) {
2900 // turn matrix / scalar into a multiply...
2901 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2902 op = spv::OpMatrixTimesScalar;
2903 } else
2904 firstClass = false;
2905 break;
2906 case spv::OpMatrixTimesScalar:
2907 if (builder.isMatrix(right))
2908 std::swap(left, right);
2909 assert(builder.isScalar(right));
2910 break;
2911 case spv::OpVectorTimesMatrix:
2912 assert(builder.isVector(left));
2913 assert(builder.isMatrix(right));
2914 break;
2915 case spv::OpMatrixTimesVector:
2916 assert(builder.isMatrix(left));
2917 assert(builder.isVector(right));
2918 break;
2919 case spv::OpMatrixTimesMatrix:
2920 assert(builder.isMatrix(left));
2921 assert(builder.isMatrix(right));
2922 break;
2923 default:
2924 firstClass = false;
2925 break;
2926 }
2927
John Kessenich32cfd492016-02-02 12:37:46 -07002928 if (firstClass)
2929 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002930
2931 // Handle component-wise +, -, *, and / for all combinations of type.
2932 // The result type of all of them is the same type as the (a) matrix operand.
2933 // The algorithm is to:
2934 // - break the matrix(es) into vectors
2935 // - smear any scalar to a vector
2936 // - do vector operations
2937 // - make a matrix out the vector results
2938 switch (op) {
2939 case spv::OpFAdd:
2940 case spv::OpFSub:
2941 case spv::OpFDiv:
2942 case spv::OpFMul:
2943 {
2944 // one time set up...
2945 bool leftMat = builder.isMatrix(left);
2946 bool rightMat = builder.isMatrix(right);
2947 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2948 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2949 spv::Id scalarType = builder.getScalarTypeId(typeId);
2950 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2951 std::vector<spv::Id> results;
2952 spv::Id smearVec = spv::NoResult;
2953 if (builder.isScalar(left))
2954 smearVec = builder.smearScalar(precision, left, vecType);
2955 else if (builder.isScalar(right))
2956 smearVec = builder.smearScalar(precision, right, vecType);
2957
2958 // do each vector op
2959 for (unsigned int c = 0; c < numCols; ++c) {
2960 std::vector<unsigned int> indexes;
2961 indexes.push_back(c);
2962 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2963 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2964 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2965 builder.setPrecision(results.back(), precision);
2966 }
2967
2968 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002969 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002970 }
2971 default:
2972 assert(0);
2973 return spv::NoResult;
2974 }
2975}
2976
Rex Xu04db3f52015-09-16 11:44:02 +08002977spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06002978{
2979 spv::Op unaryOp = spv::OpNop;
2980 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08002981 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08002982 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002983
2984 switch (op) {
2985 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002986 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002987 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002988 if (builder.isMatrixType(typeId))
2989 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2990 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002991 unaryOp = spv::OpSNegate;
2992 break;
2993
2994 case glslang::EOpLogicalNot:
2995 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002996 unaryOp = spv::OpLogicalNot;
2997 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002998 case glslang::EOpBitwiseNot:
2999 unaryOp = spv::OpNot;
3000 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003001
John Kessenich140f3df2015-06-26 16:58:36 -06003002 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003003 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003004 break;
3005 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpTranspose:
3009 unaryOp = spv::OpTranspose;
3010 break;
3011
3012 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003013 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003014 break;
3015 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003017 break;
3018 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003019 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 break;
3021 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003022 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003023 break;
3024 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 break;
3027 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003028 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 break;
3030 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003031 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 break;
3033 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003034 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003035 break;
3036
3037 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003050 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
3052 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003053 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003054 break;
3055
3056 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003057 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003058 break;
3059 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003060 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003061 break;
3062
3063 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003064 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003065 break;
3066 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003067 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003068 break;
3069 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003070 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003071 break;
3072 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003073 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003074 break;
3075 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003076 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003077 break;
3078 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003079 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003080 break;
3081
3082 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003083 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003084 break;
3085 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 break;
3088 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003089 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003090 break;
3091 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003095 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
3097 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003098 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003099 break;
3100
3101 case glslang::EOpIsNan:
3102 unaryOp = spv::OpIsNan;
3103 break;
3104 case glslang::EOpIsInf:
3105 unaryOp = spv::OpIsInf;
3106 break;
3107
Rex Xucbc426e2015-12-15 16:03:10 +08003108 case glslang::EOpFloatBitsToInt:
3109 case glslang::EOpFloatBitsToUint:
3110 case glslang::EOpIntBitsToFloat:
3111 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003112 case glslang::EOpDoubleBitsToInt64:
3113 case glslang::EOpDoubleBitsToUint64:
3114 case glslang::EOpInt64BitsToDouble:
3115 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003116 unaryOp = spv::OpBitcast;
3117 break;
3118
John Kessenich140f3df2015-06-26 16:58:36 -06003119 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003135 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003136 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003137 case glslang::EOpPackSnorm4x8:
3138 libCall = spv::GLSLstd450PackSnorm4x8;
3139 break;
3140 case glslang::EOpUnpackSnorm4x8:
3141 libCall = spv::GLSLstd450UnpackSnorm4x8;
3142 break;
3143 case glslang::EOpPackUnorm4x8:
3144 libCall = spv::GLSLstd450PackUnorm4x8;
3145 break;
3146 case glslang::EOpUnpackUnorm4x8:
3147 libCall = spv::GLSLstd450UnpackUnorm4x8;
3148 break;
3149 case glslang::EOpPackDouble2x32:
3150 libCall = spv::GLSLstd450PackDouble2x32;
3151 break;
3152 case glslang::EOpUnpackDouble2x32:
3153 libCall = spv::GLSLstd450UnpackDouble2x32;
3154 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003155
Rex Xu8ff43de2016-04-22 16:51:45 +08003156 case glslang::EOpPackInt2x32:
3157 case glslang::EOpUnpackInt2x32:
3158 case glslang::EOpPackUint2x32:
3159 case glslang::EOpUnpackUint2x32:
3160 spv::MissingFunctionality("shader int64");
3161 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3162 break;
3163
John Kessenich140f3df2015-06-26 16:58:36 -06003164 case glslang::EOpDPdx:
3165 unaryOp = spv::OpDPdx;
3166 break;
3167 case glslang::EOpDPdy:
3168 unaryOp = spv::OpDPdy;
3169 break;
3170 case glslang::EOpFwidth:
3171 unaryOp = spv::OpFwidth;
3172 break;
3173 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003174 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003175 unaryOp = spv::OpDPdxFine;
3176 break;
3177 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003178 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003179 unaryOp = spv::OpDPdyFine;
3180 break;
3181 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003182 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003183 unaryOp = spv::OpFwidthFine;
3184 break;
3185 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003186 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003187 unaryOp = spv::OpDPdxCoarse;
3188 break;
3189 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003190 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003191 unaryOp = spv::OpDPdyCoarse;
3192 break;
3193 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003194 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003195 unaryOp = spv::OpFwidthCoarse;
3196 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003197 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003198 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003199 libCall = spv::GLSLstd450InterpolateAtCentroid;
3200 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003201 case glslang::EOpAny:
3202 unaryOp = spv::OpAny;
3203 break;
3204 case glslang::EOpAll:
3205 unaryOp = spv::OpAll;
3206 break;
3207
3208 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003209 if (isFloat)
3210 libCall = spv::GLSLstd450FAbs;
3211 else
3212 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003213 break;
3214 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003215 if (isFloat)
3216 libCall = spv::GLSLstd450FSign;
3217 else
3218 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003219 break;
3220
John Kessenichfc51d282015-08-19 13:34:18 -06003221 case glslang::EOpAtomicCounterIncrement:
3222 case glslang::EOpAtomicCounterDecrement:
3223 case glslang::EOpAtomicCounter:
3224 {
3225 // Handle all of the atomics in one place, in createAtomicOperation()
3226 std::vector<spv::Id> operands;
3227 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003228 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003229 }
3230
John Kessenichfc51d282015-08-19 13:34:18 -06003231 case glslang::EOpBitFieldReverse:
3232 unaryOp = spv::OpBitReverse;
3233 break;
3234 case glslang::EOpBitCount:
3235 unaryOp = spv::OpBitCount;
3236 break;
3237 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003238 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003239 break;
3240 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003241 if (isUnsigned)
3242 libCall = spv::GLSLstd450FindUMsb;
3243 else
3244 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003245 break;
3246
Rex Xu574ab042016-04-14 16:53:07 +08003247 case glslang::EOpBallot:
3248 case glslang::EOpReadFirstInvocation:
3249 spv::MissingFunctionality("shader ballot");
3250 libCall = spv::GLSLstd450Bad;
3251 break;
3252
John Kessenich140f3df2015-06-26 16:58:36 -06003253 default:
3254 return 0;
3255 }
3256
3257 spv::Id id;
3258 if (libCall >= 0) {
3259 std::vector<spv::Id> args;
3260 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003261 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003262 } else
3263 id = builder.createUnaryOp(unaryOp, typeId, operand);
3264
John Kessenich32cfd492016-02-02 12:37:46 -07003265 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003266}
3267
John Kessenich7a53f762016-01-20 11:19:27 -07003268// Create a unary operation on a matrix
3269spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3270{
3271 // Handle unary operations vector by vector.
3272 // The result type is the same type as the original type.
3273 // The algorithm is to:
3274 // - break the matrix into vectors
3275 // - apply the operation to each vector
3276 // - make a matrix out the vector results
3277
3278 // get the types sorted out
3279 int numCols = builder.getNumColumns(operand);
3280 int numRows = builder.getNumRows(operand);
3281 spv::Id scalarType = builder.getScalarTypeId(typeId);
3282 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3283 std::vector<spv::Id> results;
3284
3285 // do each vector op
3286 for (int c = 0; c < numCols; ++c) {
3287 std::vector<unsigned int> indexes;
3288 indexes.push_back(c);
3289 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3290 results.push_back(builder.createUnaryOp(op, vecType, vec));
3291 builder.setPrecision(results.back(), precision);
3292 }
3293
3294 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003295 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003296}
3297
John Kessenich140f3df2015-06-26 16:58:36 -06003298spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3299{
3300 spv::Op convOp = spv::OpNop;
3301 spv::Id zero = 0;
3302 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003303 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003304
3305 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3306
3307 switch (op) {
3308 case glslang::EOpConvIntToBool:
3309 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003310 case glslang::EOpConvInt64ToBool:
3311 case glslang::EOpConvUint64ToBool:
3312 zero = (op == glslang::EOpConvInt64ToBool ||
3313 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003314 zero = makeSmearedConstant(zero, vectorSize);
3315 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3316
3317 case glslang::EOpConvFloatToBool:
3318 zero = builder.makeFloatConstant(0.0F);
3319 zero = makeSmearedConstant(zero, vectorSize);
3320 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3321
3322 case glslang::EOpConvDoubleToBool:
3323 zero = builder.makeDoubleConstant(0.0);
3324 zero = makeSmearedConstant(zero, vectorSize);
3325 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3326
3327 case glslang::EOpConvBoolToFloat:
3328 convOp = spv::OpSelect;
3329 zero = builder.makeFloatConstant(0.0);
3330 one = builder.makeFloatConstant(1.0);
3331 break;
3332 case glslang::EOpConvBoolToDouble:
3333 convOp = spv::OpSelect;
3334 zero = builder.makeDoubleConstant(0.0);
3335 one = builder.makeDoubleConstant(1.0);
3336 break;
3337 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003338 case glslang::EOpConvBoolToInt64:
3339 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3340 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003341 convOp = spv::OpSelect;
3342 break;
3343 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003344 case glslang::EOpConvBoolToUint64:
3345 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3346 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003347 convOp = spv::OpSelect;
3348 break;
3349
3350 case glslang::EOpConvIntToFloat:
3351 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003352 case glslang::EOpConvInt64ToFloat:
3353 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003354 convOp = spv::OpConvertSToF;
3355 break;
3356
3357 case glslang::EOpConvUintToFloat:
3358 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003359 case glslang::EOpConvUint64ToFloat:
3360 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003361 convOp = spv::OpConvertUToF;
3362 break;
3363
3364 case glslang::EOpConvDoubleToFloat:
3365 case glslang::EOpConvFloatToDouble:
3366 convOp = spv::OpFConvert;
3367 break;
3368
3369 case glslang::EOpConvFloatToInt:
3370 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003371 case glslang::EOpConvFloatToInt64:
3372 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003373 convOp = spv::OpConvertFToS;
3374 break;
3375
3376 case glslang::EOpConvUintToInt:
3377 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003378 case glslang::EOpConvUint64ToInt64:
3379 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003380 if (builder.isInSpecConstCodeGenMode()) {
3381 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003382 zero = (op == glslang::EOpConvUintToInt64 ||
3383 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003384 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003385 // Use OpIAdd, instead of OpBitcast to do the conversion when
3386 // generating for OpSpecConstantOp instruction.
3387 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3388 }
3389 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003390 convOp = spv::OpBitcast;
3391 break;
3392
3393 case glslang::EOpConvFloatToUint:
3394 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003395 case glslang::EOpConvFloatToUint64:
3396 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003397 convOp = spv::OpConvertFToU;
3398 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003399
3400 case glslang::EOpConvIntToInt64:
3401 case glslang::EOpConvInt64ToInt:
3402 convOp = spv::OpSConvert;
3403 break;
3404
3405 case glslang::EOpConvUintToUint64:
3406 case glslang::EOpConvUint64ToUint:
3407 convOp = spv::OpUConvert;
3408 break;
3409
3410 case glslang::EOpConvIntToUint64:
3411 case glslang::EOpConvInt64ToUint:
3412 case glslang::EOpConvUint64ToInt:
3413 case glslang::EOpConvUintToInt64:
3414 // OpSConvert/OpUConvert + OpBitCast
3415 switch (op) {
3416 case glslang::EOpConvIntToUint64:
3417 convOp = spv::OpSConvert;
3418 type = builder.makeIntType(64);
3419 break;
3420 case glslang::EOpConvInt64ToUint:
3421 convOp = spv::OpSConvert;
3422 type = builder.makeIntType(32);
3423 break;
3424 case glslang::EOpConvUint64ToInt:
3425 convOp = spv::OpUConvert;
3426 type = builder.makeUintType(32);
3427 break;
3428 case glslang::EOpConvUintToInt64:
3429 convOp = spv::OpUConvert;
3430 type = builder.makeUintType(64);
3431 break;
3432 default:
3433 assert(0);
3434 break;
3435 }
3436
3437 if (vectorSize > 0)
3438 type = builder.makeVectorType(type, vectorSize);
3439
3440 operand = builder.createUnaryOp(convOp, type, operand);
3441
3442 if (builder.isInSpecConstCodeGenMode()) {
3443 // Build zero scalar or vector for OpIAdd.
3444 zero = (op == glslang::EOpConvIntToUint64 ||
3445 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3446 zero = makeSmearedConstant(zero, vectorSize);
3447 // Use OpIAdd, instead of OpBitcast to do the conversion when
3448 // generating for OpSpecConstantOp instruction.
3449 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3450 }
3451 // For normal run-time conversion instruction, use OpBitcast.
3452 convOp = spv::OpBitcast;
3453 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003454 default:
3455 break;
3456 }
3457
3458 spv::Id result = 0;
3459 if (convOp == spv::OpNop)
3460 return result;
3461
3462 if (convOp == spv::OpSelect) {
3463 zero = makeSmearedConstant(zero, vectorSize);
3464 one = makeSmearedConstant(one, vectorSize);
3465 result = builder.createTriOp(convOp, destType, operand, one, zero);
3466 } else
3467 result = builder.createUnaryOp(convOp, destType, operand);
3468
John Kessenich32cfd492016-02-02 12:37:46 -07003469 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003470}
3471
3472spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3473{
3474 if (vectorSize == 0)
3475 return constant;
3476
3477 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3478 std::vector<spv::Id> components;
3479 for (int c = 0; c < vectorSize; ++c)
3480 components.push_back(constant);
3481 return builder.makeCompositeConstant(vectorTypeId, components);
3482}
3483
John Kessenich426394d2015-07-23 10:22:48 -06003484// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003485spv::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 -06003486{
3487 spv::Op opCode = spv::OpNop;
3488
3489 switch (op) {
3490 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003491 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003492 opCode = spv::OpAtomicIAdd;
3493 break;
3494 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003495 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003496 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003497 break;
3498 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003499 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003500 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003501 break;
3502 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003503 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003504 opCode = spv::OpAtomicAnd;
3505 break;
3506 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003507 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003508 opCode = spv::OpAtomicOr;
3509 break;
3510 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003511 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003512 opCode = spv::OpAtomicXor;
3513 break;
3514 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003515 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003516 opCode = spv::OpAtomicExchange;
3517 break;
3518 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003519 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003520 opCode = spv::OpAtomicCompareExchange;
3521 break;
3522 case glslang::EOpAtomicCounterIncrement:
3523 opCode = spv::OpAtomicIIncrement;
3524 break;
3525 case glslang::EOpAtomicCounterDecrement:
3526 opCode = spv::OpAtomicIDecrement;
3527 break;
3528 case glslang::EOpAtomicCounter:
3529 opCode = spv::OpAtomicLoad;
3530 break;
3531 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003532 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003533 break;
3534 }
3535
3536 // Sort out the operands
3537 // - mapping from glslang -> SPV
3538 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003539 // - compare-exchange swaps the value and comparator
3540 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003541 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3542 auto opIt = operands.begin(); // walk the glslang operands
3543 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003544 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3545 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3546 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003547 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3548 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003549 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003550 spvAtomicOperands.push_back(*(opIt + 1));
3551 spvAtomicOperands.push_back(*opIt);
3552 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003553 }
John Kessenich426394d2015-07-23 10:22:48 -06003554
John Kessenich3e60a6f2015-09-14 22:45:16 -06003555 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003556 for (; opIt != operands.end(); ++opIt)
3557 spvAtomicOperands.push_back(*opIt);
3558
3559 return builder.createOp(opCode, typeId, spvAtomicOperands);
3560}
3561
John Kessenich5e4b1242015-08-06 22:53:06 -06003562spv::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 -06003563{
Rex Xu8ff43de2016-04-22 16:51:45 +08003564 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003565 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3566
John Kessenich140f3df2015-06-26 16:58:36 -06003567 spv::Op opCode = spv::OpNop;
3568 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003569 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003570 spv::Id typeId0 = 0;
3571 if (consumedOperands > 0)
3572 typeId0 = builder.getTypeId(operands[0]);
3573 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003574
3575 switch (op) {
3576 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003577 if (isFloat)
3578 libCall = spv::GLSLstd450FMin;
3579 else if (isUnsigned)
3580 libCall = spv::GLSLstd450UMin;
3581 else
3582 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003583 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003584 break;
3585 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003586 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003587 break;
3588 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003589 if (isFloat)
3590 libCall = spv::GLSLstd450FMax;
3591 else if (isUnsigned)
3592 libCall = spv::GLSLstd450UMax;
3593 else
3594 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003595 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003596 break;
3597 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003598 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003599 break;
3600 case glslang::EOpDot:
3601 opCode = spv::OpDot;
3602 break;
3603 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003605 break;
3606
3607 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003608 if (isFloat)
3609 libCall = spv::GLSLstd450FClamp;
3610 else if (isUnsigned)
3611 libCall = spv::GLSLstd450UClamp;
3612 else
3613 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003614 builder.promoteScalar(precision, operands.front(), operands[1]);
3615 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003616 break;
3617 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003618 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3619 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003620 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003621 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003622 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003623 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003624 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003625 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003626 break;
3627 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003628 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003629 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003630 break;
3631 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003632 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003633 builder.promoteScalar(precision, operands[0], operands[2]);
3634 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003635 break;
3636
3637 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003638 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003639 break;
3640 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003641 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003642 break;
3643 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003644 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003645 break;
3646 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003647 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003648 break;
3649 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003650 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003651 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003652 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003653 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003654 libCall = spv::GLSLstd450InterpolateAtSample;
3655 break;
3656 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003657 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003658 libCall = spv::GLSLstd450InterpolateAtOffset;
3659 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003660 case glslang::EOpAddCarry:
3661 opCode = spv::OpIAddCarry;
3662 typeId = builder.makeStructResultType(typeId0, typeId0);
3663 consumedOperands = 2;
3664 break;
3665 case glslang::EOpSubBorrow:
3666 opCode = spv::OpISubBorrow;
3667 typeId = builder.makeStructResultType(typeId0, typeId0);
3668 consumedOperands = 2;
3669 break;
3670 case glslang::EOpUMulExtended:
3671 opCode = spv::OpUMulExtended;
3672 typeId = builder.makeStructResultType(typeId0, typeId0);
3673 consumedOperands = 2;
3674 break;
3675 case glslang::EOpIMulExtended:
3676 opCode = spv::OpSMulExtended;
3677 typeId = builder.makeStructResultType(typeId0, typeId0);
3678 consumedOperands = 2;
3679 break;
3680 case glslang::EOpBitfieldExtract:
3681 if (isUnsigned)
3682 opCode = spv::OpBitFieldUExtract;
3683 else
3684 opCode = spv::OpBitFieldSExtract;
3685 break;
3686 case glslang::EOpBitfieldInsert:
3687 opCode = spv::OpBitFieldInsert;
3688 break;
3689
3690 case glslang::EOpFma:
3691 libCall = spv::GLSLstd450Fma;
3692 break;
3693 case glslang::EOpFrexp:
3694 libCall = spv::GLSLstd450FrexpStruct;
3695 if (builder.getNumComponents(operands[0]) == 1)
3696 frexpIntType = builder.makeIntegerType(32, true);
3697 else
3698 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3699 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3700 consumedOperands = 1;
3701 break;
3702 case glslang::EOpLdexp:
3703 libCall = spv::GLSLstd450Ldexp;
3704 break;
3705
Rex Xu574ab042016-04-14 16:53:07 +08003706 case glslang::EOpReadInvocation:
3707 spv::MissingFunctionality("shader ballot");
3708 libCall = spv::GLSLstd450Bad;
3709 break;
3710
John Kessenich140f3df2015-06-26 16:58:36 -06003711 default:
3712 return 0;
3713 }
3714
3715 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003716 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003717 // Use an extended instruction from the standard library.
3718 // Construct the call arguments, without modifying the original operands vector.
3719 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3720 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003721 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003722 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003723 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003724 case 0:
3725 // should all be handled by visitAggregate and createNoArgOperation
3726 assert(0);
3727 return 0;
3728 case 1:
3729 // should all be handled by createUnaryOperation
3730 assert(0);
3731 return 0;
3732 case 2:
3733 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3734 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003735 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003736 // anything 3 or over doesn't have l-value operands, so all should be consumed
3737 assert(consumedOperands == operands.size());
3738 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003739 break;
3740 }
3741 }
3742
John Kessenich55e7d112015-11-15 21:33:39 -07003743 // Decode the return types that were structures
3744 switch (op) {
3745 case glslang::EOpAddCarry:
3746 case glslang::EOpSubBorrow:
3747 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3748 id = builder.createCompositeExtract(id, typeId0, 0);
3749 break;
3750 case glslang::EOpUMulExtended:
3751 case glslang::EOpIMulExtended:
3752 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3753 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3754 break;
3755 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003756 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003757 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3758 id = builder.createCompositeExtract(id, typeId0, 0);
3759 break;
3760 default:
3761 break;
3762 }
3763
John Kessenich32cfd492016-02-02 12:37:46 -07003764 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003765}
3766
3767// Intrinsics with no arguments, no return value, and no precision.
3768spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3769{
3770 // TODO: get the barrier operands correct
3771
3772 switch (op) {
3773 case glslang::EOpEmitVertex:
3774 builder.createNoResultOp(spv::OpEmitVertex);
3775 return 0;
3776 case glslang::EOpEndPrimitive:
3777 builder.createNoResultOp(spv::OpEndPrimitive);
3778 return 0;
3779 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3781 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003782 return 0;
3783 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003784 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003785 return 0;
3786 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003787 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003788 return 0;
3789 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003790 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003791 return 0;
3792 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003794 return 0;
3795 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003796 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003797 return 0;
3798 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003799 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003800 return 0;
3801 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003802 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003803 return 0;
3804 }
3805}
3806
3807spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3808{
John Kessenich2f273362015-07-18 22:34:27 -06003809 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003810 spv::Id id;
3811 if (symbolValues.end() != iter) {
3812 id = iter->second;
3813 return id;
3814 }
3815
3816 // it was not found, create it
3817 id = createSpvVariable(symbol);
3818 symbolValues[symbol->getId()] = id;
3819
3820 if (! symbol->getType().isStruct()) {
3821 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003822 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003823 if (symbol->getType().getQualifier().hasSpecConstantId())
3824 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003825 if (symbol->getQualifier().hasLocation())
3826 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3827 if (symbol->getQualifier().hasIndex())
3828 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3829 if (symbol->getQualifier().hasComponent())
3830 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3831 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003832 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003833 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003834 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003835 if (symbol->getQualifier().hasXfbBuffer())
3836 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3837 if (symbol->getQualifier().hasXfbOffset())
3838 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3839 }
3840 }
3841
John Kesseniche0b6cad2015-12-24 10:30:13 -07003842 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003843 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003844 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003845 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003846 }
John Kessenich140f3df2015-06-26 16:58:36 -06003847 if (symbol->getQualifier().hasSet())
3848 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003849 else if (IsDescriptorResource(symbol->getType())) {
3850 // default to 0
3851 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3852 }
John Kessenich140f3df2015-06-26 16:58:36 -06003853 if (symbol->getQualifier().hasBinding())
3854 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003855 if (symbol->getQualifier().hasAttachment())
3856 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003857 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003858 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003859 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003860 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003861 if (symbol->getQualifier().hasXfbBuffer())
3862 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3863 }
3864
Rex Xu1da878f2016-02-21 20:59:01 +08003865 if (symbol->getType().isImage()) {
3866 std::vector<spv::Decoration> memory;
3867 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3868 for (unsigned int i = 0; i < memory.size(); ++i)
3869 addDecoration(id, memory[i]);
3870 }
3871
John Kessenich140f3df2015-06-26 16:58:36 -06003872 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003873 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003874 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003875 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003876
John Kessenich140f3df2015-06-26 16:58:36 -06003877 return id;
3878}
3879
John Kessenich55e7d112015-11-15 21:33:39 -07003880// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003881void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3882{
3883 if (dec != spv::BadValue)
3884 builder.addDecoration(id, dec);
3885}
3886
John Kessenich55e7d112015-11-15 21:33:39 -07003887// If 'dec' is valid, add a one-operand decoration to an object
3888void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3889{
3890 if (dec != spv::BadValue)
3891 builder.addDecoration(id, dec, value);
3892}
3893
3894// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003895void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3896{
3897 if (dec != spv::BadValue)
3898 builder.addMemberDecoration(id, (unsigned)member, dec);
3899}
3900
John Kessenich92187592016-02-01 13:45:25 -07003901// If 'dec' is valid, add a one-operand decoration to a struct member
3902void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3903{
3904 if (dec != spv::BadValue)
3905 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3906}
3907
John Kessenich55e7d112015-11-15 21:33:39 -07003908// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003909// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003910//
3911// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3912//
3913// Recursively walk the nodes. The nodes form a tree whose leaves are
3914// regular constants, which themselves are trees that createSpvConstant()
3915// recursively walks. So, this function walks the "top" of the tree:
3916// - emit specialization constant-building instructions for specConstant
3917// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003918spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003919{
John Kessenich7cc0e282016-03-20 00:46:02 -06003920 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003921
qining4f4bb812016-04-03 23:55:17 -04003922 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003923 if (! node.getQualifier().specConstant) {
3924 // hand off to the non-spec-constant path
3925 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3926 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003927 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003928 nextConst, false);
3929 }
3930
3931 // We now know we have a specialization constant to build
3932
qining4f4bb812016-04-03 23:55:17 -04003933 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3934 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3935 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3936 std::vector<spv::Id> dimConstId;
3937 for (int dim = 0; dim < 3; ++dim) {
3938 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3939 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3940 if (specConst)
3941 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3942 }
3943 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3944 }
3945
3946 // An AST node labelled as specialization constant should be a symbol node.
3947 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3948 if (auto* sn = node.getAsSymbolNode()) {
3949 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04003950 // Traverse the constant constructor sub tree like generating normal run-time instructions.
3951 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
3952 // will set the builder into spec constant op instruction generating mode.
3953 sub_tree->traverse(this);
3954 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04003955 } else if (auto* const_union_array = &sn->getConstArray()){
3956 int nextConst = 0;
3957 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003958 }
3959 }
qining4f4bb812016-04-03 23:55:17 -04003960
3961 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3962 // constant sub tree as initializer.
3963 spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
3964 exit(1);
3965 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003966}
3967
John Kessenich140f3df2015-06-26 16:58:36 -06003968// Use 'consts' as the flattened glslang source of scalar constants to recursively
3969// build the aggregate SPIR-V constant.
3970//
3971// If there are not enough elements present in 'consts', 0 will be substituted;
3972// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3973//
qining08408382016-03-21 09:51:37 -04003974spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003975{
3976 // vector of constants for SPIR-V
3977 std::vector<spv::Id> spvConsts;
3978
3979 // Type is used for struct and array constants
3980 spv::Id typeId = convertGlslangToSpvType(glslangType);
3981
3982 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003983 glslang::TType elementType(glslangType, 0);
3984 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003985 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003986 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003987 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003988 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003989 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003990 } else if (glslangType.getStruct()) {
3991 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3992 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003993 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003994 } else if (glslangType.isVector()) {
3995 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3996 bool zero = nextConst >= consts.size();
3997 switch (glslangType.getBasicType()) {
3998 case glslang::EbtInt:
3999 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4000 break;
4001 case glslang::EbtUint:
4002 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4003 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004004 case glslang::EbtInt64:
4005 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4006 break;
4007 case glslang::EbtUint64:
4008 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4009 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004010 case glslang::EbtFloat:
4011 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4012 break;
4013 case glslang::EbtDouble:
4014 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4015 break;
4016 case glslang::EbtBool:
4017 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4018 break;
4019 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004020 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004021 break;
4022 }
4023 ++nextConst;
4024 }
4025 } else {
4026 // we have a non-aggregate (scalar) constant
4027 bool zero = nextConst >= consts.size();
4028 spv::Id scalar = 0;
4029 switch (glslangType.getBasicType()) {
4030 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004031 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004032 break;
4033 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004034 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004035 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004036 case glslang::EbtInt64:
4037 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4038 break;
4039 case glslang::EbtUint64:
4040 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4041 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004042 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004043 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004044 break;
4045 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004046 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004047 break;
4048 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004049 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004052 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004053 break;
4054 }
4055 ++nextConst;
4056 return scalar;
4057 }
4058
4059 return builder.makeCompositeConstant(typeId, spvConsts);
4060}
4061
John Kessenich7c1aa102015-10-15 13:29:11 -06004062// Return true if the node is a constant or symbol whose reading has no
4063// non-trivial observable cost or effect.
4064bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4065{
4066 // don't know what this is
4067 if (node == nullptr)
4068 return false;
4069
4070 // a constant is safe
4071 if (node->getAsConstantUnion() != nullptr)
4072 return true;
4073
4074 // not a symbol means non-trivial
4075 if (node->getAsSymbolNode() == nullptr)
4076 return false;
4077
4078 // a symbol, depends on what's being read
4079 switch (node->getType().getQualifier().storage) {
4080 case glslang::EvqTemporary:
4081 case glslang::EvqGlobal:
4082 case glslang::EvqIn:
4083 case glslang::EvqInOut:
4084 case glslang::EvqConst:
4085 case glslang::EvqConstReadOnly:
4086 case glslang::EvqUniform:
4087 return true;
4088 default:
4089 return false;
4090 }
4091}
4092
4093// A node is trivial if it is a single operation with no side effects.
4094// Error on the side of saying non-trivial.
4095// Return true if trivial.
4096bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4097{
4098 if (node == nullptr)
4099 return false;
4100
4101 // symbols and constants are trivial
4102 if (isTrivialLeaf(node))
4103 return true;
4104
4105 // otherwise, it needs to be a simple operation or one or two leaf nodes
4106
4107 // not a simple operation
4108 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4109 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4110 if (binaryNode == nullptr && unaryNode == nullptr)
4111 return false;
4112
4113 // not on leaf nodes
4114 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4115 return false;
4116
4117 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4118 return false;
4119 }
4120
4121 switch (node->getAsOperator()->getOp()) {
4122 case glslang::EOpLogicalNot:
4123 case glslang::EOpConvIntToBool:
4124 case glslang::EOpConvUintToBool:
4125 case glslang::EOpConvFloatToBool:
4126 case glslang::EOpConvDoubleToBool:
4127 case glslang::EOpEqual:
4128 case glslang::EOpNotEqual:
4129 case glslang::EOpLessThan:
4130 case glslang::EOpGreaterThan:
4131 case glslang::EOpLessThanEqual:
4132 case glslang::EOpGreaterThanEqual:
4133 case glslang::EOpIndexDirect:
4134 case glslang::EOpIndexDirectStruct:
4135 case glslang::EOpLogicalXor:
4136 case glslang::EOpAny:
4137 case glslang::EOpAll:
4138 return true;
4139 default:
4140 return false;
4141 }
4142}
4143
4144// Emit short-circuiting code, where 'right' is never evaluated unless
4145// the left side is true (for &&) or false (for ||).
4146spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4147{
4148 spv::Id boolTypeId = builder.makeBoolType();
4149
4150 // emit left operand
4151 builder.clearAccessChain();
4152 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004153 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004154
4155 // Operands to accumulate OpPhi operands
4156 std::vector<spv::Id> phiOperands;
4157 // accumulate left operand's phi information
4158 phiOperands.push_back(leftId);
4159 phiOperands.push_back(builder.getBuildPoint()->getId());
4160
4161 // Make the two kinds of operation symmetric with a "!"
4162 // || => emit "if (! left) result = right"
4163 // && => emit "if ( left) result = right"
4164 //
4165 // TODO: this runtime "not" for || could be avoided by adding functionality
4166 // to 'builder' to have an "else" without an "then"
4167 if (op == glslang::EOpLogicalOr)
4168 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4169
4170 // make an "if" based on the left value
4171 spv::Builder::If ifBuilder(leftId, builder);
4172
4173 // emit right operand as the "then" part of the "if"
4174 builder.clearAccessChain();
4175 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004176 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004177
4178 // accumulate left operand's phi information
4179 phiOperands.push_back(rightId);
4180 phiOperands.push_back(builder.getBuildPoint()->getId());
4181
4182 // finish the "if"
4183 ifBuilder.makeEndIf();
4184
4185 // phi together the two results
4186 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4187}
4188
John Kessenich140f3df2015-06-26 16:58:36 -06004189}; // end anonymous namespace
4190
4191namespace glslang {
4192
John Kessenich68d78fd2015-07-12 19:28:10 -06004193void GetSpirvVersion(std::string& version)
4194{
John Kessenich9e55f632015-07-15 10:03:39 -06004195 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004196 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004197 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004198 version = buf;
4199}
4200
John Kessenich140f3df2015-06-26 16:58:36 -06004201// Write SPIR-V out to a binary file
4202void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4203{
4204 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004205 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004206 for (int i = 0; i < (int)spirv.size(); ++i) {
4207 unsigned int word = spirv[i];
4208 out.write((const char*)&word, 4);
4209 }
4210 out.close();
4211}
4212
4213//
4214// Set up the glslang traversal
4215//
4216void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4217{
4218 TIntermNode* root = intermediate.getTreeRoot();
4219
4220 if (root == 0)
4221 return;
4222
4223 glslang::GetThreadPoolAllocator().push();
4224
4225 TGlslangToSpvTraverser it(&intermediate);
4226
4227 root->traverse(&it);
4228
4229 it.dumpSpv(spirv);
4230
4231 glslang::GetThreadPoolAllocator().pop();
4232}
4233
4234}; // end namespace glslang