blob: b4d5fb11d571bd679daa54c3a16c27abb9b725ad [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
Lei Zhang09caf122016-05-02 18:11:54 -0400112 std::string getWarningsAndErrors() const { return warningsErrors.str(); }
113
John Kessenich140f3df2015-06-26 16:58:36 -0600114protected:
John Kessenich5e801132016-02-15 11:09:46 -0700115 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -0700116 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -0700117 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600118 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
119 spv::Id getSampledType(const glslang::TSampler&);
120 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700121 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700122 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700123 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800124 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700125 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700126 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
127 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
128 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600129
130 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
131 void makeFunctions(const glslang::TIntermSequence&);
132 void makeGlobalInitializers(const glslang::TIntermSequence&);
133 void visitFunctions(const glslang::TIntermSequence&);
134 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800135 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600136 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
137 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600138 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
139
140 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 -0700141 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800142 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 -0700143 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600144 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
145 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800146 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 -0600147 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id createNoArgOperation(glslang::TOperator op);
149 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
150 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700151 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600152 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700153 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400154 spv::Id createSpvConstant(const glslang::TIntermTyped&);
155 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600156 bool isTrivialLeaf(const glslang::TIntermTyped* node);
157 bool isTrivial(const glslang::TIntermTyped* node);
158 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600159
160 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700161 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600162 int sequenceDepth;
163
Lei Zhang09caf122016-05-02 18:11:54 -0400164 std::ostringstream warningsErrors;
165
John Kessenich140f3df2015-06-26 16:58:36 -0600166 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
167 spv::Builder builder;
168 bool inMain;
169 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700170 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700171 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600172 const glslang::TIntermediate* glslangIntermediate;
173 spv::Id stdBuiltins;
174
John Kessenich2f273362015-07-18 22:34:27 -0600175 std::unordered_map<int, spv::Id> symbolValues;
176 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
177 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700178 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600179 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600180 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600181};
182
183//
184// Helper functions for translating glslang representations to SPIR-V enumerants.
185//
186
187// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700188spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600189{
John Kessenich66e2faf2016-03-12 18:34:36 -0700190 switch (source) {
191 case glslang::EShSourceGlsl:
192 switch (profile) {
193 case ENoProfile:
194 case ECoreProfile:
195 case ECompatibilityProfile:
196 return spv::SourceLanguageGLSL;
197 case EEsProfile:
198 return spv::SourceLanguageESSL;
199 default:
200 return spv::SourceLanguageUnknown;
201 }
202 case glslang::EShSourceHlsl:
203 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600204 default:
205 return spv::SourceLanguageUnknown;
206 }
207}
208
209// Translate glslang language (stage) to SPIR-V execution model.
210spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
211{
212 switch (stage) {
213 case EShLangVertex: return spv::ExecutionModelVertex;
214 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
215 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
216 case EShLangGeometry: return spv::ExecutionModelGeometry;
217 case EShLangFragment: return spv::ExecutionModelFragment;
218 case EShLangCompute: return spv::ExecutionModelGLCompute;
219 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700220 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600221 return spv::ExecutionModelFragment;
222 }
223}
224
225// Translate glslang type to SPIR-V storage class.
226spv::StorageClass TranslateStorageClass(const glslang::TType& type)
227{
228 if (type.getQualifier().isPipeInput())
229 return spv::StorageClassInput;
230 else if (type.getQualifier().isPipeOutput())
231 return spv::StorageClassOutput;
232 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700233 if (type.getQualifier().layoutPushConstant)
234 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 if (type.getBasicType() == glslang::EbtBlock)
236 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800237 else if (type.getBasicType() == glslang::EbtAtomicUint)
238 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 else
240 return spv::StorageClassUniformConstant;
241 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
242 } else {
243 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700244 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
245 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
247 case glslang::EvqTemporary: return spv::StorageClassFunction;
248 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700249 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600250 return spv::StorageClassFunction;
251 }
252 }
253}
254
255// Translate glslang sampler type to SPIR-V dimensionality.
256spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
257{
258 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700259 case glslang::Esd1D: return spv::Dim1D;
260 case glslang::Esd2D: return spv::Dim2D;
261 case glslang::Esd3D: return spv::Dim3D;
262 case glslang::EsdCube: return spv::DimCube;
263 case glslang::EsdRect: return spv::DimRect;
264 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700265 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600268 return spv::Dim2D;
269 }
270}
271
272// Translate glslang type to SPIR-V precision decorations.
273spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
274{
275 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700276 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600277 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 default:
279 return spv::NoPrecision;
280 }
281}
282
283// Translate glslang type to SPIR-V block decorations.
284spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
289 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
298 return (spv::Decoration)spv::BadValue;
299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
327 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
332 return (spv::Decoration)spv::BadValue;
333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600342 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600347 return (spv::Decoration)spv::BadValue;
348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600350 return (spv::Decoration)spv::BadValue;
351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700357// Returns spv::Decoration(spv::BadValue) when no decoration
358// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700359spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700361 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
363 return (spv::Decoration)spv::BadValue;
364 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700365 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700366 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700369 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600370 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700371 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600372 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700373 else if (qualifier.sample) {
374 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600375 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700376 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600377 return (spv::Decoration)spv::BadValue;
378}
379
John Kessenich92187592016-02-01 13:45:25 -0700380// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700381spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600382{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700383 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600384 return spv::DecorationInvariant;
385 else
386 return (spv::Decoration)spv::BadValue;
387}
388
389// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700390spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600391{
392 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700393 case glslang::EbvPointSize:
394 switch (glslangIntermediate->getStage()) {
395 case EShLangGeometry:
396 builder.addCapability(spv::CapabilityGeometryPointSize);
397 break;
398 case EShLangTessControl:
399 case EShLangTessEvaluation:
400 builder.addCapability(spv::CapabilityTessellationPointSize);
401 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100402 default:
403 break;
John Kessenich92187592016-02-01 13:45:25 -0700404 }
405 return spv::BuiltInPointSize;
406
407 case glslang::EbvClipDistance:
408 builder.addCapability(spv::CapabilityClipDistance);
409 return spv::BuiltInClipDistance;
410
411 case glslang::EbvCullDistance:
412 builder.addCapability(spv::CapabilityCullDistance);
413 return spv::BuiltInCullDistance;
414
415 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500416 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700417 return spv::BuiltInViewportIndex;
418
John Kessenich5e801132016-02-15 11:09:46 -0700419 case glslang::EbvSampleId:
420 builder.addCapability(spv::CapabilitySampleRateShading);
421 return spv::BuiltInSampleId;
422
423 case glslang::EbvSamplePosition:
424 builder.addCapability(spv::CapabilitySampleRateShading);
425 return spv::BuiltInSamplePosition;
426
427 case glslang::EbvSampleMask:
428 builder.addCapability(spv::CapabilitySampleRateShading);
429 return spv::BuiltInSampleMask;
430
John Kessenich140f3df2015-06-26 16:58:36 -0600431 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600432 case glslang::EbvVertexId: return spv::BuiltInVertexId;
433 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700434 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
435 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600436 case glslang::EbvBaseVertex:
437 case glslang::EbvBaseInstance:
438 case glslang::EbvDrawId:
439 // TODO: Add SPIR-V builtin ID.
Lei Zhang09caf122016-05-02 18:11:54 -0400440 spv::MissingFunctionality(warningsErrors, "Draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600441 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600442 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
443 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
444 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600445 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
446 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
447 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
448 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
449 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
450 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
451 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600452 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
453 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
454 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
455 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
456 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
457 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
458 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
459 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
460 default: return (spv::BuiltIn)spv::BadValue;
461 }
462}
463
Rex Xufc618912015-09-09 16:42:49 +0800464// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700465spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800466{
467 assert(type.getBasicType() == glslang::EbtSampler);
468
John Kessenich5d0fa972016-02-15 11:57:00 -0700469 // Check for capabilities
470 switch (type.getQualifier().layoutFormat) {
471 case glslang::ElfRg32f:
472 case glslang::ElfRg16f:
473 case glslang::ElfR11fG11fB10f:
474 case glslang::ElfR16f:
475 case glslang::ElfRgba16:
476 case glslang::ElfRgb10A2:
477 case glslang::ElfRg16:
478 case glslang::ElfRg8:
479 case glslang::ElfR16:
480 case glslang::ElfR8:
481 case glslang::ElfRgba16Snorm:
482 case glslang::ElfRg16Snorm:
483 case glslang::ElfRg8Snorm:
484 case glslang::ElfR16Snorm:
485 case glslang::ElfR8Snorm:
486
487 case glslang::ElfRg32i:
488 case glslang::ElfRg16i:
489 case glslang::ElfRg8i:
490 case glslang::ElfR16i:
491 case glslang::ElfR8i:
492
493 case glslang::ElfRgb10a2ui:
494 case glslang::ElfRg32ui:
495 case glslang::ElfRg16ui:
496 case glslang::ElfRg8ui:
497 case glslang::ElfR16ui:
498 case glslang::ElfR8ui:
499 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
500 break;
501
502 default:
503 break;
504 }
505
506 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800507 switch (type.getQualifier().layoutFormat) {
508 case glslang::ElfNone: return spv::ImageFormatUnknown;
509 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
510 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
511 case glslang::ElfR32f: return spv::ImageFormatR32f;
512 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
513 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
514 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
515 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
516 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
517 case glslang::ElfR16f: return spv::ImageFormatR16f;
518 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
519 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
520 case glslang::ElfRg16: return spv::ImageFormatRg16;
521 case glslang::ElfRg8: return spv::ImageFormatRg8;
522 case glslang::ElfR16: return spv::ImageFormatR16;
523 case glslang::ElfR8: return spv::ImageFormatR8;
524 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
525 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
526 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
527 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
528 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
529 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
530 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
531 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
532 case glslang::ElfR32i: return spv::ImageFormatR32i;
533 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
534 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
535 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
536 case glslang::ElfR16i: return spv::ImageFormatR16i;
537 case glslang::ElfR8i: return spv::ImageFormatR8i;
538 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
539 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
540 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
541 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
542 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
543 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
544 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
545 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
546 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
547 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
548 default: return (spv::ImageFormat)spv::BadValue;
549 }
550}
551
John Kessenich6c292d32016-02-15 20:58:50 -0700552// Return whether or not the given type is something that should be tied to a
553// descriptor set.
554bool IsDescriptorResource(const glslang::TType& type)
555{
John Kessenichf7497e22016-03-08 21:36:22 -0700556 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700557 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700558 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700559
560 // non block...
561 // basically samplerXXX/subpass/sampler/texture are all included
562 // if they are the global-scope-class, not the function parameter
563 // (or local, if they ever exist) class.
564 if (type.getBasicType() == glslang::EbtSampler)
565 return type.getQualifier().isUniformOrBuffer();
566
567 // None of the above.
568 return false;
569}
570
John Kesseniche0b6cad2015-12-24 10:30:13 -0700571void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
572{
573 if (child.layoutMatrix == glslang::ElmNone)
574 child.layoutMatrix = parent.layoutMatrix;
575
576 if (parent.invariant)
577 child.invariant = true;
578 if (parent.nopersp)
579 child.nopersp = true;
580 if (parent.flat)
581 child.flat = true;
582 if (parent.centroid)
583 child.centroid = true;
584 if (parent.patch)
585 child.patch = true;
586 if (parent.sample)
587 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800588 if (parent.coherent)
589 child.coherent = true;
590 if (parent.volatil)
591 child.volatil = true;
592 if (parent.restrict)
593 child.restrict = true;
594 if (parent.readonly)
595 child.readonly = true;
596 if (parent.writeonly)
597 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700598}
599
600bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
601{
John Kessenich7b9fa252016-01-21 18:56:57 -0700602 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700603 // - struct members can inherit from a struct declaration
604 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
605 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700606 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700607}
608
John Kessenich140f3df2015-06-26 16:58:36 -0600609//
610// Implement the TGlslangToSpvTraverser class.
611//
612
613TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
614 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
Lei Zhang09caf122016-05-02 18:11:54 -0400615 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, warningsErrors),
John Kessenich140f3df2015-06-26 16:58:36 -0600616 inMain(false), mainTerminated(false), linkageOnly(false),
617 glslangIntermediate(glslangIntermediate)
618{
619 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
620
621 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700622 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600623 stdBuiltins = builder.import("GLSL.std.450");
624 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700625 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
626 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600627
628 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600629 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
630 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600631 builder.addSourceExtension(it->c_str());
632
633 // Add the top-level modes for this shader.
634
John Kessenich92187592016-02-01 13:45:25 -0700635 if (glslangIntermediate->getXfbMode()) {
636 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600637 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700638 }
John Kessenich140f3df2015-06-26 16:58:36 -0600639
640 unsigned int mode;
641 switch (glslangIntermediate->getStage()) {
642 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600643 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600644 break;
645
646 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600647 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600648 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
649 break;
650
651 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600652 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700654 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
655 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
656 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600657 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600658 }
659 if (mode != spv::BadValue)
660 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
661
John Kesseniche6903322015-10-13 16:29:02 -0600662 switch (glslangIntermediate->getVertexSpacing()) {
663 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
664 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
665 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
666 default: mode = spv::BadValue; break;
667 }
668 if (mode != spv::BadValue)
669 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
670
671 switch (glslangIntermediate->getVertexOrder()) {
672 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
673 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
674 default: mode = spv::BadValue; break;
675 }
676 if (mode != spv::BadValue)
677 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
678
679 if (glslangIntermediate->getPointMode())
680 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600681 break;
682
683 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600684 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600685 switch (glslangIntermediate->getInputPrimitive()) {
686 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
687 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
688 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700689 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600690 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
691 default: mode = spv::BadValue; break;
692 }
693 if (mode != spv::BadValue)
694 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600695
John Kessenich140f3df2015-06-26 16:58:36 -0600696 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
697
698 switch (glslangIntermediate->getOutputPrimitive()) {
699 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
700 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
701 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
702 default: mode = spv::BadValue; break;
703 }
704 if (mode != spv::BadValue)
705 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
706 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
707 break;
708
709 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600710 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600711 if (glslangIntermediate->getPixelCenterInteger())
712 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600713
John Kessenich140f3df2015-06-26 16:58:36 -0600714 if (glslangIntermediate->getOriginUpperLeft())
715 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600716 else
717 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600718
719 if (glslangIntermediate->getEarlyFragmentTests())
720 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
721
722 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600723 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
724 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
725 default: mode = spv::BadValue; break;
726 }
727 if (mode != spv::BadValue)
728 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
729
730 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
731 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600732 break;
733
734 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600735 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600736 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
737 glslangIntermediate->getLocalSize(1),
738 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600739 break;
740
741 default:
742 break;
743 }
744
745}
746
John Kessenich7ba63412015-12-20 17:37:07 -0700747// Finish everything and dump
748void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
749{
750 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100751 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
752 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700753
qiningda397332016-03-09 19:54:03 -0500754 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700755 builder.dump(out);
756}
757
John Kessenich140f3df2015-06-26 16:58:36 -0600758TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
759{
760 if (! mainTerminated) {
761 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
762 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600763 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600764 }
765}
766
767//
768// Implement the traversal functions.
769//
770// Return true from interior nodes to have the external traversal
771// continue on to children. Return false if children were
772// already processed.
773//
774
775//
776// Symbols can turn into
777// - uniform/input reads
778// - output writes
779// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
780// - something simple that degenerates into the last bullet
781//
782void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
783{
qining75d1d802016-04-06 14:42:01 -0400784 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
785 if (symbol->getType().getQualifier().isSpecConstant())
786 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
787
John Kessenich140f3df2015-06-26 16:58:36 -0600788 // getSymbolId() will set up all the IO decorations on the first call.
789 // Formal function parameters were mapped during makeFunctions().
790 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700791
792 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
793 if (builder.isPointer(id)) {
794 spv::StorageClass sc = builder.getStorageClass(id);
795 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
796 iOSet.insert(id);
797 }
798
799 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700800 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600801 // Prepare to generate code for the access
802
803 // L-value chains will be computed left to right. We're on the symbol now,
804 // which is the left-most part of the access chain, so now is "clear" time,
805 // followed by setting the base.
806 builder.clearAccessChain();
807
808 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700809 // except for
810 // A) "const in" arguments to a function, which are an intermediate object.
811 // See comments in handleUserFunctionCall().
812 // B) Specialization constants (normal constant don't even come in as a variable),
813 // These are also pure R-values.
814 glslang::TQualifier qualifier = symbol->getQualifier();
815 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
816 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600817 builder.setAccessChainRValue(id);
818 else
819 builder.setAccessChainLValue(id);
820 }
821}
822
823bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
824{
qining40887662016-04-03 22:20:42 -0400825 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
826 if (node->getType().getQualifier().isSpecConstant())
827 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
828
John Kessenich140f3df2015-06-26 16:58:36 -0600829 // First, handle special cases
830 switch (node->getOp()) {
831 case glslang::EOpAssign:
832 case glslang::EOpAddAssign:
833 case glslang::EOpSubAssign:
834 case glslang::EOpMulAssign:
835 case glslang::EOpVectorTimesMatrixAssign:
836 case glslang::EOpVectorTimesScalarAssign:
837 case glslang::EOpMatrixTimesScalarAssign:
838 case glslang::EOpMatrixTimesMatrixAssign:
839 case glslang::EOpDivAssign:
840 case glslang::EOpModAssign:
841 case glslang::EOpAndAssign:
842 case glslang::EOpInclusiveOrAssign:
843 case glslang::EOpExclusiveOrAssign:
844 case glslang::EOpLeftShiftAssign:
845 case glslang::EOpRightShiftAssign:
846 // A bin-op assign "a += b" means the same thing as "a = a + b"
847 // where a is evaluated before b. For a simple assignment, GLSL
848 // says to evaluate the left before the right. So, always, left
849 // node then right node.
850 {
851 // get the left l-value, save it away
852 builder.clearAccessChain();
853 node->getLeft()->traverse(this);
854 spv::Builder::AccessChain lValue = builder.getAccessChain();
855
856 // evaluate the right
857 builder.clearAccessChain();
858 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700859 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600860
861 if (node->getOp() != glslang::EOpAssign) {
862 // the left is also an r-value
863 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700864 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600865
866 // do the operation
867 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
868 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
869 node->getType().getBasicType());
870
871 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700872 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600873 }
874
875 // store the result
876 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800877 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600878
879 // assignments are expressions having an rValue after they are evaluated...
880 builder.clearAccessChain();
881 builder.setAccessChainRValue(rValue);
882 }
883 return false;
884 case glslang::EOpIndexDirect:
885 case glslang::EOpIndexDirectStruct:
886 {
887 // Get the left part of the access chain.
888 node->getLeft()->traverse(this);
889
890 // Add the next element in the chain
891
John Kessenich55e7d112015-11-15 21:33:39 -0700892 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600893 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
894 // This may be, e.g., an anonymous block-member selection, which generally need
895 // index remapping due to hidden members in anonymous blocks.
896 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700897 assert(remapper.size() > 0);
898 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600899 }
900
901 if (! node->getLeft()->getType().isArray() &&
902 node->getLeft()->getType().isVector() &&
903 node->getOp() == glslang::EOpIndexDirect) {
904 // This is essentially a hard-coded vector swizzle of size 1,
905 // so short circuit the access-chain stuff with a swizzle.
906 std::vector<unsigned> swizzle;
907 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600908 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600909 } else {
910 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600911 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600912 }
913 }
914 return false;
915 case glslang::EOpIndexIndirect:
916 {
917 // Structure or array or vector indirection.
918 // Will use native SPIR-V access-chain for struct and array indirection;
919 // matrices are arrays of vectors, so will also work for a matrix.
920 // Will use the access chain's 'component' for variable index into a vector.
921
922 // This adapter is building access chains left to right.
923 // Set up the access chain to the left.
924 node->getLeft()->traverse(this);
925
926 // save it so that computing the right side doesn't trash it
927 spv::Builder::AccessChain partial = builder.getAccessChain();
928
929 // compute the next index in the chain
930 builder.clearAccessChain();
931 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700932 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600933
934 // restore the saved access chain
935 builder.setAccessChain(partial);
936
937 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600938 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600939 else
John Kessenichfa668da2015-09-13 14:46:30 -0600940 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600941 }
942 return false;
943 case glslang::EOpVectorSwizzle:
944 {
945 node->getLeft()->traverse(this);
946 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
947 std::vector<unsigned> swizzle;
948 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
949 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600950 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
952 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600953 case glslang::EOpLogicalOr:
954 case glslang::EOpLogicalAnd:
955 {
956
957 // These may require short circuiting, but can sometimes be done as straight
958 // binary operations. The right operand must be short circuited if it has
959 // side effects, and should probably be if it is complex.
960 if (isTrivial(node->getRight()->getAsTyped()))
961 break; // handle below as a normal binary operation
962 // otherwise, we need to do dynamic short circuiting on the right operand
963 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
964 builder.clearAccessChain();
965 builder.setAccessChainRValue(result);
966 }
967 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600968 default:
969 break;
970 }
971
972 // Assume generic binary op...
973
John Kessenich32cfd492016-02-02 12:37:46 -0700974 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600975 builder.clearAccessChain();
976 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700977 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600978
John Kessenich32cfd492016-02-02 12:37:46 -0700979 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600980 builder.clearAccessChain();
981 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700982 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600983
John Kessenich32cfd492016-02-02 12:37:46 -0700984 // get result
985 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
986 convertGlslangToSpvType(node->getType()), left, right,
987 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600988
John Kessenich50e57562015-12-21 21:21:11 -0700989 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600990 if (! result) {
Lei Zhang09caf122016-05-02 18:11:54 -0400991 spv::MissingFunctionality(warningsErrors, "unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700992 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600993 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600994 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600995 return false;
996 }
John Kessenich140f3df2015-06-26 16:58:36 -0600997}
998
999bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1000{
qining40887662016-04-03 22:20:42 -04001001 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1002 if (node->getType().getQualifier().isSpecConstant())
1003 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1004
John Kessenichfc51d282015-08-19 13:34:18 -06001005 spv::Id result = spv::NoResult;
1006
1007 // try texturing first
1008 result = createImageTextureFunctionCall(node);
1009 if (result != spv::NoResult) {
1010 builder.clearAccessChain();
1011 builder.setAccessChainRValue(result);
1012
1013 return false; // done with this node
1014 }
1015
1016 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001017
1018 if (node->getOp() == glslang::EOpArrayLength) {
1019 // Quite special; won't want to evaluate the operand.
1020
1021 // Normal .length() would have been constant folded by the front-end.
1022 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001023 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001024 assert(node->getOperand()->getType().isRuntimeSizedArray());
1025 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1026 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001027 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1028 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001029
1030 builder.clearAccessChain();
1031 builder.setAccessChainRValue(length);
1032
1033 return false;
1034 }
1035
John Kessenichfc51d282015-08-19 13:34:18 -06001036 // Start by evaluating the operand
1037
John Kessenich140f3df2015-06-26 16:58:36 -06001038 builder.clearAccessChain();
1039 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001040
Rex Xufc618912015-09-09 16:42:49 +08001041 spv::Id operand = spv::NoResult;
1042
1043 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1044 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001045 node->getOp() == glslang::EOpAtomicCounter ||
1046 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001047 operand = builder.accessChainGetLValue(); // Special case l-value operands
1048 else
John Kessenich32cfd492016-02-02 12:37:46 -07001049 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001050
1051 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1052
1053 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001054 if (! result)
1055 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001056
1057 // if not, then possibly an operation
1058 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001059 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001060
1061 if (result) {
1062 builder.clearAccessChain();
1063 builder.setAccessChainRValue(result);
1064
1065 return false; // done with this node
1066 }
1067
1068 // it must be a special case, check...
1069 switch (node->getOp()) {
1070 case glslang::EOpPostIncrement:
1071 case glslang::EOpPostDecrement:
1072 case glslang::EOpPreIncrement:
1073 case glslang::EOpPreDecrement:
1074 {
1075 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001076 spv::Id one = 0;
1077 if (node->getBasicType() == glslang::EbtFloat)
1078 one = builder.makeFloatConstant(1.0F);
1079 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1080 one = builder.makeInt64Constant(1);
1081 else
1082 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001083 glslang::TOperator op;
1084 if (node->getOp() == glslang::EOpPreIncrement ||
1085 node->getOp() == glslang::EOpPostIncrement)
1086 op = glslang::EOpAdd;
1087 else
1088 op = glslang::EOpSub;
1089
1090 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001091 convertGlslangToSpvType(node->getType()), operand, one,
1092 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001093 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001094
1095 // The result of operation is always stored, but conditionally the
1096 // consumed result. The consumed result is always an r-value.
1097 builder.accessChainStore(result);
1098 builder.clearAccessChain();
1099 if (node->getOp() == glslang::EOpPreIncrement ||
1100 node->getOp() == glslang::EOpPreDecrement)
1101 builder.setAccessChainRValue(result);
1102 else
1103 builder.setAccessChainRValue(operand);
1104 }
1105
1106 return false;
1107
1108 case glslang::EOpEmitStreamVertex:
1109 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1110 return false;
1111 case glslang::EOpEndStreamPrimitive:
1112 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1113 return false;
1114
1115 default:
Lei Zhang09caf122016-05-02 18:11:54 -04001116 spv::MissingFunctionality(warningsErrors, "unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001117 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001118 }
John Kessenich140f3df2015-06-26 16:58:36 -06001119}
1120
1121bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1122{
qining27e04a02016-04-14 16:40:20 -04001123 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1124 if (node->getType().getQualifier().isSpecConstant())
1125 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1126
John Kessenichfc51d282015-08-19 13:34:18 -06001127 spv::Id result = spv::NoResult;
1128
1129 // try texturing
1130 result = createImageTextureFunctionCall(node);
1131 if (result != spv::NoResult) {
1132 builder.clearAccessChain();
1133 builder.setAccessChainRValue(result);
1134
1135 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001136 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001137 // "imageStore" is a special case, which has no result
1138 return false;
1139 }
John Kessenichfc51d282015-08-19 13:34:18 -06001140
John Kessenich140f3df2015-06-26 16:58:36 -06001141 glslang::TOperator binOp = glslang::EOpNull;
1142 bool reduceComparison = true;
1143 bool isMatrix = false;
1144 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001145 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001146
1147 assert(node->getOp());
1148
1149 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1150
1151 switch (node->getOp()) {
1152 case glslang::EOpSequence:
1153 {
1154 if (preVisit)
1155 ++sequenceDepth;
1156 else
1157 --sequenceDepth;
1158
1159 if (sequenceDepth == 1) {
1160 // If this is the parent node of all the functions, we want to see them
1161 // early, so all call points have actual SPIR-V functions to reference.
1162 // In all cases, still let the traverser visit the children for us.
1163 makeFunctions(node->getAsAggregate()->getSequence());
1164
1165 // Also, we want all globals initializers to go into the entry of main(), before
1166 // anything else gets there, so visit out of order, doing them all now.
1167 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1168
1169 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1170 // so do them manually.
1171 visitFunctions(node->getAsAggregate()->getSequence());
1172
1173 return false;
1174 }
1175
1176 return true;
1177 }
1178 case glslang::EOpLinkerObjects:
1179 {
1180 if (visit == glslang::EvPreVisit)
1181 linkageOnly = true;
1182 else
1183 linkageOnly = false;
1184
1185 return true;
1186 }
1187 case glslang::EOpComma:
1188 {
1189 // processing from left to right naturally leaves the right-most
1190 // lying around in the access chain
1191 glslang::TIntermSequence& glslangOperands = node->getSequence();
1192 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1193 glslangOperands[i]->traverse(this);
1194
1195 return false;
1196 }
1197 case glslang::EOpFunction:
1198 if (visit == glslang::EvPreVisit) {
1199 if (isShaderEntrypoint(node)) {
1200 inMain = true;
1201 builder.setBuildPoint(shaderEntry->getLastBlock());
1202 } else {
1203 handleFunctionEntry(node);
1204 }
1205 } else {
1206 if (inMain)
1207 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001208 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001209 inMain = false;
1210 }
1211
1212 return true;
1213 case glslang::EOpParameters:
1214 // Parameters will have been consumed by EOpFunction processing, but not
1215 // the body, so we still visited the function node's children, making this
1216 // child redundant.
1217 return false;
1218 case glslang::EOpFunctionCall:
1219 {
1220 if (node->isUserDefined())
1221 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001222 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1223 if (result) {
1224 builder.clearAccessChain();
1225 builder.setAccessChainRValue(result);
1226 } else
Lei Zhang09caf122016-05-02 18:11:54 -04001227 spv::MissingFunctionality(warningsErrors, "missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001228
1229 return false;
1230 }
1231 case glslang::EOpConstructMat2x2:
1232 case glslang::EOpConstructMat2x3:
1233 case glslang::EOpConstructMat2x4:
1234 case glslang::EOpConstructMat3x2:
1235 case glslang::EOpConstructMat3x3:
1236 case glslang::EOpConstructMat3x4:
1237 case glslang::EOpConstructMat4x2:
1238 case glslang::EOpConstructMat4x3:
1239 case glslang::EOpConstructMat4x4:
1240 case glslang::EOpConstructDMat2x2:
1241 case glslang::EOpConstructDMat2x3:
1242 case glslang::EOpConstructDMat2x4:
1243 case glslang::EOpConstructDMat3x2:
1244 case glslang::EOpConstructDMat3x3:
1245 case glslang::EOpConstructDMat3x4:
1246 case glslang::EOpConstructDMat4x2:
1247 case glslang::EOpConstructDMat4x3:
1248 case glslang::EOpConstructDMat4x4:
1249 isMatrix = true;
1250 // fall through
1251 case glslang::EOpConstructFloat:
1252 case glslang::EOpConstructVec2:
1253 case glslang::EOpConstructVec3:
1254 case glslang::EOpConstructVec4:
1255 case glslang::EOpConstructDouble:
1256 case glslang::EOpConstructDVec2:
1257 case glslang::EOpConstructDVec3:
1258 case glslang::EOpConstructDVec4:
1259 case glslang::EOpConstructBool:
1260 case glslang::EOpConstructBVec2:
1261 case glslang::EOpConstructBVec3:
1262 case glslang::EOpConstructBVec4:
1263 case glslang::EOpConstructInt:
1264 case glslang::EOpConstructIVec2:
1265 case glslang::EOpConstructIVec3:
1266 case glslang::EOpConstructIVec4:
1267 case glslang::EOpConstructUint:
1268 case glslang::EOpConstructUVec2:
1269 case glslang::EOpConstructUVec3:
1270 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001271 case glslang::EOpConstructInt64:
1272 case glslang::EOpConstructI64Vec2:
1273 case glslang::EOpConstructI64Vec3:
1274 case glslang::EOpConstructI64Vec4:
1275 case glslang::EOpConstructUint64:
1276 case glslang::EOpConstructU64Vec2:
1277 case glslang::EOpConstructU64Vec3:
1278 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001279 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001280 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001281 {
1282 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001283 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001284 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1285 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001286 if (node->getOp() == glslang::EOpConstructTextureSampler)
1287 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1288 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001289 std::vector<spv::Id> constituents;
1290 for (int c = 0; c < (int)arguments.size(); ++c)
1291 constituents.push_back(arguments[c]);
1292 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001293 } else if (isMatrix)
1294 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1295 else
1296 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001297
1298 builder.clearAccessChain();
1299 builder.setAccessChainRValue(constructed);
1300
1301 return false;
1302 }
1303
1304 // These six are component-wise compares with component-wise results.
1305 // Forward on to createBinaryOperation(), requesting a vector result.
1306 case glslang::EOpLessThan:
1307 case glslang::EOpGreaterThan:
1308 case glslang::EOpLessThanEqual:
1309 case glslang::EOpGreaterThanEqual:
1310 case glslang::EOpVectorEqual:
1311 case glslang::EOpVectorNotEqual:
1312 {
1313 // Map the operation to a binary
1314 binOp = node->getOp();
1315 reduceComparison = false;
1316 switch (node->getOp()) {
1317 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1318 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1319 default: binOp = node->getOp(); break;
1320 }
1321
1322 break;
1323 }
1324 case glslang::EOpMul:
1325 // compontent-wise matrix multiply
1326 binOp = glslang::EOpMul;
1327 break;
1328 case glslang::EOpOuterProduct:
1329 // two vectors multiplied to make a matrix
1330 binOp = glslang::EOpOuterProduct;
1331 break;
1332 case glslang::EOpDot:
1333 {
1334 // for scalar dot product, use multiply
1335 glslang::TIntermSequence& glslangOperands = node->getSequence();
1336 if (! glslangOperands[0]->getAsTyped()->isVector())
1337 binOp = glslang::EOpMul;
1338 break;
1339 }
1340 case glslang::EOpMod:
1341 // when an aggregate, this is the floating-point mod built-in function,
1342 // which can be emitted by the one in createBinaryOperation()
1343 binOp = glslang::EOpMod;
1344 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001345 case glslang::EOpEmitVertex:
1346 case glslang::EOpEndPrimitive:
1347 case glslang::EOpBarrier:
1348 case glslang::EOpMemoryBarrier:
1349 case glslang::EOpMemoryBarrierAtomicCounter:
1350 case glslang::EOpMemoryBarrierBuffer:
1351 case glslang::EOpMemoryBarrierImage:
1352 case glslang::EOpMemoryBarrierShared:
1353 case glslang::EOpGroupMemoryBarrier:
1354 noReturnValue = true;
1355 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1356 break;
1357
John Kessenich426394d2015-07-23 10:22:48 -06001358 case glslang::EOpAtomicAdd:
1359 case glslang::EOpAtomicMin:
1360 case glslang::EOpAtomicMax:
1361 case glslang::EOpAtomicAnd:
1362 case glslang::EOpAtomicOr:
1363 case glslang::EOpAtomicXor:
1364 case glslang::EOpAtomicExchange:
1365 case glslang::EOpAtomicCompSwap:
1366 atomic = true;
1367 break;
1368
John Kessenich140f3df2015-06-26 16:58:36 -06001369 default:
1370 break;
1371 }
1372
1373 //
1374 // See if it maps to a regular operation.
1375 //
John Kessenich140f3df2015-06-26 16:58:36 -06001376 if (binOp != glslang::EOpNull) {
1377 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1378 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1379 assert(left && right);
1380
1381 builder.clearAccessChain();
1382 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001383 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001384
1385 builder.clearAccessChain();
1386 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001387 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001388
1389 result = createBinaryOperation(binOp, precision,
1390 convertGlslangToSpvType(node->getType()), leftId, rightId,
1391 left->getType().getBasicType(), reduceComparison);
1392
1393 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001394 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001395 builder.clearAccessChain();
1396 builder.setAccessChainRValue(result);
1397
1398 return false;
1399 }
1400
John Kessenich426394d2015-07-23 10:22:48 -06001401 //
1402 // Create the list of operands.
1403 //
John Kessenich140f3df2015-06-26 16:58:36 -06001404 glslang::TIntermSequence& glslangOperands = node->getSequence();
1405 std::vector<spv::Id> operands;
1406 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1407 builder.clearAccessChain();
1408 glslangOperands[arg]->traverse(this);
1409
1410 // special case l-value operands; there are just a few
1411 bool lvalue = false;
1412 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001413 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001414 case glslang::EOpModf:
1415 if (arg == 1)
1416 lvalue = true;
1417 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001418 case glslang::EOpInterpolateAtSample:
1419 case glslang::EOpInterpolateAtOffset:
1420 if (arg == 0)
1421 lvalue = true;
1422 break;
Rex Xud4782c12015-09-06 16:30:11 +08001423 case glslang::EOpAtomicAdd:
1424 case glslang::EOpAtomicMin:
1425 case glslang::EOpAtomicMax:
1426 case glslang::EOpAtomicAnd:
1427 case glslang::EOpAtomicOr:
1428 case glslang::EOpAtomicXor:
1429 case glslang::EOpAtomicExchange:
1430 case glslang::EOpAtomicCompSwap:
1431 if (arg == 0)
1432 lvalue = true;
1433 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001434 case glslang::EOpAddCarry:
1435 case glslang::EOpSubBorrow:
1436 if (arg == 2)
1437 lvalue = true;
1438 break;
1439 case glslang::EOpUMulExtended:
1440 case glslang::EOpIMulExtended:
1441 if (arg >= 2)
1442 lvalue = true;
1443 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001444 default:
1445 break;
1446 }
1447 if (lvalue)
1448 operands.push_back(builder.accessChainGetLValue());
1449 else
John Kessenich32cfd492016-02-02 12:37:46 -07001450 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001451 }
John Kessenich426394d2015-07-23 10:22:48 -06001452
1453 if (atomic) {
1454 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001455 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001456 } else {
1457 // Pass through to generic operations.
1458 switch (glslangOperands.size()) {
1459 case 0:
1460 result = createNoArgOperation(node->getOp());
1461 break;
1462 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001463 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001464 break;
1465 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001466 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001467 break;
1468 }
John Kessenich140f3df2015-06-26 16:58:36 -06001469 }
1470
1471 if (noReturnValue)
1472 return false;
1473
1474 if (! result) {
Lei Zhang09caf122016-05-02 18:11:54 -04001475 spv::MissingFunctionality(warningsErrors, "unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001476 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001477 } else {
1478 builder.clearAccessChain();
1479 builder.setAccessChainRValue(result);
1480 return false;
1481 }
1482}
1483
1484bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1485{
1486 // This path handles both if-then-else and ?:
1487 // The if-then-else has a node type of void, while
1488 // ?: has a non-void node type
1489 spv::Id result = 0;
1490 if (node->getBasicType() != glslang::EbtVoid) {
1491 // don't handle this as just on-the-fly temporaries, because there will be two names
1492 // and better to leave SSA to later passes
1493 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1494 }
1495
1496 // emit the condition before doing anything with selection
1497 node->getCondition()->traverse(this);
1498
1499 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001500 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001501
1502 if (node->getTrueBlock()) {
1503 // emit the "then" statement
1504 node->getTrueBlock()->traverse(this);
1505 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001506 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001507 }
1508
1509 if (node->getFalseBlock()) {
1510 ifBuilder.makeBeginElse();
1511 // emit the "else" statement
1512 node->getFalseBlock()->traverse(this);
1513 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001514 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001515 }
1516
1517 ifBuilder.makeEndIf();
1518
1519 if (result) {
1520 // GLSL only has r-values as the result of a :?, but
1521 // if we have an l-value, that can be more efficient if it will
1522 // become the base of a complex r-value expression, because the
1523 // next layer copies r-values into memory to use the access-chain mechanism
1524 builder.clearAccessChain();
1525 builder.setAccessChainLValue(result);
1526 }
1527
1528 return false;
1529}
1530
1531bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1532{
1533 // emit and get the condition before doing anything with switch
1534 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001535 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001536
1537 // browse the children to sort out code segments
1538 int defaultSegment = -1;
1539 std::vector<TIntermNode*> codeSegments;
1540 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1541 std::vector<int> caseValues;
1542 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1543 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1544 TIntermNode* child = *c;
1545 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001546 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001547 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001548 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001549 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1550 } else
1551 codeSegments.push_back(child);
1552 }
1553
1554 // handle the case where the last code segment is missing, due to no code
1555 // statements between the last case and the end of the switch statement
1556 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1557 (int)codeSegments.size() == defaultSegment)
1558 codeSegments.push_back(nullptr);
1559
1560 // make the switch statement
1561 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001562 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001563
1564 // emit all the code in the segments
1565 breakForLoop.push(false);
1566 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1567 builder.nextSwitchSegment(segmentBlocks, s);
1568 if (codeSegments[s])
1569 codeSegments[s]->traverse(this);
1570 else
1571 builder.addSwitchBreak();
1572 }
1573 breakForLoop.pop();
1574
1575 builder.endSwitch(segmentBlocks);
1576
1577 return false;
1578}
1579
1580void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1581{
1582 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001583 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001584
1585 builder.clearAccessChain();
1586 builder.setAccessChainRValue(constant);
1587}
1588
1589bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1590{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001591 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001592 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001593 // Spec requires back edges to target header blocks, and every header block
1594 // must dominate its merge block. Make a header block first to ensure these
1595 // conditions are met. By definition, it will contain OpLoopMerge, followed
1596 // by a block-ending branch. But we don't want to put any other body/test
1597 // instructions in it, since the body/test may have arbitrary instructions,
1598 // including merges of its own.
1599 builder.setBuildPoint(&blocks.head);
1600 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001601 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001602 spv::Block& test = builder.makeNewBlock();
1603 builder.createBranch(&test);
1604
1605 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001606 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001607 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001608 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001609 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1610
1611 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001612 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001613 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001614 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001615 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001616 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001617
1618 builder.setBuildPoint(&blocks.continue_target);
1619 if (node->getTerminal())
1620 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001621 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001622 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001623 builder.createBranch(&blocks.body);
1624
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001625 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001626 builder.setBuildPoint(&blocks.body);
1627 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001628 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001629 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001630 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001631
1632 builder.setBuildPoint(&blocks.continue_target);
1633 if (node->getTerminal())
1634 node->getTerminal()->traverse(this);
1635 if (node->getTest()) {
1636 node->getTest()->traverse(this);
1637 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001638 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001639 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001640 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001641 // TODO: unless there was a break/return/discard instruction
1642 // somewhere in the body, this is an infinite loop, so we should
1643 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001644 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001645 }
John Kessenich140f3df2015-06-26 16:58:36 -06001646 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001647 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001648 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001649 return false;
1650}
1651
1652bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1653{
1654 if (node->getExpression())
1655 node->getExpression()->traverse(this);
1656
1657 switch (node->getFlowOp()) {
1658 case glslang::EOpKill:
1659 builder.makeDiscard();
1660 break;
1661 case glslang::EOpBreak:
1662 if (breakForLoop.top())
1663 builder.createLoopExit();
1664 else
1665 builder.addSwitchBreak();
1666 break;
1667 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001668 builder.createLoopContinue();
1669 break;
1670 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001671 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001672 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001673 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001674 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001675
1676 builder.clearAccessChain();
1677 break;
1678
1679 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001680 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001681 break;
1682 }
1683
1684 return false;
1685}
1686
1687spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1688{
1689 // First, steer off constants, which are not SPIR-V variables, but
1690 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001691 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001692 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001693 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001694 }
1695
1696 // Now, handle actual variables
1697 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1698 spv::Id spvType = convertGlslangToSpvType(node->getType());
1699
1700 const char* name = node->getName().c_str();
1701 if (glslang::IsAnonymous(name))
1702 name = "";
1703
1704 return builder.createVariable(storageClass, spvType, name);
1705}
1706
1707// Return type Id of the sampled type.
1708spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1709{
1710 switch (sampler.type) {
1711 case glslang::EbtFloat: return builder.makeFloatType(32);
1712 case glslang::EbtInt: return builder.makeIntType(32);
1713 case glslang::EbtUint: return builder.makeUintType(32);
1714 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001715 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001716 return builder.makeFloatType(32);
1717 }
1718}
1719
John Kessenich3ac051e2015-12-20 11:29:16 -07001720// Convert from a glslang type to an SPV type, by calling into a
1721// recursive version of this function. This establishes the inherited
1722// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001723spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1724{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001725 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001726}
1727
1728// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001729// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001730spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001731{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001732 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001733
1734 switch (type.getBasicType()) {
1735 case glslang::EbtVoid:
1736 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001737 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001738 break;
1739 case glslang::EbtFloat:
1740 spvType = builder.makeFloatType(32);
1741 break;
1742 case glslang::EbtDouble:
1743 spvType = builder.makeFloatType(64);
1744 break;
1745 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001746 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1747 // a 32-bit int where non-0 means true.
1748 if (explicitLayout != glslang::ElpNone)
1749 spvType = builder.makeUintType(32);
1750 else
1751 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001752 break;
1753 case glslang::EbtInt:
1754 spvType = builder.makeIntType(32);
1755 break;
1756 case glslang::EbtUint:
1757 spvType = builder.makeUintType(32);
1758 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001759 case glslang::EbtInt64:
1760 builder.addCapability(spv::CapabilityInt64);
1761 spvType = builder.makeIntType(64);
1762 break;
1763 case glslang::EbtUint64:
1764 builder.addCapability(spv::CapabilityInt64);
1765 spvType = builder.makeUintType(64);
1766 break;
John Kessenich426394d2015-07-23 10:22:48 -06001767 case glslang::EbtAtomicUint:
Lei Zhang09caf122016-05-02 18:11:54 -04001768 spv::TbdFunctionality(warningsErrors, "Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
John Kessenich426394d2015-07-23 10:22:48 -06001769 spvType = builder.makeUintType(32);
1770 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001771 case glslang::EbtSampler:
1772 {
1773 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001774 if (sampler.sampler) {
1775 // pure sampler
1776 spvType = builder.makeSamplerType();
1777 } else {
1778 // an image is present, make its type
1779 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1780 sampler.image ? 2 : 1, TranslateImageFormat(type));
1781 if (sampler.combined) {
1782 // already has both image and sampler, make the combined type
1783 spvType = builder.makeSampledImageType(spvType);
1784 }
John Kessenich55e7d112015-11-15 21:33:39 -07001785 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001786 }
John Kessenich140f3df2015-06-26 16:58:36 -06001787 break;
1788 case glslang::EbtStruct:
1789 case glslang::EbtBlock:
1790 {
1791 // If we've seen this struct type, return it
1792 const glslang::TTypeList* glslangStruct = type.getStruct();
1793 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001794
1795 // Try to share structs for different layouts, but not yet for other
1796 // kinds of qualification (primarily not yet including interpolant qualification).
1797 if (! HasNonLayoutQualifiers(qualifier))
1798 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1799 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001800 break;
1801
1802 // else, we haven't seen it...
1803
1804 // Create a vector of struct types for SPIR-V to consume
1805 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1806 if (type.getBasicType() == glslang::EbtBlock)
1807 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001808 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001809 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1810 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1811 if (glslangType.hiddenMember()) {
1812 ++memberDelta;
1813 if (type.getBasicType() == glslang::EbtBlock)
1814 memberRemapper[glslangStruct][i] = -1;
1815 } else {
1816 if (type.getBasicType() == glslang::EbtBlock)
1817 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001818 // modify just this child's view of the qualifier
1819 glslang::TQualifier subQualifier = glslangType.getQualifier();
1820 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001821
1822 // manually inherit location; it's more complex
1823 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1824 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1825 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001826 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001827
1828 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001829 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001830 }
1831 }
1832
1833 // Make the SPIR-V type
1834 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001835 if (! HasNonLayoutQualifiers(qualifier))
1836 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001837
1838 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001839 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001840 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001841 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1842 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1843 int member = i;
1844 if (type.getBasicType() == glslang::EbtBlock)
1845 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001846
John Kesseniche0b6cad2015-12-24 10:30:13 -07001847 // modify just this child's view of the qualifier
1848 glslang::TQualifier subQualifier = glslangType.getQualifier();
1849 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001850
John Kessenich140f3df2015-06-26 16:58:36 -06001851 // using -1 above to indicate a hidden member
1852 if (member >= 0) {
1853 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001854 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001855 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001856 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1857 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001858
Rex Xu1da878f2016-02-21 20:59:01 +08001859 if (qualifier.storage == glslang::EvqBuffer) {
1860 std::vector<spv::Decoration> memory;
1861 TranslateMemoryDecoration(subQualifier, memory);
1862 for (unsigned int i = 0; i < memory.size(); ++i)
1863 addMemberDecoration(spvType, member, memory[i]);
1864 }
1865
John Kessenich09677482016-02-19 12:21:50 -07001866 // compute location decoration; tricky based on whether inheritance is at play
1867 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1868 // probably move to the linker stage of the front end proper, and just have the
1869 // answer sitting already distributed throughout the individual member locations.
1870 int location = -1; // will only decorate if present or inherited
1871 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1872 location = subQualifier.layoutLocation;
1873 else if (qualifier.hasLocation()) // inheritance
1874 location = qualifier.layoutLocation + locationOffset;
1875 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001876 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001877 if (location >= 0)
1878 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1879
1880 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001881 if (glslangType.getQualifier().hasComponent())
1882 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1883 if (glslangType.getQualifier().hasXfbOffset())
1884 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001885 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001886 // figure out what to do with offset, which is accumulating
1887 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001888 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001889 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001890 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001891 offset = nextOffset;
1892 }
John Kessenich140f3df2015-06-26 16:58:36 -06001893
John Kessenichf85e8062015-12-19 13:57:10 -07001894 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001895 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001896
John Kessenich140f3df2015-06-26 16:58:36 -06001897 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001898 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1899 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001900 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001901 }
1902 }
1903
1904 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001905 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001906 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001907 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001908 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001909 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001910 }
John Kessenich140f3df2015-06-26 16:58:36 -06001911 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001912 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001913 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001914 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001915 if (type.getQualifier().hasXfbBuffer())
1916 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1917 }
1918 }
1919 break;
1920 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001921 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001922 break;
1923 }
1924
1925 if (type.isMatrix())
1926 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1927 else {
1928 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1929 if (type.getVectorSize() > 1)
1930 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1931 }
1932
1933 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001934 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1935
John Kessenichc9a80832015-09-12 12:17:44 -06001936 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001937 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001938 // We need to decorate array strides for types needing explicit layout, except blocks.
1939 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001940 // Use a dummy glslang type for querying internal strides of
1941 // arrays of arrays, but using just a one-dimensional array.
1942 glslang::TType simpleArrayType(type, 0); // deference type of the array
1943 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1944 simpleArrayType.getArraySizes().dereference();
1945
1946 // Will compute the higher-order strides here, rather than making a whole
1947 // pile of types and doing repetitive recursion on their contents.
1948 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1949 }
John Kessenichf8842e52016-01-04 19:22:56 -07001950
1951 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001952 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001953 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001954 if (stride > 0)
1955 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001956 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001957 }
1958 } else {
1959 // single-dimensional array, and don't yet have stride
1960
John Kessenichf8842e52016-01-04 19:22:56 -07001961 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001962 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1963 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001964 }
John Kessenich31ed4832015-09-09 17:51:38 -06001965
John Kessenichc9a80832015-09-12 12:17:44 -06001966 // Do the outer dimension, which might not be known for a runtime-sized array
1967 if (type.isRuntimeSizedArray()) {
1968 spvType = builder.makeRuntimeArray(spvType);
1969 } else {
1970 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001971 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001972 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001973 if (stride > 0)
1974 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001975 }
1976
1977 return spvType;
1978}
1979
John Kessenich6c292d32016-02-15 20:58:50 -07001980// Turn the expression forming the array size into an id.
1981// This is not quite trivial, because of specialization constants.
1982// Sometimes, a raw constant is turned into an Id, and sometimes
1983// a specialization constant expression is.
1984spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1985{
1986 // First, see if this is sized with a node, meaning a specialization constant:
1987 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1988 if (specNode != nullptr) {
1989 builder.clearAccessChain();
1990 specNode->traverse(this);
1991 return accessChainLoad(specNode->getAsTyped()->getType());
1992 }
1993
1994 // Otherwise, need a compile-time (front end) size, get it:
1995 int size = arraySizes.getDimSize(dim);
1996 assert(size > 0);
1997 return builder.makeUintConstant(size);
1998}
1999
John Kessenich103bef92016-02-08 21:38:15 -07002000// Wrap the builder's accessChainLoad to:
2001// - localize handling of RelaxedPrecision
2002// - use the SPIR-V inferred type instead of another conversion of the glslang type
2003// (avoids unnecessary work and possible type punning for structures)
2004// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002005spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2006{
John Kessenich103bef92016-02-08 21:38:15 -07002007 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2008 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2009
2010 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002011 if (type.getBasicType() == glslang::EbtBool) {
2012 if (builder.isScalarType(nominalTypeId)) {
2013 // Conversion for bool
2014 spv::Id boolType = builder.makeBoolType();
2015 if (nominalTypeId != boolType)
2016 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2017 } else if (builder.isVectorType(nominalTypeId)) {
2018 // Conversion for bvec
2019 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2020 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2021 if (nominalTypeId != bvecType)
2022 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2023 }
2024 }
John Kessenich103bef92016-02-08 21:38:15 -07002025
2026 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002027}
2028
Rex Xu27253232016-02-23 17:51:09 +08002029// Wrap the builder's accessChainStore to:
2030// - do conversion of concrete to abstract type
2031void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2032{
2033 // Need to convert to abstract types when necessary
2034 if (type.getBasicType() == glslang::EbtBool) {
2035 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2036
2037 if (builder.isScalarType(nominalTypeId)) {
2038 // Conversion for bool
2039 spv::Id boolType = builder.makeBoolType();
2040 if (nominalTypeId != boolType) {
2041 spv::Id zero = builder.makeUintConstant(0);
2042 spv::Id one = builder.makeUintConstant(1);
2043 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2044 }
2045 } else if (builder.isVectorType(nominalTypeId)) {
2046 // Conversion for bvec
2047 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2048 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2049 if (nominalTypeId != bvecType) {
2050 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2051 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2052 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2053 }
2054 }
2055 }
2056
2057 builder.accessChainStore(rvalue);
2058}
2059
John Kessenichf85e8062015-12-19 13:57:10 -07002060// Decide whether or not this type should be
2061// decorated with offsets and strides, and if so
2062// whether std140 or std430 rules should be applied.
2063glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002064{
John Kessenichf85e8062015-12-19 13:57:10 -07002065 // has to be a block
2066 if (type.getBasicType() != glslang::EbtBlock)
2067 return glslang::ElpNone;
2068
2069 // has to be a uniform or buffer block
2070 if (type.getQualifier().storage != glslang::EvqUniform &&
2071 type.getQualifier().storage != glslang::EvqBuffer)
2072 return glslang::ElpNone;
2073
2074 // return the layout to use
2075 switch (type.getQualifier().layoutPacking) {
2076 case glslang::ElpStd140:
2077 case glslang::ElpStd430:
2078 return type.getQualifier().layoutPacking;
2079 default:
2080 return glslang::ElpNone;
2081 }
John Kessenich31ed4832015-09-09 17:51:38 -06002082}
2083
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002084// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002085int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002086{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002087 int size;
John Kessenich49987892015-12-29 17:11:44 -07002088 int stride;
2089 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002090
2091 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002092}
2093
John Kessenich49987892015-12-29 17:11:44 -07002094// 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 -07002095// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002096int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002097{
John Kessenich49987892015-12-29 17:11:44 -07002098 glslang::TType elementType;
2099 elementType.shallowCopy(matrixType);
2100 elementType.clearArraySizes();
2101
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002102 int size;
John Kessenich49987892015-12-29 17:11:44 -07002103 int stride;
2104 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2105
2106 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002107}
2108
John Kessenich5e4b1242015-08-06 22:53:06 -06002109// Given a member type of a struct, realign the current offset for it, and compute
2110// the next (not yet aligned) offset for the next member, which will get aligned
2111// on the next call.
2112// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2113// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2114// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002115void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002116 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002117{
2118 // this will get a positive value when deemed necessary
2119 nextOffset = -1;
2120
John Kessenich5e4b1242015-08-06 22:53:06 -06002121 // override anything in currentOffset with user-set offset
2122 if (memberType.getQualifier().hasOffset())
2123 currentOffset = memberType.getQualifier().layoutOffset;
2124
2125 // It could be that current linker usage in glslang updated all the layoutOffset,
2126 // in which case the following code does not matter. But, that's not quite right
2127 // once cross-compilation unit GLSL validation is done, as the original user
2128 // settings are needed in layoutOffset, and then the following will come into play.
2129
John Kessenichf85e8062015-12-19 13:57:10 -07002130 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002131 if (! memberType.getQualifier().hasOffset())
2132 currentOffset = -1;
2133
2134 return;
2135 }
2136
John Kessenichf85e8062015-12-19 13:57:10 -07002137 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002138 if (currentOffset < 0)
2139 currentOffset = 0;
2140
2141 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2142 // but possibly not yet correctly aligned.
2143
2144 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002145 int dummyStride;
2146 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002147 glslang::RoundToPow2(currentOffset, memberAlignment);
2148 nextOffset = currentOffset + memberSize;
2149}
2150
John Kessenich140f3df2015-06-26 16:58:36 -06002151bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2152{
John Kessenich4d65ee32016-03-12 18:17:47 -07002153 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002154 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002155 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002156}
2157
2158// Make all the functions, skeletally, without actually visiting their bodies.
2159void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2160{
2161 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2162 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2163 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2164 continue;
2165
2166 // We're on a user function. Set up the basic interface for the function now,
2167 // so that it's available to call.
2168 // Translating the body will happen later.
2169 //
2170 // Typically (except for a "const in" parameter), an address will be passed to the
2171 // function. What it is an address of varies:
2172 //
2173 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2174 // so that write needs to be to a copy, hence the address of a copy works.
2175 //
2176 // - "const in" parameters can just be the r-value, as no writes need occur.
2177 //
2178 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2179 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2180
2181 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002182 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002183 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2184
2185 for (int p = 0; p < (int)parameters.size(); ++p) {
2186 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2187 spv::Id typeId = convertGlslangToSpvType(paramType);
2188 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2189 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2190 else
2191 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002192 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002193 paramTypes.push_back(typeId);
2194 }
2195
2196 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002197 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2198 convertGlslangToSpvType(glslFunction->getType()),
2199 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002200
2201 // Track function to emit/call later
2202 functionMap[glslFunction->getName().c_str()] = function;
2203
2204 // Set the parameter id's
2205 for (int p = 0; p < (int)parameters.size(); ++p) {
2206 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2207 // give a name too
2208 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2209 }
2210 }
2211}
2212
2213// Process all the initializers, while skipping the functions and link objects
2214void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2215{
2216 builder.setBuildPoint(shaderEntry->getLastBlock());
2217 for (int i = 0; i < (int)initializers.size(); ++i) {
2218 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2219 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2220
2221 // We're on a top-level node that's not a function. Treat as an initializer, whose
2222 // code goes into the beginning of main.
2223 initializer->traverse(this);
2224 }
2225 }
2226}
2227
2228// Process all the functions, while skipping initializers.
2229void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2230{
2231 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2232 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2233 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2234 node->traverse(this);
2235 }
2236}
2237
2238void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2239{
2240 // SPIR-V functions should already be in the functionMap from the prepass
2241 // that called makeFunctions().
2242 spv::Function* function = functionMap[node->getName().c_str()];
2243 spv::Block* functionBlock = function->getEntryBlock();
2244 builder.setBuildPoint(functionBlock);
2245}
2246
Rex Xu04db3f52015-09-16 11:44:02 +08002247void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002248{
Rex Xufc618912015-09-09 16:42:49 +08002249 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002250
2251 glslang::TSampler sampler = {};
2252 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002253 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002254 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2255 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2256 }
2257
John Kessenich140f3df2015-06-26 16:58:36 -06002258 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2259 builder.clearAccessChain();
2260 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002261
2262 // Special case l-value operands
2263 bool lvalue = false;
2264 switch (node.getOp()) {
2265 case glslang::EOpImageAtomicAdd:
2266 case glslang::EOpImageAtomicMin:
2267 case glslang::EOpImageAtomicMax:
2268 case glslang::EOpImageAtomicAnd:
2269 case glslang::EOpImageAtomicOr:
2270 case glslang::EOpImageAtomicXor:
2271 case glslang::EOpImageAtomicExchange:
2272 case glslang::EOpImageAtomicCompSwap:
2273 if (i == 0)
2274 lvalue = true;
2275 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002276 case glslang::EOpSparseImageLoad:
2277 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2278 lvalue = true;
2279 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002280 case glslang::EOpSparseTexture:
2281 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2282 lvalue = true;
2283 break;
2284 case glslang::EOpSparseTextureClamp:
2285 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2286 lvalue = true;
2287 break;
2288 case glslang::EOpSparseTextureLod:
2289 case glslang::EOpSparseTextureOffset:
2290 if (i == 3)
2291 lvalue = true;
2292 break;
2293 case glslang::EOpSparseTextureFetch:
2294 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2295 lvalue = true;
2296 break;
2297 case glslang::EOpSparseTextureFetchOffset:
2298 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2299 lvalue = true;
2300 break;
2301 case glslang::EOpSparseTextureLodOffset:
2302 case glslang::EOpSparseTextureGrad:
2303 case glslang::EOpSparseTextureOffsetClamp:
2304 if (i == 4)
2305 lvalue = true;
2306 break;
2307 case glslang::EOpSparseTextureGradOffset:
2308 case glslang::EOpSparseTextureGradClamp:
2309 if (i == 5)
2310 lvalue = true;
2311 break;
2312 case glslang::EOpSparseTextureGradOffsetClamp:
2313 if (i == 6)
2314 lvalue = true;
2315 break;
2316 case glslang::EOpSparseTextureGather:
2317 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2318 lvalue = true;
2319 break;
2320 case glslang::EOpSparseTextureGatherOffset:
2321 case glslang::EOpSparseTextureGatherOffsets:
2322 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2323 lvalue = true;
2324 break;
Rex Xufc618912015-09-09 16:42:49 +08002325 default:
2326 break;
2327 }
2328
Rex Xu6b86d492015-09-16 17:48:22 +08002329 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002330 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002331 else
John Kessenich32cfd492016-02-02 12:37:46 -07002332 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002333 }
2334}
2335
John Kessenichfc51d282015-08-19 13:34:18 -06002336void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002337{
John Kessenichfc51d282015-08-19 13:34:18 -06002338 builder.clearAccessChain();
2339 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002340 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002341}
John Kessenich140f3df2015-06-26 16:58:36 -06002342
John Kessenichfc51d282015-08-19 13:34:18 -06002343spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2344{
Rex Xufc618912015-09-09 16:42:49 +08002345 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002346 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002347 }
2348
John Kessenichfc51d282015-08-19 13:34:18 -06002349 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002350 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2351 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2352 std::vector<spv::Id> arguments;
2353 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002354 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002355 else
2356 translateArguments(*node->getAsUnaryNode(), arguments);
2357 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2358
2359 spv::Builder::TextureParameters params = { };
2360 params.sampler = arguments[0];
2361
Rex Xu04db3f52015-09-16 11:44:02 +08002362 glslang::TCrackedTextureOp cracked;
2363 node->crackTexture(sampler, cracked);
2364
John Kessenichfc51d282015-08-19 13:34:18 -06002365 // Check for queries
2366 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002367 // a sampled image needs to have the image extracted first
2368 if (builder.isSampledImage(params.sampler))
2369 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002370 switch (node->getOp()) {
2371 case glslang::EOpImageQuerySize:
2372 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002373 if (arguments.size() > 1) {
2374 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002375 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002376 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002377 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002378 case glslang::EOpImageQuerySamples:
2379 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002380 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002381 case glslang::EOpTextureQueryLod:
2382 params.coords = arguments[1];
2383 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2384 case glslang::EOpTextureQueryLevels:
2385 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002386 case glslang::EOpSparseTexelsResident:
2387 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002388 default:
2389 assert(0);
2390 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002391 }
John Kessenich140f3df2015-06-26 16:58:36 -06002392 }
2393
Rex Xufc618912015-09-09 16:42:49 +08002394 // Check for image functions other than queries
2395 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002396 std::vector<spv::Id> operands;
2397 auto opIt = arguments.begin();
2398 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002399
2400 // Handle subpass operations
2401 // TODO: GLSL should change to have the "MS" only on the type rather than the
2402 // built-in function.
2403 if (cracked.subpass) {
2404 // add on the (0,0) coordinate
2405 spv::Id zero = builder.makeIntConstant(0);
2406 std::vector<spv::Id> comps;
2407 comps.push_back(zero);
2408 comps.push_back(zero);
2409 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2410 if (sampler.ms) {
2411 operands.push_back(spv::ImageOperandsSampleMask);
2412 operands.push_back(*(opIt++));
2413 }
2414 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2415 }
2416
John Kessenich56bab042015-09-16 10:54:31 -06002417 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002418 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002419 if (sampler.ms) {
2420 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002421 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002422 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002423 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2424 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002425 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002426 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002427 if (sampler.ms) {
2428 operands.push_back(*(opIt + 1));
2429 operands.push_back(spv::ImageOperandsSampleMask);
2430 operands.push_back(*opIt);
2431 } else
2432 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002433 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002434 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2435 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002436 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002437 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2438 builder.addCapability(spv::CapabilitySparseResidency);
2439 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2440 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2441
2442 if (sampler.ms) {
2443 operands.push_back(spv::ImageOperandsSampleMask);
2444 operands.push_back(*opIt++);
2445 }
2446
2447 // Create the return type that was a special structure
2448 spv::Id texelOut = *opIt;
2449 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2450 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2451 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2452
2453 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2454
2455 // Decode the return type
2456 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2457 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002458 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002459 // Process image atomic operations
2460
2461 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2462 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002463 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002464
Rex Xufc618912015-09-09 16:42:49 +08002465 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002466 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002467
2468 std::vector<spv::Id> operands;
2469 operands.push_back(pointer);
2470 for (; opIt != arguments.end(); ++opIt)
2471 operands.push_back(*opIt);
2472
Rex Xu04db3f52015-09-16 11:44:02 +08002473 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002474 }
2475 }
2476
2477 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002478 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002479 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2480
John Kessenichfc51d282015-08-19 13:34:18 -06002481 // check for bias argument
2482 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002483 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002484 int nonBiasArgCount = 2;
2485 if (cracked.offset)
2486 ++nonBiasArgCount;
2487 if (cracked.grad)
2488 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002489 if (cracked.lodClamp)
2490 ++nonBiasArgCount;
2491 if (sparse)
2492 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002493
2494 if ((int)arguments.size() > nonBiasArgCount)
2495 bias = true;
2496 }
2497
John Kessenichfc51d282015-08-19 13:34:18 -06002498 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002499
John Kessenichfc51d282015-08-19 13:34:18 -06002500 params.coords = arguments[1];
2501 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002502 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002503
2504 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002505 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002506 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002507 ++extraArgs;
2508 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002509 params.Dref = arguments[2];
2510 ++extraArgs;
2511 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002512 std::vector<spv::Id> indexes;
2513 int comp;
2514 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002515 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002516 else
2517 comp = builder.getNumComponents(params.coords) - 1;
2518 indexes.push_back(comp);
2519 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2520 }
2521 if (cracked.lod) {
2522 params.lod = arguments[2];
2523 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002524 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2525 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2526 noImplicitLod = true;
2527 }
2528 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002529 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002530 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002531 }
2532 if (cracked.grad) {
2533 params.gradX = arguments[2 + extraArgs];
2534 params.gradY = arguments[3 + extraArgs];
2535 extraArgs += 2;
2536 }
John Kessenich55e7d112015-11-15 21:33:39 -07002537 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002538 params.offset = arguments[2 + extraArgs];
2539 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002540 } else if (cracked.offsets) {
2541 params.offsets = arguments[2 + extraArgs];
2542 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002543 }
Rex Xu48edadf2015-12-31 16:11:41 +08002544 if (cracked.lodClamp) {
2545 params.lodClamp = arguments[2 + extraArgs];
2546 ++extraArgs;
2547 }
2548 if (sparse) {
2549 params.texelOut = arguments[2 + extraArgs];
2550 ++extraArgs;
2551 }
John Kessenichfc51d282015-08-19 13:34:18 -06002552 if (bias) {
2553 params.bias = arguments[2 + extraArgs];
2554 ++extraArgs;
2555 }
John Kessenich55e7d112015-11-15 21:33:39 -07002556 if (cracked.gather && ! sampler.shadow) {
2557 // default component is 0, if missing, otherwise an argument
2558 if (2 + extraArgs < (int)arguments.size()) {
2559 params.comp = arguments[2 + extraArgs];
2560 ++extraArgs;
2561 } else {
2562 params.comp = builder.makeIntConstant(0);
2563 }
2564 }
John Kessenichfc51d282015-08-19 13:34:18 -06002565
John Kessenich019f08f2016-02-15 15:40:42 -07002566 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002567}
2568
2569spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2570{
2571 // Grab the function's pointer from the previously created function
2572 spv::Function* function = functionMap[node->getName().c_str()];
2573 if (! function)
2574 return 0;
2575
2576 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2577 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2578
2579 // See comments in makeFunctions() for details about the semantics for parameter passing.
2580 //
2581 // These imply we need a four step process:
2582 // 1. Evaluate the arguments
2583 // 2. Allocate and make copies of in, out, and inout arguments
2584 // 3. Make the call
2585 // 4. Copy back the results
2586
2587 // 1. Evaluate the arguments
2588 std::vector<spv::Builder::AccessChain> lValues;
2589 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002590 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002591 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2592 // build l-value
2593 builder.clearAccessChain();
2594 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002595 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002596 // keep outputs as l-values, evaluate input-only as r-values
2597 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2598 // save l-value
2599 lValues.push_back(builder.getAccessChain());
2600 } else {
2601 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002602 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002603 }
2604 }
2605
2606 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2607 // copy the original into that space.
2608 //
2609 // Also, build up the list of actual arguments to pass in for the call
2610 int lValueCount = 0;
2611 int rValueCount = 0;
2612 std::vector<spv::Id> spvArgs;
2613 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2614 spv::Id arg;
2615 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2616 // need space to hold the copy
2617 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2618 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2619 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2620 // need to copy the input into output space
2621 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002622 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002623 builder.createStore(copy, arg);
2624 }
2625 ++lValueCount;
2626 } else {
2627 arg = rValues[rValueCount];
2628 ++rValueCount;
2629 }
2630 spvArgs.push_back(arg);
2631 }
2632
2633 // 3. Make the call.
2634 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002635 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002636
2637 // 4. Copy back out an "out" arguments.
2638 lValueCount = 0;
2639 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2640 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2641 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2642 spv::Id copy = builder.createLoad(spvArgs[a]);
2643 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002644 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002645 }
2646 ++lValueCount;
2647 }
2648 }
2649
2650 return result;
2651}
2652
2653// Translate AST operation to SPV operation, already having SPV-based operands/types.
2654spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2655 spv::Id typeId, spv::Id left, spv::Id right,
2656 glslang::TBasicType typeProxy, bool reduceComparison)
2657{
Rex Xu8ff43de2016-04-22 16:51:45 +08002658 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002659 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002660 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002661
2662 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002663 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002664 bool comparison = false;
2665
2666 switch (op) {
2667 case glslang::EOpAdd:
2668 case glslang::EOpAddAssign:
2669 if (isFloat)
2670 binOp = spv::OpFAdd;
2671 else
2672 binOp = spv::OpIAdd;
2673 break;
2674 case glslang::EOpSub:
2675 case glslang::EOpSubAssign:
2676 if (isFloat)
2677 binOp = spv::OpFSub;
2678 else
2679 binOp = spv::OpISub;
2680 break;
2681 case glslang::EOpMul:
2682 case glslang::EOpMulAssign:
2683 if (isFloat)
2684 binOp = spv::OpFMul;
2685 else
2686 binOp = spv::OpIMul;
2687 break;
2688 case glslang::EOpVectorTimesScalar:
2689 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002690 if (isFloat) {
2691 if (builder.isVector(right))
2692 std::swap(left, right);
2693 assert(builder.isScalar(right));
2694 needMatchingVectors = false;
2695 binOp = spv::OpVectorTimesScalar;
2696 } else
2697 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002698 break;
2699 case glslang::EOpVectorTimesMatrix:
2700 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002701 binOp = spv::OpVectorTimesMatrix;
2702 break;
2703 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002704 binOp = spv::OpMatrixTimesVector;
2705 break;
2706 case glslang::EOpMatrixTimesScalar:
2707 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002708 binOp = spv::OpMatrixTimesScalar;
2709 break;
2710 case glslang::EOpMatrixTimesMatrix:
2711 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002712 binOp = spv::OpMatrixTimesMatrix;
2713 break;
2714 case glslang::EOpOuterProduct:
2715 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002716 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002717 break;
2718
2719 case glslang::EOpDiv:
2720 case glslang::EOpDivAssign:
2721 if (isFloat)
2722 binOp = spv::OpFDiv;
2723 else if (isUnsigned)
2724 binOp = spv::OpUDiv;
2725 else
2726 binOp = spv::OpSDiv;
2727 break;
2728 case glslang::EOpMod:
2729 case glslang::EOpModAssign:
2730 if (isFloat)
2731 binOp = spv::OpFMod;
2732 else if (isUnsigned)
2733 binOp = spv::OpUMod;
2734 else
2735 binOp = spv::OpSMod;
2736 break;
2737 case glslang::EOpRightShift:
2738 case glslang::EOpRightShiftAssign:
2739 if (isUnsigned)
2740 binOp = spv::OpShiftRightLogical;
2741 else
2742 binOp = spv::OpShiftRightArithmetic;
2743 break;
2744 case glslang::EOpLeftShift:
2745 case glslang::EOpLeftShiftAssign:
2746 binOp = spv::OpShiftLeftLogical;
2747 break;
2748 case glslang::EOpAnd:
2749 case glslang::EOpAndAssign:
2750 binOp = spv::OpBitwiseAnd;
2751 break;
2752 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002753 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002754 binOp = spv::OpLogicalAnd;
2755 break;
2756 case glslang::EOpInclusiveOr:
2757 case glslang::EOpInclusiveOrAssign:
2758 binOp = spv::OpBitwiseOr;
2759 break;
2760 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002761 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002762 binOp = spv::OpLogicalOr;
2763 break;
2764 case glslang::EOpExclusiveOr:
2765 case glslang::EOpExclusiveOrAssign:
2766 binOp = spv::OpBitwiseXor;
2767 break;
2768 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002769 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002770 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002771 break;
2772
2773 case glslang::EOpLessThan:
2774 case glslang::EOpGreaterThan:
2775 case glslang::EOpLessThanEqual:
2776 case glslang::EOpGreaterThanEqual:
2777 case glslang::EOpEqual:
2778 case glslang::EOpNotEqual:
2779 case glslang::EOpVectorEqual:
2780 case glslang::EOpVectorNotEqual:
2781 comparison = true;
2782 break;
2783 default:
2784 break;
2785 }
2786
John Kessenich7c1aa102015-10-15 13:29:11 -06002787 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002788 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002789 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002790 if (builder.isMatrix(left) || builder.isMatrix(right))
2791 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002792
2793 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002794 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002795 builder.promoteScalar(precision, left, right);
2796
John Kessenich32cfd492016-02-02 12:37:46 -07002797 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002798 }
2799
2800 if (! comparison)
2801 return 0;
2802
John Kessenich7c1aa102015-10-15 13:29:11 -06002803 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002804
2805 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2806 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2807
John Kessenich22118352015-12-21 20:54:09 -07002808 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002809 }
2810
2811 switch (op) {
2812 case glslang::EOpLessThan:
2813 if (isFloat)
2814 binOp = spv::OpFOrdLessThan;
2815 else if (isUnsigned)
2816 binOp = spv::OpULessThan;
2817 else
2818 binOp = spv::OpSLessThan;
2819 break;
2820 case glslang::EOpGreaterThan:
2821 if (isFloat)
2822 binOp = spv::OpFOrdGreaterThan;
2823 else if (isUnsigned)
2824 binOp = spv::OpUGreaterThan;
2825 else
2826 binOp = spv::OpSGreaterThan;
2827 break;
2828 case glslang::EOpLessThanEqual:
2829 if (isFloat)
2830 binOp = spv::OpFOrdLessThanEqual;
2831 else if (isUnsigned)
2832 binOp = spv::OpULessThanEqual;
2833 else
2834 binOp = spv::OpSLessThanEqual;
2835 break;
2836 case glslang::EOpGreaterThanEqual:
2837 if (isFloat)
2838 binOp = spv::OpFOrdGreaterThanEqual;
2839 else if (isUnsigned)
2840 binOp = spv::OpUGreaterThanEqual;
2841 else
2842 binOp = spv::OpSGreaterThanEqual;
2843 break;
2844 case glslang::EOpEqual:
2845 case glslang::EOpVectorEqual:
2846 if (isFloat)
2847 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002848 else if (isBool)
2849 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002850 else
2851 binOp = spv::OpIEqual;
2852 break;
2853 case glslang::EOpNotEqual:
2854 case glslang::EOpVectorNotEqual:
2855 if (isFloat)
2856 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002857 else if (isBool)
2858 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002859 else
2860 binOp = spv::OpINotEqual;
2861 break;
2862 default:
2863 break;
2864 }
2865
John Kessenich32cfd492016-02-02 12:37:46 -07002866 if (binOp != spv::OpNop)
2867 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002868
2869 return 0;
2870}
2871
John Kessenich04bb8a02015-12-12 12:28:14 -07002872//
2873// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2874// These can be any of:
2875//
2876// matrix * scalar
2877// scalar * matrix
2878// matrix * matrix linear algebraic
2879// matrix * vector
2880// vector * matrix
2881// matrix * matrix componentwise
2882// matrix op matrix op in {+, -, /}
2883// matrix op scalar op in {+, -, /}
2884// scalar op matrix op in {+, -, /}
2885//
2886spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2887{
2888 bool firstClass = true;
2889
2890 // First, handle first-class matrix operations (* and matrix/scalar)
2891 switch (op) {
2892 case spv::OpFDiv:
2893 if (builder.isMatrix(left) && builder.isScalar(right)) {
2894 // turn matrix / scalar into a multiply...
2895 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2896 op = spv::OpMatrixTimesScalar;
2897 } else
2898 firstClass = false;
2899 break;
2900 case spv::OpMatrixTimesScalar:
2901 if (builder.isMatrix(right))
2902 std::swap(left, right);
2903 assert(builder.isScalar(right));
2904 break;
2905 case spv::OpVectorTimesMatrix:
2906 assert(builder.isVector(left));
2907 assert(builder.isMatrix(right));
2908 break;
2909 case spv::OpMatrixTimesVector:
2910 assert(builder.isMatrix(left));
2911 assert(builder.isVector(right));
2912 break;
2913 case spv::OpMatrixTimesMatrix:
2914 assert(builder.isMatrix(left));
2915 assert(builder.isMatrix(right));
2916 break;
2917 default:
2918 firstClass = false;
2919 break;
2920 }
2921
John Kessenich32cfd492016-02-02 12:37:46 -07002922 if (firstClass)
2923 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002924
2925 // Handle component-wise +, -, *, and / for all combinations of type.
2926 // The result type of all of them is the same type as the (a) matrix operand.
2927 // The algorithm is to:
2928 // - break the matrix(es) into vectors
2929 // - smear any scalar to a vector
2930 // - do vector operations
2931 // - make a matrix out the vector results
2932 switch (op) {
2933 case spv::OpFAdd:
2934 case spv::OpFSub:
2935 case spv::OpFDiv:
2936 case spv::OpFMul:
2937 {
2938 // one time set up...
2939 bool leftMat = builder.isMatrix(left);
2940 bool rightMat = builder.isMatrix(right);
2941 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2942 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2943 spv::Id scalarType = builder.getScalarTypeId(typeId);
2944 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2945 std::vector<spv::Id> results;
2946 spv::Id smearVec = spv::NoResult;
2947 if (builder.isScalar(left))
2948 smearVec = builder.smearScalar(precision, left, vecType);
2949 else if (builder.isScalar(right))
2950 smearVec = builder.smearScalar(precision, right, vecType);
2951
2952 // do each vector op
2953 for (unsigned int c = 0; c < numCols; ++c) {
2954 std::vector<unsigned int> indexes;
2955 indexes.push_back(c);
2956 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2957 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2958 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2959 builder.setPrecision(results.back(), precision);
2960 }
2961
2962 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002963 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002964 }
2965 default:
2966 assert(0);
2967 return spv::NoResult;
2968 }
2969}
2970
Rex Xu04db3f52015-09-16 11:44:02 +08002971spv::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 -06002972{
2973 spv::Op unaryOp = spv::OpNop;
2974 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08002975 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08002976 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002977
2978 switch (op) {
2979 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002980 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002981 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002982 if (builder.isMatrixType(typeId))
2983 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2984 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002985 unaryOp = spv::OpSNegate;
2986 break;
2987
2988 case glslang::EOpLogicalNot:
2989 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002990 unaryOp = spv::OpLogicalNot;
2991 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002992 case glslang::EOpBitwiseNot:
2993 unaryOp = spv::OpNot;
2994 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002995
John Kessenich140f3df2015-06-26 16:58:36 -06002996 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002997 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002998 break;
2999 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003000 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003001 break;
3002 case glslang::EOpTranspose:
3003 unaryOp = spv::OpTranspose;
3004 break;
3005
3006 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003007 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003008 break;
3009 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003010 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003011 break;
3012 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003013 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003014 break;
3015 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003017 break;
3018 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003019 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 break;
3021 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003022 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003023 break;
3024 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 break;
3027 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003028 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 break;
3030
3031 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003032 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003033 break;
3034 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003035 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 break;
3037 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049
3050 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003051 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003052 break;
3053 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003054 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003055 break;
3056
3057 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003058 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003059 break;
3060 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003061 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003062 break;
3063 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003064 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003065 break;
3066 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003067 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003068 break;
3069 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003070 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003071 break;
3072 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003073 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003074 break;
3075
3076 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003077 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003078 break;
3079 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003080 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003081 break;
3082 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003083 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003084 break;
3085 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 break;
3088 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003089 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003090 break;
3091 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094
3095 case glslang::EOpIsNan:
3096 unaryOp = spv::OpIsNan;
3097 break;
3098 case glslang::EOpIsInf:
3099 unaryOp = spv::OpIsInf;
3100 break;
3101
Rex Xucbc426e2015-12-15 16:03:10 +08003102 case glslang::EOpFloatBitsToInt:
3103 case glslang::EOpFloatBitsToUint:
3104 case glslang::EOpIntBitsToFloat:
3105 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003106 case glslang::EOpDoubleBitsToInt64:
3107 case glslang::EOpDoubleBitsToUint64:
3108 case glslang::EOpInt64BitsToDouble:
3109 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003110 unaryOp = spv::OpBitcast;
3111 break;
3112
John Kessenich140f3df2015-06-26 16:58:36 -06003113 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003114 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003115 break;
3116 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003118 break;
3119 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003131 case glslang::EOpPackSnorm4x8:
3132 libCall = spv::GLSLstd450PackSnorm4x8;
3133 break;
3134 case glslang::EOpUnpackSnorm4x8:
3135 libCall = spv::GLSLstd450UnpackSnorm4x8;
3136 break;
3137 case glslang::EOpPackUnorm4x8:
3138 libCall = spv::GLSLstd450PackUnorm4x8;
3139 break;
3140 case glslang::EOpUnpackUnorm4x8:
3141 libCall = spv::GLSLstd450UnpackUnorm4x8;
3142 break;
3143 case glslang::EOpPackDouble2x32:
3144 libCall = spv::GLSLstd450PackDouble2x32;
3145 break;
3146 case glslang::EOpUnpackDouble2x32:
3147 libCall = spv::GLSLstd450UnpackDouble2x32;
3148 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003149
Rex Xu8ff43de2016-04-22 16:51:45 +08003150 case glslang::EOpPackInt2x32:
3151 case glslang::EOpUnpackInt2x32:
3152 case glslang::EOpPackUint2x32:
3153 case glslang::EOpUnpackUint2x32:
Lei Zhang09caf122016-05-02 18:11:54 -04003154 spv::MissingFunctionality(warningsErrors, "shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003155 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3156 break;
3157
John Kessenich140f3df2015-06-26 16:58:36 -06003158 case glslang::EOpDPdx:
3159 unaryOp = spv::OpDPdx;
3160 break;
3161 case glslang::EOpDPdy:
3162 unaryOp = spv::OpDPdy;
3163 break;
3164 case glslang::EOpFwidth:
3165 unaryOp = spv::OpFwidth;
3166 break;
3167 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003168 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003169 unaryOp = spv::OpDPdxFine;
3170 break;
3171 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003172 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003173 unaryOp = spv::OpDPdyFine;
3174 break;
3175 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003176 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003177 unaryOp = spv::OpFwidthFine;
3178 break;
3179 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003180 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003181 unaryOp = spv::OpDPdxCoarse;
3182 break;
3183 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003184 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003185 unaryOp = spv::OpDPdyCoarse;
3186 break;
3187 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003188 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003189 unaryOp = spv::OpFwidthCoarse;
3190 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003191 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003192 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003193 libCall = spv::GLSLstd450InterpolateAtCentroid;
3194 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003195 case glslang::EOpAny:
3196 unaryOp = spv::OpAny;
3197 break;
3198 case glslang::EOpAll:
3199 unaryOp = spv::OpAll;
3200 break;
3201
3202 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003203 if (isFloat)
3204 libCall = spv::GLSLstd450FAbs;
3205 else
3206 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003207 break;
3208 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003209 if (isFloat)
3210 libCall = spv::GLSLstd450FSign;
3211 else
3212 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003213 break;
3214
John Kessenichfc51d282015-08-19 13:34:18 -06003215 case glslang::EOpAtomicCounterIncrement:
3216 case glslang::EOpAtomicCounterDecrement:
3217 case glslang::EOpAtomicCounter:
3218 {
3219 // Handle all of the atomics in one place, in createAtomicOperation()
3220 std::vector<spv::Id> operands;
3221 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003222 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003223 }
3224
John Kessenichfc51d282015-08-19 13:34:18 -06003225 case glslang::EOpBitFieldReverse:
3226 unaryOp = spv::OpBitReverse;
3227 break;
3228 case glslang::EOpBitCount:
3229 unaryOp = spv::OpBitCount;
3230 break;
3231 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003232 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003233 break;
3234 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003235 if (isUnsigned)
3236 libCall = spv::GLSLstd450FindUMsb;
3237 else
3238 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003239 break;
3240
John Kessenich140f3df2015-06-26 16:58:36 -06003241 default:
3242 return 0;
3243 }
3244
3245 spv::Id id;
3246 if (libCall >= 0) {
3247 std::vector<spv::Id> args;
3248 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003249 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003250 } else
3251 id = builder.createUnaryOp(unaryOp, typeId, operand);
3252
John Kessenich32cfd492016-02-02 12:37:46 -07003253 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003254}
3255
John Kessenich7a53f762016-01-20 11:19:27 -07003256// Create a unary operation on a matrix
3257spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3258{
3259 // Handle unary operations vector by vector.
3260 // The result type is the same type as the original type.
3261 // The algorithm is to:
3262 // - break the matrix into vectors
3263 // - apply the operation to each vector
3264 // - make a matrix out the vector results
3265
3266 // get the types sorted out
3267 int numCols = builder.getNumColumns(operand);
3268 int numRows = builder.getNumRows(operand);
3269 spv::Id scalarType = builder.getScalarTypeId(typeId);
3270 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3271 std::vector<spv::Id> results;
3272
3273 // do each vector op
3274 for (int c = 0; c < numCols; ++c) {
3275 std::vector<unsigned int> indexes;
3276 indexes.push_back(c);
3277 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3278 results.push_back(builder.createUnaryOp(op, vecType, vec));
3279 builder.setPrecision(results.back(), precision);
3280 }
3281
3282 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003283 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003284}
3285
John Kessenich140f3df2015-06-26 16:58:36 -06003286spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3287{
3288 spv::Op convOp = spv::OpNop;
3289 spv::Id zero = 0;
3290 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003291 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003292
3293 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3294
3295 switch (op) {
3296 case glslang::EOpConvIntToBool:
3297 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003298 case glslang::EOpConvInt64ToBool:
3299 case glslang::EOpConvUint64ToBool:
3300 zero = (op == glslang::EOpConvInt64ToBool ||
3301 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003302 zero = makeSmearedConstant(zero, vectorSize);
3303 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3304
3305 case glslang::EOpConvFloatToBool:
3306 zero = builder.makeFloatConstant(0.0F);
3307 zero = makeSmearedConstant(zero, vectorSize);
3308 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3309
3310 case glslang::EOpConvDoubleToBool:
3311 zero = builder.makeDoubleConstant(0.0);
3312 zero = makeSmearedConstant(zero, vectorSize);
3313 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3314
3315 case glslang::EOpConvBoolToFloat:
3316 convOp = spv::OpSelect;
3317 zero = builder.makeFloatConstant(0.0);
3318 one = builder.makeFloatConstant(1.0);
3319 break;
3320 case glslang::EOpConvBoolToDouble:
3321 convOp = spv::OpSelect;
3322 zero = builder.makeDoubleConstant(0.0);
3323 one = builder.makeDoubleConstant(1.0);
3324 break;
3325 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003326 case glslang::EOpConvBoolToInt64:
3327 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3328 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003329 convOp = spv::OpSelect;
3330 break;
3331 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003332 case glslang::EOpConvBoolToUint64:
3333 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3334 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003335 convOp = spv::OpSelect;
3336 break;
3337
3338 case glslang::EOpConvIntToFloat:
3339 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003340 case glslang::EOpConvInt64ToFloat:
3341 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003342 convOp = spv::OpConvertSToF;
3343 break;
3344
3345 case glslang::EOpConvUintToFloat:
3346 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003347 case glslang::EOpConvUint64ToFloat:
3348 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003349 convOp = spv::OpConvertUToF;
3350 break;
3351
3352 case glslang::EOpConvDoubleToFloat:
3353 case glslang::EOpConvFloatToDouble:
3354 convOp = spv::OpFConvert;
3355 break;
3356
3357 case glslang::EOpConvFloatToInt:
3358 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003359 case glslang::EOpConvFloatToInt64:
3360 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003361 convOp = spv::OpConvertFToS;
3362 break;
3363
3364 case glslang::EOpConvUintToInt:
3365 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003366 case glslang::EOpConvUint64ToInt64:
3367 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003368 if (builder.isInSpecConstCodeGenMode()) {
3369 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003370 zero = (op == glslang::EOpConvUintToInt64 ||
3371 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003372 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003373 // Use OpIAdd, instead of OpBitcast to do the conversion when
3374 // generating for OpSpecConstantOp instruction.
3375 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3376 }
3377 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003378 convOp = spv::OpBitcast;
3379 break;
3380
3381 case glslang::EOpConvFloatToUint:
3382 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003383 case glslang::EOpConvFloatToUint64:
3384 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003385 convOp = spv::OpConvertFToU;
3386 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003387
3388 case glslang::EOpConvIntToInt64:
3389 case glslang::EOpConvInt64ToInt:
3390 convOp = spv::OpSConvert;
3391 break;
3392
3393 case glslang::EOpConvUintToUint64:
3394 case glslang::EOpConvUint64ToUint:
3395 convOp = spv::OpUConvert;
3396 break;
3397
3398 case glslang::EOpConvIntToUint64:
3399 case glslang::EOpConvInt64ToUint:
3400 case glslang::EOpConvUint64ToInt:
3401 case glslang::EOpConvUintToInt64:
3402 // OpSConvert/OpUConvert + OpBitCast
3403 switch (op) {
3404 case glslang::EOpConvIntToUint64:
3405 convOp = spv::OpSConvert;
3406 type = builder.makeIntType(64);
3407 break;
3408 case glslang::EOpConvInt64ToUint:
3409 convOp = spv::OpSConvert;
3410 type = builder.makeIntType(32);
3411 break;
3412 case glslang::EOpConvUint64ToInt:
3413 convOp = spv::OpUConvert;
3414 type = builder.makeUintType(32);
3415 break;
3416 case glslang::EOpConvUintToInt64:
3417 convOp = spv::OpUConvert;
3418 type = builder.makeUintType(64);
3419 break;
3420 default:
3421 assert(0);
3422 break;
3423 }
3424
3425 if (vectorSize > 0)
3426 type = builder.makeVectorType(type, vectorSize);
3427
3428 operand = builder.createUnaryOp(convOp, type, operand);
3429
3430 if (builder.isInSpecConstCodeGenMode()) {
3431 // Build zero scalar or vector for OpIAdd.
3432 zero = (op == glslang::EOpConvIntToUint64 ||
3433 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3434 zero = makeSmearedConstant(zero, vectorSize);
3435 // Use OpIAdd, instead of OpBitcast to do the conversion when
3436 // generating for OpSpecConstantOp instruction.
3437 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3438 }
3439 // For normal run-time conversion instruction, use OpBitcast.
3440 convOp = spv::OpBitcast;
3441 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003442 default:
3443 break;
3444 }
3445
3446 spv::Id result = 0;
3447 if (convOp == spv::OpNop)
3448 return result;
3449
3450 if (convOp == spv::OpSelect) {
3451 zero = makeSmearedConstant(zero, vectorSize);
3452 one = makeSmearedConstant(one, vectorSize);
3453 result = builder.createTriOp(convOp, destType, operand, one, zero);
3454 } else
3455 result = builder.createUnaryOp(convOp, destType, operand);
3456
John Kessenich32cfd492016-02-02 12:37:46 -07003457 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003458}
3459
3460spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3461{
3462 if (vectorSize == 0)
3463 return constant;
3464
3465 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3466 std::vector<spv::Id> components;
3467 for (int c = 0; c < vectorSize; ++c)
3468 components.push_back(constant);
3469 return builder.makeCompositeConstant(vectorTypeId, components);
3470}
3471
John Kessenich426394d2015-07-23 10:22:48 -06003472// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003473spv::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 -06003474{
3475 spv::Op opCode = spv::OpNop;
3476
3477 switch (op) {
3478 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003479 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003480 opCode = spv::OpAtomicIAdd;
3481 break;
3482 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003483 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003484 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003485 break;
3486 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003487 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003488 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003489 break;
3490 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003491 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003492 opCode = spv::OpAtomicAnd;
3493 break;
3494 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003495 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003496 opCode = spv::OpAtomicOr;
3497 break;
3498 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003499 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003500 opCode = spv::OpAtomicXor;
3501 break;
3502 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003503 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003504 opCode = spv::OpAtomicExchange;
3505 break;
3506 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003507 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003508 opCode = spv::OpAtomicCompareExchange;
3509 break;
3510 case glslang::EOpAtomicCounterIncrement:
3511 opCode = spv::OpAtomicIIncrement;
3512 break;
3513 case glslang::EOpAtomicCounterDecrement:
3514 opCode = spv::OpAtomicIDecrement;
3515 break;
3516 case glslang::EOpAtomicCounter:
3517 opCode = spv::OpAtomicLoad;
3518 break;
3519 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003520 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003521 break;
3522 }
3523
3524 // Sort out the operands
3525 // - mapping from glslang -> SPV
3526 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003527 // - compare-exchange swaps the value and comparator
3528 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003529 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3530 auto opIt = operands.begin(); // walk the glslang operands
3531 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003532 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3533 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3534 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003535 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3536 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003537 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003538 spvAtomicOperands.push_back(*(opIt + 1));
3539 spvAtomicOperands.push_back(*opIt);
3540 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003541 }
John Kessenich426394d2015-07-23 10:22:48 -06003542
John Kessenich3e60a6f2015-09-14 22:45:16 -06003543 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003544 for (; opIt != operands.end(); ++opIt)
3545 spvAtomicOperands.push_back(*opIt);
3546
3547 return builder.createOp(opCode, typeId, spvAtomicOperands);
3548}
3549
John Kessenich5e4b1242015-08-06 22:53:06 -06003550spv::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 -06003551{
Rex Xu8ff43de2016-04-22 16:51:45 +08003552 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003553 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3554
John Kessenich140f3df2015-06-26 16:58:36 -06003555 spv::Op opCode = spv::OpNop;
3556 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003557 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003558 spv::Id typeId0 = 0;
3559 if (consumedOperands > 0)
3560 typeId0 = builder.getTypeId(operands[0]);
3561 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003562
3563 switch (op) {
3564 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003565 if (isFloat)
3566 libCall = spv::GLSLstd450FMin;
3567 else if (isUnsigned)
3568 libCall = spv::GLSLstd450UMin;
3569 else
3570 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003571 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003572 break;
3573 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003574 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003575 break;
3576 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003577 if (isFloat)
3578 libCall = spv::GLSLstd450FMax;
3579 else if (isUnsigned)
3580 libCall = spv::GLSLstd450UMax;
3581 else
3582 libCall = spv::GLSLstd450SMax;
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::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003586 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003587 break;
3588 case glslang::EOpDot:
3589 opCode = spv::OpDot;
3590 break;
3591 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003592 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003593 break;
3594
3595 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003596 if (isFloat)
3597 libCall = spv::GLSLstd450FClamp;
3598 else if (isUnsigned)
3599 libCall = spv::GLSLstd450UClamp;
3600 else
3601 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003602 builder.promoteScalar(precision, operands.front(), operands[1]);
3603 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 break;
3605 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003606 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3607 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003608 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003609 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003610 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003611 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003612 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003613 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003614 break;
3615 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003616 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003617 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003618 break;
3619 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003620 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003621 builder.promoteScalar(precision, operands[0], operands[2]);
3622 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003623 break;
3624
3625 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003626 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003627 break;
3628 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003630 break;
3631 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003632 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003633 break;
3634 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003635 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003636 break;
3637 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003638 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003639 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003640 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003641 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003642 libCall = spv::GLSLstd450InterpolateAtSample;
3643 break;
3644 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003645 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003646 libCall = spv::GLSLstd450InterpolateAtOffset;
3647 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003648 case glslang::EOpAddCarry:
3649 opCode = spv::OpIAddCarry;
3650 typeId = builder.makeStructResultType(typeId0, typeId0);
3651 consumedOperands = 2;
3652 break;
3653 case glslang::EOpSubBorrow:
3654 opCode = spv::OpISubBorrow;
3655 typeId = builder.makeStructResultType(typeId0, typeId0);
3656 consumedOperands = 2;
3657 break;
3658 case glslang::EOpUMulExtended:
3659 opCode = spv::OpUMulExtended;
3660 typeId = builder.makeStructResultType(typeId0, typeId0);
3661 consumedOperands = 2;
3662 break;
3663 case glslang::EOpIMulExtended:
3664 opCode = spv::OpSMulExtended;
3665 typeId = builder.makeStructResultType(typeId0, typeId0);
3666 consumedOperands = 2;
3667 break;
3668 case glslang::EOpBitfieldExtract:
3669 if (isUnsigned)
3670 opCode = spv::OpBitFieldUExtract;
3671 else
3672 opCode = spv::OpBitFieldSExtract;
3673 break;
3674 case glslang::EOpBitfieldInsert:
3675 opCode = spv::OpBitFieldInsert;
3676 break;
3677
3678 case glslang::EOpFma:
3679 libCall = spv::GLSLstd450Fma;
3680 break;
3681 case glslang::EOpFrexp:
3682 libCall = spv::GLSLstd450FrexpStruct;
3683 if (builder.getNumComponents(operands[0]) == 1)
3684 frexpIntType = builder.makeIntegerType(32, true);
3685 else
3686 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3687 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3688 consumedOperands = 1;
3689 break;
3690 case glslang::EOpLdexp:
3691 libCall = spv::GLSLstd450Ldexp;
3692 break;
3693
John Kessenich140f3df2015-06-26 16:58:36 -06003694 default:
3695 return 0;
3696 }
3697
3698 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003699 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003700 // Use an extended instruction from the standard library.
3701 // Construct the call arguments, without modifying the original operands vector.
3702 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3703 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003704 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003705 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003706 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003707 case 0:
3708 // should all be handled by visitAggregate and createNoArgOperation
3709 assert(0);
3710 return 0;
3711 case 1:
3712 // should all be handled by createUnaryOperation
3713 assert(0);
3714 return 0;
3715 case 2:
3716 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3717 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003718 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003719 // anything 3 or over doesn't have l-value operands, so all should be consumed
3720 assert(consumedOperands == operands.size());
3721 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 }
3724 }
3725
John Kessenich55e7d112015-11-15 21:33:39 -07003726 // Decode the return types that were structures
3727 switch (op) {
3728 case glslang::EOpAddCarry:
3729 case glslang::EOpSubBorrow:
3730 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3731 id = builder.createCompositeExtract(id, typeId0, 0);
3732 break;
3733 case glslang::EOpUMulExtended:
3734 case glslang::EOpIMulExtended:
3735 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3736 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3737 break;
3738 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003739 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003740 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3741 id = builder.createCompositeExtract(id, typeId0, 0);
3742 break;
3743 default:
3744 break;
3745 }
3746
John Kessenich32cfd492016-02-02 12:37:46 -07003747 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003748}
3749
3750// Intrinsics with no arguments, no return value, and no precision.
3751spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3752{
3753 // TODO: get the barrier operands correct
3754
3755 switch (op) {
3756 case glslang::EOpEmitVertex:
3757 builder.createNoResultOp(spv::OpEmitVertex);
3758 return 0;
3759 case glslang::EOpEndPrimitive:
3760 builder.createNoResultOp(spv::OpEndPrimitive);
3761 return 0;
3762 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003763 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3764 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003765 return 0;
3766 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003768 return 0;
3769 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003771 return 0;
3772 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003774 return 0;
3775 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003777 return 0;
3778 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003779 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003780 return 0;
3781 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003782 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003783 return 0;
3784 default:
Lei Zhang09caf122016-05-02 18:11:54 -04003785 spv::MissingFunctionality(warningsErrors, "unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003786 return 0;
3787 }
3788}
3789
3790spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3791{
John Kessenich2f273362015-07-18 22:34:27 -06003792 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003793 spv::Id id;
3794 if (symbolValues.end() != iter) {
3795 id = iter->second;
3796 return id;
3797 }
3798
3799 // it was not found, create it
3800 id = createSpvVariable(symbol);
3801 symbolValues[symbol->getId()] = id;
3802
3803 if (! symbol->getType().isStruct()) {
3804 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003805 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003806 if (symbol->getType().getQualifier().hasSpecConstantId())
3807 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003808 if (symbol->getQualifier().hasLocation())
3809 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3810 if (symbol->getQualifier().hasIndex())
3811 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3812 if (symbol->getQualifier().hasComponent())
3813 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3814 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003815 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003816 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003818 if (symbol->getQualifier().hasXfbBuffer())
3819 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3820 if (symbol->getQualifier().hasXfbOffset())
3821 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3822 }
3823 }
3824
John Kesseniche0b6cad2015-12-24 10:30:13 -07003825 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003826 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003827 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003828 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003829 }
John Kessenich140f3df2015-06-26 16:58:36 -06003830 if (symbol->getQualifier().hasSet())
3831 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003832 else if (IsDescriptorResource(symbol->getType())) {
3833 // default to 0
3834 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3835 }
John Kessenich140f3df2015-06-26 16:58:36 -06003836 if (symbol->getQualifier().hasBinding())
3837 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003838 if (symbol->getQualifier().hasAttachment())
3839 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003840 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003841 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003842 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003843 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003844 if (symbol->getQualifier().hasXfbBuffer())
3845 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3846 }
3847
Rex Xu1da878f2016-02-21 20:59:01 +08003848 if (symbol->getType().isImage()) {
3849 std::vector<spv::Decoration> memory;
3850 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3851 for (unsigned int i = 0; i < memory.size(); ++i)
3852 addDecoration(id, memory[i]);
3853 }
3854
John Kessenich140f3df2015-06-26 16:58:36 -06003855 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003856 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003858 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003859
John Kessenich140f3df2015-06-26 16:58:36 -06003860 return id;
3861}
3862
John Kessenich55e7d112015-11-15 21:33:39 -07003863// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003864void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3865{
3866 if (dec != spv::BadValue)
3867 builder.addDecoration(id, dec);
3868}
3869
John Kessenich55e7d112015-11-15 21:33:39 -07003870// If 'dec' is valid, add a one-operand decoration to an object
3871void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3872{
3873 if (dec != spv::BadValue)
3874 builder.addDecoration(id, dec, value);
3875}
3876
3877// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003878void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3879{
3880 if (dec != spv::BadValue)
3881 builder.addMemberDecoration(id, (unsigned)member, dec);
3882}
3883
John Kessenich92187592016-02-01 13:45:25 -07003884// If 'dec' is valid, add a one-operand decoration to a struct member
3885void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3886{
3887 if (dec != spv::BadValue)
3888 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3889}
3890
John Kessenich55e7d112015-11-15 21:33:39 -07003891// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003892// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003893//
3894// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3895//
3896// Recursively walk the nodes. The nodes form a tree whose leaves are
3897// regular constants, which themselves are trees that createSpvConstant()
3898// recursively walks. So, this function walks the "top" of the tree:
3899// - emit specialization constant-building instructions for specConstant
3900// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003901spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003902{
John Kessenich7cc0e282016-03-20 00:46:02 -06003903 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003904
qining4f4bb812016-04-03 23:55:17 -04003905 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003906 if (! node.getQualifier().specConstant) {
3907 // hand off to the non-spec-constant path
3908 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3909 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003910 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003911 nextConst, false);
3912 }
3913
3914 // We now know we have a specialization constant to build
3915
qining4f4bb812016-04-03 23:55:17 -04003916 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3917 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3918 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3919 std::vector<spv::Id> dimConstId;
3920 for (int dim = 0; dim < 3; ++dim) {
3921 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3922 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3923 if (specConst)
3924 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3925 }
3926 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3927 }
3928
3929 // An AST node labelled as specialization constant should be a symbol node.
3930 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3931 if (auto* sn = node.getAsSymbolNode()) {
3932 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04003933 // Traverse the constant constructor sub tree like generating normal run-time instructions.
3934 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
3935 // will set the builder into spec constant op instruction generating mode.
3936 sub_tree->traverse(this);
3937 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04003938 } else if (auto* const_union_array = &sn->getConstArray()){
3939 int nextConst = 0;
3940 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003941 }
3942 }
qining4f4bb812016-04-03 23:55:17 -04003943
3944 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3945 // constant sub tree as initializer.
Lei Zhang09caf122016-05-02 18:11:54 -04003946 spv::MissingFunctionality(warningsErrors, "Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04003947 exit(1);
3948 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003949}
3950
John Kessenich140f3df2015-06-26 16:58:36 -06003951// Use 'consts' as the flattened glslang source of scalar constants to recursively
3952// build the aggregate SPIR-V constant.
3953//
3954// If there are not enough elements present in 'consts', 0 will be substituted;
3955// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3956//
qining08408382016-03-21 09:51:37 -04003957spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003958{
3959 // vector of constants for SPIR-V
3960 std::vector<spv::Id> spvConsts;
3961
3962 // Type is used for struct and array constants
3963 spv::Id typeId = convertGlslangToSpvType(glslangType);
3964
3965 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003966 glslang::TType elementType(glslangType, 0);
3967 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003968 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003969 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003970 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003971 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003972 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003973 } else if (glslangType.getStruct()) {
3974 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3975 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003976 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003977 } else if (glslangType.isVector()) {
3978 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3979 bool zero = nextConst >= consts.size();
3980 switch (glslangType.getBasicType()) {
3981 case glslang::EbtInt:
3982 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3983 break;
3984 case glslang::EbtUint:
3985 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3986 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003987 case glslang::EbtInt64:
3988 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
3989 break;
3990 case glslang::EbtUint64:
3991 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
3992 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003993 case glslang::EbtFloat:
3994 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3995 break;
3996 case glslang::EbtDouble:
3997 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3998 break;
3999 case glslang::EbtBool:
4000 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4001 break;
4002 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004003 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004004 break;
4005 }
4006 ++nextConst;
4007 }
4008 } else {
4009 // we have a non-aggregate (scalar) constant
4010 bool zero = nextConst >= consts.size();
4011 spv::Id scalar = 0;
4012 switch (glslangType.getBasicType()) {
4013 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004014 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004015 break;
4016 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004017 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004018 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004019 case glslang::EbtInt64:
4020 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4021 break;
4022 case glslang::EbtUint64:
4023 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4024 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004025 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004026 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004027 break;
4028 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004029 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004030 break;
4031 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004032 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004033 break;
4034 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004035 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004036 break;
4037 }
4038 ++nextConst;
4039 return scalar;
4040 }
4041
4042 return builder.makeCompositeConstant(typeId, spvConsts);
4043}
4044
John Kessenich7c1aa102015-10-15 13:29:11 -06004045// Return true if the node is a constant or symbol whose reading has no
4046// non-trivial observable cost or effect.
4047bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4048{
4049 // don't know what this is
4050 if (node == nullptr)
4051 return false;
4052
4053 // a constant is safe
4054 if (node->getAsConstantUnion() != nullptr)
4055 return true;
4056
4057 // not a symbol means non-trivial
4058 if (node->getAsSymbolNode() == nullptr)
4059 return false;
4060
4061 // a symbol, depends on what's being read
4062 switch (node->getType().getQualifier().storage) {
4063 case glslang::EvqTemporary:
4064 case glslang::EvqGlobal:
4065 case glslang::EvqIn:
4066 case glslang::EvqInOut:
4067 case glslang::EvqConst:
4068 case glslang::EvqConstReadOnly:
4069 case glslang::EvqUniform:
4070 return true;
4071 default:
4072 return false;
4073 }
4074}
4075
4076// A node is trivial if it is a single operation with no side effects.
4077// Error on the side of saying non-trivial.
4078// Return true if trivial.
4079bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4080{
4081 if (node == nullptr)
4082 return false;
4083
4084 // symbols and constants are trivial
4085 if (isTrivialLeaf(node))
4086 return true;
4087
4088 // otherwise, it needs to be a simple operation or one or two leaf nodes
4089
4090 // not a simple operation
4091 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4092 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4093 if (binaryNode == nullptr && unaryNode == nullptr)
4094 return false;
4095
4096 // not on leaf nodes
4097 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4098 return false;
4099
4100 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4101 return false;
4102 }
4103
4104 switch (node->getAsOperator()->getOp()) {
4105 case glslang::EOpLogicalNot:
4106 case glslang::EOpConvIntToBool:
4107 case glslang::EOpConvUintToBool:
4108 case glslang::EOpConvFloatToBool:
4109 case glslang::EOpConvDoubleToBool:
4110 case glslang::EOpEqual:
4111 case glslang::EOpNotEqual:
4112 case glslang::EOpLessThan:
4113 case glslang::EOpGreaterThan:
4114 case glslang::EOpLessThanEqual:
4115 case glslang::EOpGreaterThanEqual:
4116 case glslang::EOpIndexDirect:
4117 case glslang::EOpIndexDirectStruct:
4118 case glslang::EOpLogicalXor:
4119 case glslang::EOpAny:
4120 case glslang::EOpAll:
4121 return true;
4122 default:
4123 return false;
4124 }
4125}
4126
4127// Emit short-circuiting code, where 'right' is never evaluated unless
4128// the left side is true (for &&) or false (for ||).
4129spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4130{
4131 spv::Id boolTypeId = builder.makeBoolType();
4132
4133 // emit left operand
4134 builder.clearAccessChain();
4135 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004136 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004137
4138 // Operands to accumulate OpPhi operands
4139 std::vector<spv::Id> phiOperands;
4140 // accumulate left operand's phi information
4141 phiOperands.push_back(leftId);
4142 phiOperands.push_back(builder.getBuildPoint()->getId());
4143
4144 // Make the two kinds of operation symmetric with a "!"
4145 // || => emit "if (! left) result = right"
4146 // && => emit "if ( left) result = right"
4147 //
4148 // TODO: this runtime "not" for || could be avoided by adding functionality
4149 // to 'builder' to have an "else" without an "then"
4150 if (op == glslang::EOpLogicalOr)
4151 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4152
4153 // make an "if" based on the left value
4154 spv::Builder::If ifBuilder(leftId, builder);
4155
4156 // emit right operand as the "then" part of the "if"
4157 builder.clearAccessChain();
4158 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004159 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004160
4161 // accumulate left operand's phi information
4162 phiOperands.push_back(rightId);
4163 phiOperands.push_back(builder.getBuildPoint()->getId());
4164
4165 // finish the "if"
4166 ifBuilder.makeEndIf();
4167
4168 // phi together the two results
4169 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4170}
4171
John Kessenich140f3df2015-06-26 16:58:36 -06004172}; // end anonymous namespace
4173
4174namespace glslang {
4175
John Kessenich68d78fd2015-07-12 19:28:10 -06004176void GetSpirvVersion(std::string& version)
4177{
John Kessenich9e55f632015-07-15 10:03:39 -06004178 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004179 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004180 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004181 version = buf;
4182}
4183
John Kessenich140f3df2015-06-26 16:58:36 -06004184// Write SPIR-V out to a binary file
4185void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4186{
4187 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004188 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004189 for (int i = 0; i < (int)spirv.size(); ++i) {
4190 unsigned int word = spirv[i];
4191 out.write((const char*)&word, 4);
4192 }
4193 out.close();
4194}
4195
4196//
4197// Set up the glslang traversal
4198//
4199void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4200{
Lei Zhang09caf122016-05-02 18:11:54 -04004201 GlslangToSpv(intermediate, spirv, nullptr);
4202}
4203
4204void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, std::string* messages)
4205{
John Kessenich140f3df2015-06-26 16:58:36 -06004206 TIntermNode* root = intermediate.getTreeRoot();
4207
4208 if (root == 0)
4209 return;
4210
4211 glslang::GetThreadPoolAllocator().push();
4212
4213 TGlslangToSpvTraverser it(&intermediate);
4214
4215 root->traverse(&it);
4216
4217 it.dumpSpv(spirv);
4218
Lei Zhang09caf122016-05-02 18:11:54 -04004219 if (messages != nullptr) *messages = it.getWarningsAndErrors();
4220
John Kessenich140f3df2015-06-26 16:58:36 -06004221 glslang::GetThreadPoolAllocator().pop();
4222}
4223
4224}; // end namespace glslang