blob: 0240d8d4fd94e0afe87089f59bc5c12b0ca7cbcb [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
88}
89
John Kessenich140f3df2015-06-26 16:58:36 -060090//
91// The main holder of information for translating glslang to SPIR-V.
92//
93// Derives from the AST walking base class.
94//
95class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
96public:
97 TGlslangToSpvTraverser(const glslang::TIntermediate*);
98 virtual ~TGlslangToSpvTraverser();
99
100 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
101 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
102 void visitConstantUnion(glslang::TIntermConstantUnion*);
103 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
104 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
105 void visitSymbol(glslang::TIntermSymbol* symbol);
106 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
107 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
108 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
109
John Kessenich7ba63412015-12-20 17:37:07 -0700110 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112protected:
John Kessenich5e801132016-02-15 11:09:46 -0700113 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -0700114 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -0700115 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600116 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
117 spv::Id getSampledType(const glslang::TSampler&);
118 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700119 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700120 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700121 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800122 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700123 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700124 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
125 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
126 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
129 void makeFunctions(const glslang::TIntermSequence&);
130 void makeGlobalInitializers(const glslang::TIntermSequence&);
131 void visitFunctions(const glslang::TIntermSequence&);
132 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800133 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600134 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
135 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600136 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
137
138 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700139 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800140 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700141 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
143 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800144 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
qining13545202016-03-21 09:51:37 -0400154 spv::Id createSpvConstantFromConstSubTree(glslang::TIntermTyped* subTree);
John Kessenich7c1aa102015-10-15 13:29:11 -0600155 bool isTrivialLeaf(const glslang::TIntermTyped* node);
156 bool isTrivial(const glslang::TIntermTyped* node);
157 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600158
159 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700160 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600161 int sequenceDepth;
162
163 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
164 spv::Builder builder;
165 bool inMain;
166 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700167 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 -0700168 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600169 const glslang::TIntermediate* glslangIntermediate;
170 spv::Id stdBuiltins;
171
John Kessenich2f273362015-07-18 22:34:27 -0600172 std::unordered_map<int, spv::Id> symbolValues;
173 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
174 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700175 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600176 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 -0600177 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600178};
179
180//
181// Helper functions for translating glslang representations to SPIR-V enumerants.
182//
183
184// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700185spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600186{
John Kessenich66e2faf2016-03-12 18:34:36 -0700187 switch (source) {
188 case glslang::EShSourceGlsl:
189 switch (profile) {
190 case ENoProfile:
191 case ECoreProfile:
192 case ECompatibilityProfile:
193 return spv::SourceLanguageGLSL;
194 case EEsProfile:
195 return spv::SourceLanguageESSL;
196 default:
197 return spv::SourceLanguageUnknown;
198 }
199 case glslang::EShSourceHlsl:
200 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600201 default:
202 return spv::SourceLanguageUnknown;
203 }
204}
205
206// Translate glslang language (stage) to SPIR-V execution model.
207spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
208{
209 switch (stage) {
210 case EShLangVertex: return spv::ExecutionModelVertex;
211 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
212 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
213 case EShLangGeometry: return spv::ExecutionModelGeometry;
214 case EShLangFragment: return spv::ExecutionModelFragment;
215 case EShLangCompute: return spv::ExecutionModelGLCompute;
216 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600218 return spv::ExecutionModelFragment;
219 }
220}
221
222// Translate glslang type to SPIR-V storage class.
223spv::StorageClass TranslateStorageClass(const glslang::TType& type)
224{
225 if (type.getQualifier().isPipeInput())
226 return spv::StorageClassInput;
227 else if (type.getQualifier().isPipeOutput())
228 return spv::StorageClassOutput;
229 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700230 if (type.getQualifier().layoutPushConstant)
231 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600232 if (type.getBasicType() == glslang::EbtBlock)
233 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800234 else if (type.getBasicType() == glslang::EbtAtomicUint)
235 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 else
237 return spv::StorageClassUniformConstant;
238 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
239 } else {
240 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700241 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
242 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600243 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
244 case glslang::EvqTemporary: return spv::StorageClassFunction;
245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::StorageClassFunction;
248 }
249 }
250}
251
252// Translate glslang sampler type to SPIR-V dimensionality.
253spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
254{
255 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700256 case glslang::Esd1D: return spv::Dim1D;
257 case glslang::Esd2D: return spv::Dim2D;
258 case glslang::Esd3D: return spv::Dim3D;
259 case glslang::EsdCube: return spv::DimCube;
260 case glslang::EsdRect: return spv::DimRect;
261 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700262 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700264 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600265 return spv::Dim2D;
266 }
267}
268
269// Translate glslang type to SPIR-V precision decorations.
270spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
271{
272 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700273 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600274 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600275 default:
276 return spv::NoPrecision;
277 }
278}
279
280// Translate glslang type to SPIR-V block decorations.
281spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
282{
283 if (type.getBasicType() == glslang::EbtBlock) {
284 switch (type.getQualifier().storage) {
285 case glslang::EvqUniform: return spv::DecorationBlock;
286 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
287 case glslang::EvqVaryingIn: return spv::DecorationBlock;
288 case glslang::EvqVaryingOut: return spv::DecorationBlock;
289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 break;
292 }
293 }
294
295 return (spv::Decoration)spv::BadValue;
296}
297
Rex Xu1da878f2016-02-21 20:59:01 +0800298// Translate glslang type to SPIR-V memory decorations.
299void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
300{
301 if (qualifier.coherent)
302 memory.push_back(spv::DecorationCoherent);
303 if (qualifier.volatil)
304 memory.push_back(spv::DecorationVolatile);
305 if (qualifier.restrict)
306 memory.push_back(spv::DecorationRestrict);
307 if (qualifier.readonly)
308 memory.push_back(spv::DecorationNonWritable);
309 if (qualifier.writeonly)
310 memory.push_back(spv::DecorationNonReadable);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700314spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600315{
316 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700317 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600318 case glslang::ElmRowMajor:
319 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600321 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 default:
323 // opaque layouts don't need a majorness
324 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600325 }
326 } else {
327 switch (type.getBasicType()) {
328 default:
329 return (spv::Decoration)spv::BadValue;
330 break;
331 case glslang::EbtBlock:
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform:
334 case glslang::EvqBuffer:
335 switch (type.getQualifier().layoutPacking) {
336 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
338 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600339 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 }
341 case glslang::EvqVaryingIn:
342 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700343 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return (spv::Decoration)spv::BadValue;
345 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600347 return (spv::Decoration)spv::BadValue;
348 }
349 }
350 }
351}
352
353// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700354// Returns spv::Decoration(spv::BadValue) when no decoration
355// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700356spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600357{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700358 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700359 // Smooth decoration doesn't exist in SPIR-V 1.0
360 return (spv::Decoration)spv::BadValue;
361 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700362 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700363 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700364 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600365 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700370 else if (qualifier.sample) {
371 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600372 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700373 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600374 return (spv::Decoration)spv::BadValue;
375}
376
John Kessenich92187592016-02-01 13:45:25 -0700377// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700378spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600379{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationInvariant;
382 else
383 return (spv::Decoration)spv::BadValue;
384}
385
386// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700387spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600388{
389 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700390 case glslang::EbvPointSize:
391 switch (glslangIntermediate->getStage()) {
392 case EShLangGeometry:
393 builder.addCapability(spv::CapabilityGeometryPointSize);
394 break;
395 case EShLangTessControl:
396 case EShLangTessEvaluation:
397 builder.addCapability(spv::CapabilityTessellationPointSize);
398 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100399 default:
400 break;
John Kessenich92187592016-02-01 13:45:25 -0700401 }
402 return spv::BuiltInPointSize;
403
404 case glslang::EbvClipDistance:
405 builder.addCapability(spv::CapabilityClipDistance);
406 return spv::BuiltInClipDistance;
407
408 case glslang::EbvCullDistance:
409 builder.addCapability(spv::CapabilityCullDistance);
410 return spv::BuiltInCullDistance;
411
412 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500413 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700414 return spv::BuiltInViewportIndex;
415
John Kessenich5e801132016-02-15 11:09:46 -0700416 case glslang::EbvSampleId:
417 builder.addCapability(spv::CapabilitySampleRateShading);
418 return spv::BuiltInSampleId;
419
420 case glslang::EbvSamplePosition:
421 builder.addCapability(spv::CapabilitySampleRateShading);
422 return spv::BuiltInSamplePosition;
423
424 case glslang::EbvSampleMask:
425 builder.addCapability(spv::CapabilitySampleRateShading);
426 return spv::BuiltInSampleMask;
427
John Kessenich140f3df2015-06-26 16:58:36 -0600428 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600429 case glslang::EbvVertexId: return spv::BuiltInVertexId;
430 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700431 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
432 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600433 case glslang::EbvBaseVertex:
434 case glslang::EbvBaseInstance:
435 case glslang::EbvDrawId:
436 // TODO: Add SPIR-V builtin ID.
437 spv::MissingFunctionality("Draw parameters");
438 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600439 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
440 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
441 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600442 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
443 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
444 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
445 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
446 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
447 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
448 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600449 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
450 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
451 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
452 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
453 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
454 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
455 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
456 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
457 default: return (spv::BuiltIn)spv::BadValue;
458 }
459}
460
Rex Xufc618912015-09-09 16:42:49 +0800461// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700462spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800463{
464 assert(type.getBasicType() == glslang::EbtSampler);
465
John Kessenich5d0fa972016-02-15 11:57:00 -0700466 // Check for capabilities
467 switch (type.getQualifier().layoutFormat) {
468 case glslang::ElfRg32f:
469 case glslang::ElfRg16f:
470 case glslang::ElfR11fG11fB10f:
471 case glslang::ElfR16f:
472 case glslang::ElfRgba16:
473 case glslang::ElfRgb10A2:
474 case glslang::ElfRg16:
475 case glslang::ElfRg8:
476 case glslang::ElfR16:
477 case glslang::ElfR8:
478 case glslang::ElfRgba16Snorm:
479 case glslang::ElfRg16Snorm:
480 case glslang::ElfRg8Snorm:
481 case glslang::ElfR16Snorm:
482 case glslang::ElfR8Snorm:
483
484 case glslang::ElfRg32i:
485 case glslang::ElfRg16i:
486 case glslang::ElfRg8i:
487 case glslang::ElfR16i:
488 case glslang::ElfR8i:
489
490 case glslang::ElfRgb10a2ui:
491 case glslang::ElfRg32ui:
492 case glslang::ElfRg16ui:
493 case glslang::ElfRg8ui:
494 case glslang::ElfR16ui:
495 case glslang::ElfR8ui:
496 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
497 break;
498
499 default:
500 break;
501 }
502
503 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800504 switch (type.getQualifier().layoutFormat) {
505 case glslang::ElfNone: return spv::ImageFormatUnknown;
506 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
507 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
508 case glslang::ElfR32f: return spv::ImageFormatR32f;
509 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
510 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
511 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
512 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
513 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
514 case glslang::ElfR16f: return spv::ImageFormatR16f;
515 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
516 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
517 case glslang::ElfRg16: return spv::ImageFormatRg16;
518 case glslang::ElfRg8: return spv::ImageFormatRg8;
519 case glslang::ElfR16: return spv::ImageFormatR16;
520 case glslang::ElfR8: return spv::ImageFormatR8;
521 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
522 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
523 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
524 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
525 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
526 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
527 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
528 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
529 case glslang::ElfR32i: return spv::ImageFormatR32i;
530 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
531 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
532 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
533 case glslang::ElfR16i: return spv::ImageFormatR16i;
534 case glslang::ElfR8i: return spv::ImageFormatR8i;
535 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
536 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
537 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
538 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
539 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
540 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
541 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
542 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
543 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
544 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
545 default: return (spv::ImageFormat)spv::BadValue;
546 }
547}
548
John Kessenich6c292d32016-02-15 20:58:50 -0700549// Return whether or not the given type is something that should be tied to a
550// descriptor set.
551bool IsDescriptorResource(const glslang::TType& type)
552{
John Kessenichf7497e22016-03-08 21:36:22 -0700553 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700554 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700555 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700556
557 // non block...
558 // basically samplerXXX/subpass/sampler/texture are all included
559 // if they are the global-scope-class, not the function parameter
560 // (or local, if they ever exist) class.
561 if (type.getBasicType() == glslang::EbtSampler)
562 return type.getQualifier().isUniformOrBuffer();
563
564 // None of the above.
565 return false;
566}
567
John Kesseniche0b6cad2015-12-24 10:30:13 -0700568void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
569{
570 if (child.layoutMatrix == glslang::ElmNone)
571 child.layoutMatrix = parent.layoutMatrix;
572
573 if (parent.invariant)
574 child.invariant = true;
575 if (parent.nopersp)
576 child.nopersp = true;
577 if (parent.flat)
578 child.flat = true;
579 if (parent.centroid)
580 child.centroid = true;
581 if (parent.patch)
582 child.patch = true;
583 if (parent.sample)
584 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800585 if (parent.coherent)
586 child.coherent = true;
587 if (parent.volatil)
588 child.volatil = true;
589 if (parent.restrict)
590 child.restrict = true;
591 if (parent.readonly)
592 child.readonly = true;
593 if (parent.writeonly)
594 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700595}
596
597bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
598{
John Kessenich7b9fa252016-01-21 18:56:57 -0700599 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700600 // - struct members can inherit from a struct declaration
601 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
602 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700603 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700604}
605
John Kessenich140f3df2015-06-26 16:58:36 -0600606//
607// Implement the TGlslangToSpvTraverser class.
608//
609
610TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
611 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700612 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600613 inMain(false), mainTerminated(false), linkageOnly(false),
614 glslangIntermediate(glslangIntermediate)
615{
616 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
617
618 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700619 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600620 stdBuiltins = builder.import("GLSL.std.450");
621 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700622 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
623 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600624
625 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600626 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
627 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600628 builder.addSourceExtension(it->c_str());
629
630 // Add the top-level modes for this shader.
631
John Kessenich92187592016-02-01 13:45:25 -0700632 if (glslangIntermediate->getXfbMode()) {
633 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600634 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700635 }
John Kessenich140f3df2015-06-26 16:58:36 -0600636
637 unsigned int mode;
638 switch (glslangIntermediate->getStage()) {
639 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600640 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600641 break;
642
643 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600644 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600645 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
646 break;
647
648 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600649 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600650 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700651 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
652 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
653 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600654 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600655 }
656 if (mode != spv::BadValue)
657 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
658
John Kesseniche6903322015-10-13 16:29:02 -0600659 switch (glslangIntermediate->getVertexSpacing()) {
660 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
661 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
662 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
663 default: mode = spv::BadValue; break;
664 }
665 if (mode != spv::BadValue)
666 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
667
668 switch (glslangIntermediate->getVertexOrder()) {
669 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
670 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
671 default: mode = spv::BadValue; break;
672 }
673 if (mode != spv::BadValue)
674 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
675
676 if (glslangIntermediate->getPointMode())
677 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600678 break;
679
680 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600681 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600682 switch (glslangIntermediate->getInputPrimitive()) {
683 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
684 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
685 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700686 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600687 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
688 default: mode = spv::BadValue; break;
689 }
690 if (mode != spv::BadValue)
691 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600692
John Kessenich140f3df2015-06-26 16:58:36 -0600693 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
694
695 switch (glslangIntermediate->getOutputPrimitive()) {
696 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
697 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
698 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
699 default: mode = spv::BadValue; break;
700 }
701 if (mode != spv::BadValue)
702 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
703 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
704 break;
705
706 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600707 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600708 if (glslangIntermediate->getPixelCenterInteger())
709 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600710
John Kessenich140f3df2015-06-26 16:58:36 -0600711 if (glslangIntermediate->getOriginUpperLeft())
712 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600713 else
714 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600715
716 if (glslangIntermediate->getEarlyFragmentTests())
717 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
718
719 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600720 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
721 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
722 default: mode = spv::BadValue; break;
723 }
724 if (mode != spv::BadValue)
725 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
726
727 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
728 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600729 break;
730
731 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600732 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600733 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
734 glslangIntermediate->getLocalSize(1),
735 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600736 break;
737
738 default:
739 break;
740 }
741
742}
743
John Kessenich7ba63412015-12-20 17:37:07 -0700744// Finish everything and dump
745void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
746{
747 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100748 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
749 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700750
qiningda397332016-03-09 19:54:03 -0500751 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700752 builder.dump(out);
753}
754
John Kessenich140f3df2015-06-26 16:58:36 -0600755TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
756{
757 if (! mainTerminated) {
758 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
759 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600760 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600761 }
762}
763
764//
765// Implement the traversal functions.
766//
767// Return true from interior nodes to have the external traversal
768// continue on to children. Return false if children were
769// already processed.
770//
771
772//
773// Symbols can turn into
774// - uniform/input reads
775// - output writes
776// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
777// - something simple that degenerates into the last bullet
778//
779void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
780{
qining75d1d802016-04-06 14:42:01 -0400781 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
782 if (symbol->getType().getQualifier().isSpecConstant())
783 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
784
John Kessenich140f3df2015-06-26 16:58:36 -0600785 // getSymbolId() will set up all the IO decorations on the first call.
786 // Formal function parameters were mapped during makeFunctions().
787 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700788
789 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
790 if (builder.isPointer(id)) {
791 spv::StorageClass sc = builder.getStorageClass(id);
792 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
793 iOSet.insert(id);
794 }
795
796 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700797 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600798 // Prepare to generate code for the access
799
800 // L-value chains will be computed left to right. We're on the symbol now,
801 // which is the left-most part of the access chain, so now is "clear" time,
802 // followed by setting the base.
803 builder.clearAccessChain();
804
805 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700806 // except for
807 // A) "const in" arguments to a function, which are an intermediate object.
808 // See comments in handleUserFunctionCall().
809 // B) Specialization constants (normal constant don't even come in as a variable),
810 // These are also pure R-values.
811 glslang::TQualifier qualifier = symbol->getQualifier();
812 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
813 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600814 builder.setAccessChainRValue(id);
815 else
816 builder.setAccessChainLValue(id);
817 }
818}
819
820bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
821{
qining40887662016-04-03 22:20:42 -0400822 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
823 if (node->getType().getQualifier().isSpecConstant())
824 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
825
John Kessenich140f3df2015-06-26 16:58:36 -0600826 // First, handle special cases
827 switch (node->getOp()) {
828 case glslang::EOpAssign:
829 case glslang::EOpAddAssign:
830 case glslang::EOpSubAssign:
831 case glslang::EOpMulAssign:
832 case glslang::EOpVectorTimesMatrixAssign:
833 case glslang::EOpVectorTimesScalarAssign:
834 case glslang::EOpMatrixTimesScalarAssign:
835 case glslang::EOpMatrixTimesMatrixAssign:
836 case glslang::EOpDivAssign:
837 case glslang::EOpModAssign:
838 case glslang::EOpAndAssign:
839 case glslang::EOpInclusiveOrAssign:
840 case glslang::EOpExclusiveOrAssign:
841 case glslang::EOpLeftShiftAssign:
842 case glslang::EOpRightShiftAssign:
843 // A bin-op assign "a += b" means the same thing as "a = a + b"
844 // where a is evaluated before b. For a simple assignment, GLSL
845 // says to evaluate the left before the right. So, always, left
846 // node then right node.
847 {
848 // get the left l-value, save it away
849 builder.clearAccessChain();
850 node->getLeft()->traverse(this);
851 spv::Builder::AccessChain lValue = builder.getAccessChain();
852
853 // evaluate the right
854 builder.clearAccessChain();
855 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700856 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600857
858 if (node->getOp() != glslang::EOpAssign) {
859 // the left is also an r-value
860 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700861 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600862
863 // do the operation
864 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
865 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
866 node->getType().getBasicType());
867
868 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700869 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600870 }
871
872 // store the result
873 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800874 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600875
876 // assignments are expressions having an rValue after they are evaluated...
877 builder.clearAccessChain();
878 builder.setAccessChainRValue(rValue);
879 }
880 return false;
881 case glslang::EOpIndexDirect:
882 case glslang::EOpIndexDirectStruct:
883 {
884 // Get the left part of the access chain.
885 node->getLeft()->traverse(this);
886
887 // Add the next element in the chain
888
John Kessenich55e7d112015-11-15 21:33:39 -0700889 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600890 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
891 // This may be, e.g., an anonymous block-member selection, which generally need
892 // index remapping due to hidden members in anonymous blocks.
893 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700894 assert(remapper.size() > 0);
895 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600896 }
897
898 if (! node->getLeft()->getType().isArray() &&
899 node->getLeft()->getType().isVector() &&
900 node->getOp() == glslang::EOpIndexDirect) {
901 // This is essentially a hard-coded vector swizzle of size 1,
902 // so short circuit the access-chain stuff with a swizzle.
903 std::vector<unsigned> swizzle;
904 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600905 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600906 } else {
907 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600908 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600909 }
910 }
911 return false;
912 case glslang::EOpIndexIndirect:
913 {
914 // Structure or array or vector indirection.
915 // Will use native SPIR-V access-chain for struct and array indirection;
916 // matrices are arrays of vectors, so will also work for a matrix.
917 // Will use the access chain's 'component' for variable index into a vector.
918
919 // This adapter is building access chains left to right.
920 // Set up the access chain to the left.
921 node->getLeft()->traverse(this);
922
923 // save it so that computing the right side doesn't trash it
924 spv::Builder::AccessChain partial = builder.getAccessChain();
925
926 // compute the next index in the chain
927 builder.clearAccessChain();
928 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700929 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600930
931 // restore the saved access chain
932 builder.setAccessChain(partial);
933
934 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600935 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600936 else
John Kessenichfa668da2015-09-13 14:46:30 -0600937 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600938 }
939 return false;
940 case glslang::EOpVectorSwizzle:
941 {
942 node->getLeft()->traverse(this);
943 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
944 std::vector<unsigned> swizzle;
945 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
946 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600947 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600948 }
949 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600950 case glslang::EOpLogicalOr:
951 case glslang::EOpLogicalAnd:
952 {
953
954 // These may require short circuiting, but can sometimes be done as straight
955 // binary operations. The right operand must be short circuited if it has
956 // side effects, and should probably be if it is complex.
957 if (isTrivial(node->getRight()->getAsTyped()))
958 break; // handle below as a normal binary operation
959 // otherwise, we need to do dynamic short circuiting on the right operand
960 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
961 builder.clearAccessChain();
962 builder.setAccessChainRValue(result);
963 }
964 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600965 default:
966 break;
967 }
968
969 // Assume generic binary op...
970
John Kessenich32cfd492016-02-02 12:37:46 -0700971 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600972 builder.clearAccessChain();
973 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700974 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600975
John Kessenich32cfd492016-02-02 12:37:46 -0700976 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600977 builder.clearAccessChain();
978 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700979 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600980
John Kessenich32cfd492016-02-02 12:37:46 -0700981 // get result
982 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
983 convertGlslangToSpvType(node->getType()), left, right,
984 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600985
John Kessenich50e57562015-12-21 21:21:11 -0700986 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600987 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700988 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700989 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600990 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600991 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600992 return false;
993 }
John Kessenich140f3df2015-06-26 16:58:36 -0600994}
995
996bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
997{
qining40887662016-04-03 22:20:42 -0400998 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
999 if (node->getType().getQualifier().isSpecConstant())
1000 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1001
John Kessenichfc51d282015-08-19 13:34:18 -06001002 spv::Id result = spv::NoResult;
1003
1004 // try texturing first
1005 result = createImageTextureFunctionCall(node);
1006 if (result != spv::NoResult) {
1007 builder.clearAccessChain();
1008 builder.setAccessChainRValue(result);
1009
1010 return false; // done with this node
1011 }
1012
1013 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001014
1015 if (node->getOp() == glslang::EOpArrayLength) {
1016 // Quite special; won't want to evaluate the operand.
1017
1018 // Normal .length() would have been constant folded by the front-end.
1019 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001020 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001021 assert(node->getOperand()->getType().isRuntimeSizedArray());
1022 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1023 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001024 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1025 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001026
1027 builder.clearAccessChain();
1028 builder.setAccessChainRValue(length);
1029
1030 return false;
1031 }
1032
John Kessenichfc51d282015-08-19 13:34:18 -06001033 // Start by evaluating the operand
1034
John Kessenich140f3df2015-06-26 16:58:36 -06001035 builder.clearAccessChain();
1036 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001037
Rex Xufc618912015-09-09 16:42:49 +08001038 spv::Id operand = spv::NoResult;
1039
1040 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1041 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001042 node->getOp() == glslang::EOpAtomicCounter ||
1043 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001044 operand = builder.accessChainGetLValue(); // Special case l-value operands
1045 else
John Kessenich32cfd492016-02-02 12:37:46 -07001046 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001047
1048 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1049
1050 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001051 if (! result)
1052 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001053
1054 // if not, then possibly an operation
1055 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001056 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001057
1058 if (result) {
1059 builder.clearAccessChain();
1060 builder.setAccessChainRValue(result);
1061
1062 return false; // done with this node
1063 }
1064
1065 // it must be a special case, check...
1066 switch (node->getOp()) {
1067 case glslang::EOpPostIncrement:
1068 case glslang::EOpPostDecrement:
1069 case glslang::EOpPreIncrement:
1070 case glslang::EOpPreDecrement:
1071 {
1072 // we need the integer value "1" or the floating point "1.0" to add/subtract
1073 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1074 builder.makeFloatConstant(1.0F) :
1075 builder.makeIntConstant(1);
1076 glslang::TOperator op;
1077 if (node->getOp() == glslang::EOpPreIncrement ||
1078 node->getOp() == glslang::EOpPostIncrement)
1079 op = glslang::EOpAdd;
1080 else
1081 op = glslang::EOpSub;
1082
1083 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1084 convertGlslangToSpvType(node->getType()), operand, one,
1085 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001086 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001087
1088 // The result of operation is always stored, but conditionally the
1089 // consumed result. The consumed result is always an r-value.
1090 builder.accessChainStore(result);
1091 builder.clearAccessChain();
1092 if (node->getOp() == glslang::EOpPreIncrement ||
1093 node->getOp() == glslang::EOpPreDecrement)
1094 builder.setAccessChainRValue(result);
1095 else
1096 builder.setAccessChainRValue(operand);
1097 }
1098
1099 return false;
1100
1101 case glslang::EOpEmitStreamVertex:
1102 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1103 return false;
1104 case glslang::EOpEndStreamPrimitive:
1105 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1106 return false;
1107
1108 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001109 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001110 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001111 }
John Kessenich140f3df2015-06-26 16:58:36 -06001112}
1113
1114bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1115{
John Kessenichfc51d282015-08-19 13:34:18 -06001116 spv::Id result = spv::NoResult;
1117
1118 // try texturing
1119 result = createImageTextureFunctionCall(node);
1120 if (result != spv::NoResult) {
1121 builder.clearAccessChain();
1122 builder.setAccessChainRValue(result);
1123
1124 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001125 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001126 // "imageStore" is a special case, which has no result
1127 return false;
1128 }
John Kessenichfc51d282015-08-19 13:34:18 -06001129
John Kessenich140f3df2015-06-26 16:58:36 -06001130 glslang::TOperator binOp = glslang::EOpNull;
1131 bool reduceComparison = true;
1132 bool isMatrix = false;
1133 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001134 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001135
1136 assert(node->getOp());
1137
1138 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1139
1140 switch (node->getOp()) {
1141 case glslang::EOpSequence:
1142 {
1143 if (preVisit)
1144 ++sequenceDepth;
1145 else
1146 --sequenceDepth;
1147
1148 if (sequenceDepth == 1) {
1149 // If this is the parent node of all the functions, we want to see them
1150 // early, so all call points have actual SPIR-V functions to reference.
1151 // In all cases, still let the traverser visit the children for us.
1152 makeFunctions(node->getAsAggregate()->getSequence());
1153
1154 // Also, we want all globals initializers to go into the entry of main(), before
1155 // anything else gets there, so visit out of order, doing them all now.
1156 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1157
1158 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1159 // so do them manually.
1160 visitFunctions(node->getAsAggregate()->getSequence());
1161
1162 return false;
1163 }
1164
1165 return true;
1166 }
1167 case glslang::EOpLinkerObjects:
1168 {
1169 if (visit == glslang::EvPreVisit)
1170 linkageOnly = true;
1171 else
1172 linkageOnly = false;
1173
1174 return true;
1175 }
1176 case glslang::EOpComma:
1177 {
1178 // processing from left to right naturally leaves the right-most
1179 // lying around in the access chain
1180 glslang::TIntermSequence& glslangOperands = node->getSequence();
1181 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1182 glslangOperands[i]->traverse(this);
1183
1184 return false;
1185 }
1186 case glslang::EOpFunction:
1187 if (visit == glslang::EvPreVisit) {
1188 if (isShaderEntrypoint(node)) {
1189 inMain = true;
1190 builder.setBuildPoint(shaderEntry->getLastBlock());
1191 } else {
1192 handleFunctionEntry(node);
1193 }
1194 } else {
1195 if (inMain)
1196 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001197 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001198 inMain = false;
1199 }
1200
1201 return true;
1202 case glslang::EOpParameters:
1203 // Parameters will have been consumed by EOpFunction processing, but not
1204 // the body, so we still visited the function node's children, making this
1205 // child redundant.
1206 return false;
1207 case glslang::EOpFunctionCall:
1208 {
1209 if (node->isUserDefined())
1210 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001211 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1212 if (result) {
1213 builder.clearAccessChain();
1214 builder.setAccessChainRValue(result);
1215 } else
1216 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001217
1218 return false;
1219 }
1220 case glslang::EOpConstructMat2x2:
1221 case glslang::EOpConstructMat2x3:
1222 case glslang::EOpConstructMat2x4:
1223 case glslang::EOpConstructMat3x2:
1224 case glslang::EOpConstructMat3x3:
1225 case glslang::EOpConstructMat3x4:
1226 case glslang::EOpConstructMat4x2:
1227 case glslang::EOpConstructMat4x3:
1228 case glslang::EOpConstructMat4x4:
1229 case glslang::EOpConstructDMat2x2:
1230 case glslang::EOpConstructDMat2x3:
1231 case glslang::EOpConstructDMat2x4:
1232 case glslang::EOpConstructDMat3x2:
1233 case glslang::EOpConstructDMat3x3:
1234 case glslang::EOpConstructDMat3x4:
1235 case glslang::EOpConstructDMat4x2:
1236 case glslang::EOpConstructDMat4x3:
1237 case glslang::EOpConstructDMat4x4:
1238 isMatrix = true;
1239 // fall through
1240 case glslang::EOpConstructFloat:
1241 case glslang::EOpConstructVec2:
1242 case glslang::EOpConstructVec3:
1243 case glslang::EOpConstructVec4:
1244 case glslang::EOpConstructDouble:
1245 case glslang::EOpConstructDVec2:
1246 case glslang::EOpConstructDVec3:
1247 case glslang::EOpConstructDVec4:
1248 case glslang::EOpConstructBool:
1249 case glslang::EOpConstructBVec2:
1250 case glslang::EOpConstructBVec3:
1251 case glslang::EOpConstructBVec4:
1252 case glslang::EOpConstructInt:
1253 case glslang::EOpConstructIVec2:
1254 case glslang::EOpConstructIVec3:
1255 case glslang::EOpConstructIVec4:
1256 case glslang::EOpConstructUint:
1257 case glslang::EOpConstructUVec2:
1258 case glslang::EOpConstructUVec3:
1259 case glslang::EOpConstructUVec4:
1260 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001261 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001262 {
1263 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001264 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001265 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1266 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001267 if (node->getOp() == glslang::EOpConstructTextureSampler)
1268 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1269 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001270 std::vector<spv::Id> constituents;
1271 for (int c = 0; c < (int)arguments.size(); ++c)
1272 constituents.push_back(arguments[c]);
1273 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001274 } else if (isMatrix)
1275 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1276 else
1277 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001278
1279 builder.clearAccessChain();
1280 builder.setAccessChainRValue(constructed);
1281
1282 return false;
1283 }
1284
1285 // These six are component-wise compares with component-wise results.
1286 // Forward on to createBinaryOperation(), requesting a vector result.
1287 case glslang::EOpLessThan:
1288 case glslang::EOpGreaterThan:
1289 case glslang::EOpLessThanEqual:
1290 case glslang::EOpGreaterThanEqual:
1291 case glslang::EOpVectorEqual:
1292 case glslang::EOpVectorNotEqual:
1293 {
1294 // Map the operation to a binary
1295 binOp = node->getOp();
1296 reduceComparison = false;
1297 switch (node->getOp()) {
1298 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1299 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1300 default: binOp = node->getOp(); break;
1301 }
1302
1303 break;
1304 }
1305 case glslang::EOpMul:
1306 // compontent-wise matrix multiply
1307 binOp = glslang::EOpMul;
1308 break;
1309 case glslang::EOpOuterProduct:
1310 // two vectors multiplied to make a matrix
1311 binOp = glslang::EOpOuterProduct;
1312 break;
1313 case glslang::EOpDot:
1314 {
1315 // for scalar dot product, use multiply
1316 glslang::TIntermSequence& glslangOperands = node->getSequence();
1317 if (! glslangOperands[0]->getAsTyped()->isVector())
1318 binOp = glslang::EOpMul;
1319 break;
1320 }
1321 case glslang::EOpMod:
1322 // when an aggregate, this is the floating-point mod built-in function,
1323 // which can be emitted by the one in createBinaryOperation()
1324 binOp = glslang::EOpMod;
1325 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001326 case glslang::EOpEmitVertex:
1327 case glslang::EOpEndPrimitive:
1328 case glslang::EOpBarrier:
1329 case glslang::EOpMemoryBarrier:
1330 case glslang::EOpMemoryBarrierAtomicCounter:
1331 case glslang::EOpMemoryBarrierBuffer:
1332 case glslang::EOpMemoryBarrierImage:
1333 case glslang::EOpMemoryBarrierShared:
1334 case glslang::EOpGroupMemoryBarrier:
1335 noReturnValue = true;
1336 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1337 break;
1338
John Kessenich426394d2015-07-23 10:22:48 -06001339 case glslang::EOpAtomicAdd:
1340 case glslang::EOpAtomicMin:
1341 case glslang::EOpAtomicMax:
1342 case glslang::EOpAtomicAnd:
1343 case glslang::EOpAtomicOr:
1344 case glslang::EOpAtomicXor:
1345 case glslang::EOpAtomicExchange:
1346 case glslang::EOpAtomicCompSwap:
1347 atomic = true;
1348 break;
1349
John Kessenich140f3df2015-06-26 16:58:36 -06001350 default:
1351 break;
1352 }
1353
1354 //
1355 // See if it maps to a regular operation.
1356 //
John Kessenich140f3df2015-06-26 16:58:36 -06001357 if (binOp != glslang::EOpNull) {
1358 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1359 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1360 assert(left && right);
1361
1362 builder.clearAccessChain();
1363 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001364 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001365
1366 builder.clearAccessChain();
1367 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001368 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001369
1370 result = createBinaryOperation(binOp, precision,
1371 convertGlslangToSpvType(node->getType()), leftId, rightId,
1372 left->getType().getBasicType(), reduceComparison);
1373
1374 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001375 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001376 builder.clearAccessChain();
1377 builder.setAccessChainRValue(result);
1378
1379 return false;
1380 }
1381
John Kessenich426394d2015-07-23 10:22:48 -06001382 //
1383 // Create the list of operands.
1384 //
John Kessenich140f3df2015-06-26 16:58:36 -06001385 glslang::TIntermSequence& glslangOperands = node->getSequence();
1386 std::vector<spv::Id> operands;
1387 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1388 builder.clearAccessChain();
1389 glslangOperands[arg]->traverse(this);
1390
1391 // special case l-value operands; there are just a few
1392 bool lvalue = false;
1393 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001394 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001395 case glslang::EOpModf:
1396 if (arg == 1)
1397 lvalue = true;
1398 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001399 case glslang::EOpInterpolateAtSample:
1400 case glslang::EOpInterpolateAtOffset:
1401 if (arg == 0)
1402 lvalue = true;
1403 break;
Rex Xud4782c12015-09-06 16:30:11 +08001404 case glslang::EOpAtomicAdd:
1405 case glslang::EOpAtomicMin:
1406 case glslang::EOpAtomicMax:
1407 case glslang::EOpAtomicAnd:
1408 case glslang::EOpAtomicOr:
1409 case glslang::EOpAtomicXor:
1410 case glslang::EOpAtomicExchange:
1411 case glslang::EOpAtomicCompSwap:
1412 if (arg == 0)
1413 lvalue = true;
1414 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001415 case glslang::EOpAddCarry:
1416 case glslang::EOpSubBorrow:
1417 if (arg == 2)
1418 lvalue = true;
1419 break;
1420 case glslang::EOpUMulExtended:
1421 case glslang::EOpIMulExtended:
1422 if (arg >= 2)
1423 lvalue = true;
1424 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001425 default:
1426 break;
1427 }
1428 if (lvalue)
1429 operands.push_back(builder.accessChainGetLValue());
1430 else
John Kessenich32cfd492016-02-02 12:37:46 -07001431 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001432 }
John Kessenich426394d2015-07-23 10:22:48 -06001433
1434 if (atomic) {
1435 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001436 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001437 } else {
1438 // Pass through to generic operations.
1439 switch (glslangOperands.size()) {
1440 case 0:
1441 result = createNoArgOperation(node->getOp());
1442 break;
1443 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001444 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001445 break;
1446 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001447 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001448 break;
1449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450 }
1451
1452 if (noReturnValue)
1453 return false;
1454
1455 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001456 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001457 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001458 } else {
1459 builder.clearAccessChain();
1460 builder.setAccessChainRValue(result);
1461 return false;
1462 }
1463}
1464
1465bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1466{
1467 // This path handles both if-then-else and ?:
1468 // The if-then-else has a node type of void, while
1469 // ?: has a non-void node type
1470 spv::Id result = 0;
1471 if (node->getBasicType() != glslang::EbtVoid) {
1472 // don't handle this as just on-the-fly temporaries, because there will be two names
1473 // and better to leave SSA to later passes
1474 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1475 }
1476
1477 // emit the condition before doing anything with selection
1478 node->getCondition()->traverse(this);
1479
1480 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001481 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001482
1483 if (node->getTrueBlock()) {
1484 // emit the "then" statement
1485 node->getTrueBlock()->traverse(this);
1486 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001487 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001488 }
1489
1490 if (node->getFalseBlock()) {
1491 ifBuilder.makeBeginElse();
1492 // emit the "else" statement
1493 node->getFalseBlock()->traverse(this);
1494 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001495 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001496 }
1497
1498 ifBuilder.makeEndIf();
1499
1500 if (result) {
1501 // GLSL only has r-values as the result of a :?, but
1502 // if we have an l-value, that can be more efficient if it will
1503 // become the base of a complex r-value expression, because the
1504 // next layer copies r-values into memory to use the access-chain mechanism
1505 builder.clearAccessChain();
1506 builder.setAccessChainLValue(result);
1507 }
1508
1509 return false;
1510}
1511
1512bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1513{
1514 // emit and get the condition before doing anything with switch
1515 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001516 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001517
1518 // browse the children to sort out code segments
1519 int defaultSegment = -1;
1520 std::vector<TIntermNode*> codeSegments;
1521 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1522 std::vector<int> caseValues;
1523 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1524 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1525 TIntermNode* child = *c;
1526 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001527 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001528 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001529 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001530 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1531 } else
1532 codeSegments.push_back(child);
1533 }
1534
1535 // handle the case where the last code segment is missing, due to no code
1536 // statements between the last case and the end of the switch statement
1537 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1538 (int)codeSegments.size() == defaultSegment)
1539 codeSegments.push_back(nullptr);
1540
1541 // make the switch statement
1542 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001543 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001544
1545 // emit all the code in the segments
1546 breakForLoop.push(false);
1547 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1548 builder.nextSwitchSegment(segmentBlocks, s);
1549 if (codeSegments[s])
1550 codeSegments[s]->traverse(this);
1551 else
1552 builder.addSwitchBreak();
1553 }
1554 breakForLoop.pop();
1555
1556 builder.endSwitch(segmentBlocks);
1557
1558 return false;
1559}
1560
1561void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1562{
1563 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001564 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001565
1566 builder.clearAccessChain();
1567 builder.setAccessChainRValue(constant);
1568}
1569
1570bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1571{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001572 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001573 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001574 // Spec requires back edges to target header blocks, and every header block
1575 // must dominate its merge block. Make a header block first to ensure these
1576 // conditions are met. By definition, it will contain OpLoopMerge, followed
1577 // by a block-ending branch. But we don't want to put any other body/test
1578 // instructions in it, since the body/test may have arbitrary instructions,
1579 // including merges of its own.
1580 builder.setBuildPoint(&blocks.head);
1581 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001582 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001583 spv::Block& test = builder.makeNewBlock();
1584 builder.createBranch(&test);
1585
1586 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001587 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001588 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001589 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001590 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1591
1592 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001593 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001594 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001595 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001596 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001597 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001598
1599 builder.setBuildPoint(&blocks.continue_target);
1600 if (node->getTerminal())
1601 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001602 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001603 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001604 builder.createBranch(&blocks.body);
1605
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001606 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001607 builder.setBuildPoint(&blocks.body);
1608 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001609 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001610 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001611 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001612
1613 builder.setBuildPoint(&blocks.continue_target);
1614 if (node->getTerminal())
1615 node->getTerminal()->traverse(this);
1616 if (node->getTest()) {
1617 node->getTest()->traverse(this);
1618 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001619 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001620 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001621 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001622 // TODO: unless there was a break/return/discard instruction
1623 // somewhere in the body, this is an infinite loop, so we should
1624 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001625 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001626 }
John Kessenich140f3df2015-06-26 16:58:36 -06001627 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001628 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001629 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001630 return false;
1631}
1632
1633bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1634{
1635 if (node->getExpression())
1636 node->getExpression()->traverse(this);
1637
1638 switch (node->getFlowOp()) {
1639 case glslang::EOpKill:
1640 builder.makeDiscard();
1641 break;
1642 case glslang::EOpBreak:
1643 if (breakForLoop.top())
1644 builder.createLoopExit();
1645 else
1646 builder.addSwitchBreak();
1647 break;
1648 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001649 builder.createLoopContinue();
1650 break;
1651 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001652 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001653 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001654 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001655 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001656
1657 builder.clearAccessChain();
1658 break;
1659
1660 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001661 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001662 break;
1663 }
1664
1665 return false;
1666}
1667
1668spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1669{
1670 // First, steer off constants, which are not SPIR-V variables, but
1671 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001672 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001673 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001674 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 }
1676
1677 // Now, handle actual variables
1678 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1679 spv::Id spvType = convertGlslangToSpvType(node->getType());
1680
1681 const char* name = node->getName().c_str();
1682 if (glslang::IsAnonymous(name))
1683 name = "";
1684
1685 return builder.createVariable(storageClass, spvType, name);
1686}
1687
1688// Return type Id of the sampled type.
1689spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1690{
1691 switch (sampler.type) {
1692 case glslang::EbtFloat: return builder.makeFloatType(32);
1693 case glslang::EbtInt: return builder.makeIntType(32);
1694 case glslang::EbtUint: return builder.makeUintType(32);
1695 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001696 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 return builder.makeFloatType(32);
1698 }
1699}
1700
John Kessenich3ac051e2015-12-20 11:29:16 -07001701// Convert from a glslang type to an SPV type, by calling into a
1702// recursive version of this function. This establishes the inherited
1703// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001704spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1705{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001706 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001707}
1708
1709// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001710// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001711spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001712{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001713 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001714
1715 switch (type.getBasicType()) {
1716 case glslang::EbtVoid:
1717 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001718 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001719 break;
1720 case glslang::EbtFloat:
1721 spvType = builder.makeFloatType(32);
1722 break;
1723 case glslang::EbtDouble:
1724 spvType = builder.makeFloatType(64);
1725 break;
1726 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001727 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1728 // a 32-bit int where non-0 means true.
1729 if (explicitLayout != glslang::ElpNone)
1730 spvType = builder.makeUintType(32);
1731 else
1732 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001733 break;
1734 case glslang::EbtInt:
1735 spvType = builder.makeIntType(32);
1736 break;
1737 case glslang::EbtUint:
1738 spvType = builder.makeUintType(32);
1739 break;
John Kessenich426394d2015-07-23 10:22:48 -06001740 case glslang::EbtAtomicUint:
1741 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1742 spvType = builder.makeUintType(32);
1743 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001744 case glslang::EbtSampler:
1745 {
1746 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001747 if (sampler.sampler) {
1748 // pure sampler
1749 spvType = builder.makeSamplerType();
1750 } else {
1751 // an image is present, make its type
1752 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1753 sampler.image ? 2 : 1, TranslateImageFormat(type));
1754 if (sampler.combined) {
1755 // already has both image and sampler, make the combined type
1756 spvType = builder.makeSampledImageType(spvType);
1757 }
John Kessenich55e7d112015-11-15 21:33:39 -07001758 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001759 }
John Kessenich140f3df2015-06-26 16:58:36 -06001760 break;
1761 case glslang::EbtStruct:
1762 case glslang::EbtBlock:
1763 {
1764 // If we've seen this struct type, return it
1765 const glslang::TTypeList* glslangStruct = type.getStruct();
1766 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001767
1768 // Try to share structs for different layouts, but not yet for other
1769 // kinds of qualification (primarily not yet including interpolant qualification).
1770 if (! HasNonLayoutQualifiers(qualifier))
1771 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1772 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001773 break;
1774
1775 // else, we haven't seen it...
1776
1777 // Create a vector of struct types for SPIR-V to consume
1778 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1779 if (type.getBasicType() == glslang::EbtBlock)
1780 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001781 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001782 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1783 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1784 if (glslangType.hiddenMember()) {
1785 ++memberDelta;
1786 if (type.getBasicType() == glslang::EbtBlock)
1787 memberRemapper[glslangStruct][i] = -1;
1788 } else {
1789 if (type.getBasicType() == glslang::EbtBlock)
1790 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001791 // modify just this child's view of the qualifier
1792 glslang::TQualifier subQualifier = glslangType.getQualifier();
1793 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001794
1795 // manually inherit location; it's more complex
1796 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1797 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1798 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001799 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001800
1801 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001802 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001803 }
1804 }
1805
1806 // Make the SPIR-V type
1807 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001808 if (! HasNonLayoutQualifiers(qualifier))
1809 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001810
1811 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001812 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001813 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001814 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1815 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1816 int member = i;
1817 if (type.getBasicType() == glslang::EbtBlock)
1818 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001819
John Kesseniche0b6cad2015-12-24 10:30:13 -07001820 // modify just this child's view of the qualifier
1821 glslang::TQualifier subQualifier = glslangType.getQualifier();
1822 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001823
John Kessenich140f3df2015-06-26 16:58:36 -06001824 // using -1 above to indicate a hidden member
1825 if (member >= 0) {
1826 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001827 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001828 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001829 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1830 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001831
Rex Xu1da878f2016-02-21 20:59:01 +08001832 if (qualifier.storage == glslang::EvqBuffer) {
1833 std::vector<spv::Decoration> memory;
1834 TranslateMemoryDecoration(subQualifier, memory);
1835 for (unsigned int i = 0; i < memory.size(); ++i)
1836 addMemberDecoration(spvType, member, memory[i]);
1837 }
1838
John Kessenich09677482016-02-19 12:21:50 -07001839 // compute location decoration; tricky based on whether inheritance is at play
1840 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1841 // probably move to the linker stage of the front end proper, and just have the
1842 // answer sitting already distributed throughout the individual member locations.
1843 int location = -1; // will only decorate if present or inherited
1844 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1845 location = subQualifier.layoutLocation;
1846 else if (qualifier.hasLocation()) // inheritance
1847 location = qualifier.layoutLocation + locationOffset;
1848 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001849 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001850 if (location >= 0)
1851 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1852
1853 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001854 if (glslangType.getQualifier().hasComponent())
1855 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1856 if (glslangType.getQualifier().hasXfbOffset())
1857 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001858 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001859 // figure out what to do with offset, which is accumulating
1860 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001861 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001862 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001863 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001864 offset = nextOffset;
1865 }
John Kessenich140f3df2015-06-26 16:58:36 -06001866
John Kessenichf85e8062015-12-19 13:57:10 -07001867 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001868 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001869
John Kessenich140f3df2015-06-26 16:58:36 -06001870 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001871 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1872 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001873 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875 }
1876
1877 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001878 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001879 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001880 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001881 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001882 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001883 }
John Kessenich140f3df2015-06-26 16:58:36 -06001884 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001885 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001886 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001887 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001888 if (type.getQualifier().hasXfbBuffer())
1889 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1890 }
1891 }
1892 break;
1893 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001894 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001895 break;
1896 }
1897
1898 if (type.isMatrix())
1899 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1900 else {
1901 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1902 if (type.getVectorSize() > 1)
1903 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1904 }
1905
1906 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001907 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1908
John Kessenichc9a80832015-09-12 12:17:44 -06001909 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001910 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001911 // We need to decorate array strides for types needing explicit layout, except blocks.
1912 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001913 // Use a dummy glslang type for querying internal strides of
1914 // arrays of arrays, but using just a one-dimensional array.
1915 glslang::TType simpleArrayType(type, 0); // deference type of the array
1916 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1917 simpleArrayType.getArraySizes().dereference();
1918
1919 // Will compute the higher-order strides here, rather than making a whole
1920 // pile of types and doing repetitive recursion on their contents.
1921 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1922 }
John Kessenichf8842e52016-01-04 19:22:56 -07001923
1924 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001925 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001926 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001927 if (stride > 0)
1928 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001929 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001930 }
1931 } else {
1932 // single-dimensional array, and don't yet have stride
1933
John Kessenichf8842e52016-01-04 19:22:56 -07001934 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001935 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1936 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001937 }
John Kessenich31ed4832015-09-09 17:51:38 -06001938
John Kessenichc9a80832015-09-12 12:17:44 -06001939 // Do the outer dimension, which might not be known for a runtime-sized array
1940 if (type.isRuntimeSizedArray()) {
1941 spvType = builder.makeRuntimeArray(spvType);
1942 } else {
1943 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001944 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001945 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001946 if (stride > 0)
1947 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001948 }
1949
1950 return spvType;
1951}
1952
John Kessenich6c292d32016-02-15 20:58:50 -07001953// Turn the expression forming the array size into an id.
1954// This is not quite trivial, because of specialization constants.
1955// Sometimes, a raw constant is turned into an Id, and sometimes
1956// a specialization constant expression is.
1957spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1958{
1959 // First, see if this is sized with a node, meaning a specialization constant:
1960 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1961 if (specNode != nullptr) {
1962 builder.clearAccessChain();
1963 specNode->traverse(this);
1964 return accessChainLoad(specNode->getAsTyped()->getType());
1965 }
1966
1967 // Otherwise, need a compile-time (front end) size, get it:
1968 int size = arraySizes.getDimSize(dim);
1969 assert(size > 0);
1970 return builder.makeUintConstant(size);
1971}
1972
John Kessenich103bef92016-02-08 21:38:15 -07001973// Wrap the builder's accessChainLoad to:
1974// - localize handling of RelaxedPrecision
1975// - use the SPIR-V inferred type instead of another conversion of the glslang type
1976// (avoids unnecessary work and possible type punning for structures)
1977// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001978spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1979{
John Kessenich103bef92016-02-08 21:38:15 -07001980 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1981 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1982
1983 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001984 if (type.getBasicType() == glslang::EbtBool) {
1985 if (builder.isScalarType(nominalTypeId)) {
1986 // Conversion for bool
1987 spv::Id boolType = builder.makeBoolType();
1988 if (nominalTypeId != boolType)
1989 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1990 } else if (builder.isVectorType(nominalTypeId)) {
1991 // Conversion for bvec
1992 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1993 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1994 if (nominalTypeId != bvecType)
1995 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1996 }
1997 }
John Kessenich103bef92016-02-08 21:38:15 -07001998
1999 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002000}
2001
Rex Xu27253232016-02-23 17:51:09 +08002002// Wrap the builder's accessChainStore to:
2003// - do conversion of concrete to abstract type
2004void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2005{
2006 // Need to convert to abstract types when necessary
2007 if (type.getBasicType() == glslang::EbtBool) {
2008 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2009
2010 if (builder.isScalarType(nominalTypeId)) {
2011 // Conversion for bool
2012 spv::Id boolType = builder.makeBoolType();
2013 if (nominalTypeId != boolType) {
2014 spv::Id zero = builder.makeUintConstant(0);
2015 spv::Id one = builder.makeUintConstant(1);
2016 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2017 }
2018 } else if (builder.isVectorType(nominalTypeId)) {
2019 // Conversion for bvec
2020 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2021 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2022 if (nominalTypeId != bvecType) {
2023 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2024 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2025 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2026 }
2027 }
2028 }
2029
2030 builder.accessChainStore(rvalue);
2031}
2032
John Kessenichf85e8062015-12-19 13:57:10 -07002033// Decide whether or not this type should be
2034// decorated with offsets and strides, and if so
2035// whether std140 or std430 rules should be applied.
2036glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002037{
John Kessenichf85e8062015-12-19 13:57:10 -07002038 // has to be a block
2039 if (type.getBasicType() != glslang::EbtBlock)
2040 return glslang::ElpNone;
2041
2042 // has to be a uniform or buffer block
2043 if (type.getQualifier().storage != glslang::EvqUniform &&
2044 type.getQualifier().storage != glslang::EvqBuffer)
2045 return glslang::ElpNone;
2046
2047 // return the layout to use
2048 switch (type.getQualifier().layoutPacking) {
2049 case glslang::ElpStd140:
2050 case glslang::ElpStd430:
2051 return type.getQualifier().layoutPacking;
2052 default:
2053 return glslang::ElpNone;
2054 }
John Kessenich31ed4832015-09-09 17:51:38 -06002055}
2056
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002057// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002058int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002059{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002060 int size;
John Kessenich49987892015-12-29 17:11:44 -07002061 int stride;
2062 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002063
2064 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002065}
2066
John Kessenich49987892015-12-29 17:11:44 -07002067// 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 -07002068// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002069int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002070{
John Kessenich49987892015-12-29 17:11:44 -07002071 glslang::TType elementType;
2072 elementType.shallowCopy(matrixType);
2073 elementType.clearArraySizes();
2074
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002075 int size;
John Kessenich49987892015-12-29 17:11:44 -07002076 int stride;
2077 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2078
2079 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002080}
2081
John Kessenich5e4b1242015-08-06 22:53:06 -06002082// Given a member type of a struct, realign the current offset for it, and compute
2083// the next (not yet aligned) offset for the next member, which will get aligned
2084// on the next call.
2085// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2086// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2087// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002088void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002089 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002090{
2091 // this will get a positive value when deemed necessary
2092 nextOffset = -1;
2093
John Kessenich5e4b1242015-08-06 22:53:06 -06002094 // override anything in currentOffset with user-set offset
2095 if (memberType.getQualifier().hasOffset())
2096 currentOffset = memberType.getQualifier().layoutOffset;
2097
2098 // It could be that current linker usage in glslang updated all the layoutOffset,
2099 // in which case the following code does not matter. But, that's not quite right
2100 // once cross-compilation unit GLSL validation is done, as the original user
2101 // settings are needed in layoutOffset, and then the following will come into play.
2102
John Kessenichf85e8062015-12-19 13:57:10 -07002103 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002104 if (! memberType.getQualifier().hasOffset())
2105 currentOffset = -1;
2106
2107 return;
2108 }
2109
John Kessenichf85e8062015-12-19 13:57:10 -07002110 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002111 if (currentOffset < 0)
2112 currentOffset = 0;
2113
2114 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2115 // but possibly not yet correctly aligned.
2116
2117 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002118 int dummyStride;
2119 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002120 glslang::RoundToPow2(currentOffset, memberAlignment);
2121 nextOffset = currentOffset + memberSize;
2122}
2123
John Kessenich140f3df2015-06-26 16:58:36 -06002124bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2125{
John Kessenich4d65ee32016-03-12 18:17:47 -07002126 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002127 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002128 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002129}
2130
2131// Make all the functions, skeletally, without actually visiting their bodies.
2132void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2133{
2134 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2135 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2136 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2137 continue;
2138
2139 // We're on a user function. Set up the basic interface for the function now,
2140 // so that it's available to call.
2141 // Translating the body will happen later.
2142 //
2143 // Typically (except for a "const in" parameter), an address will be passed to the
2144 // function. What it is an address of varies:
2145 //
2146 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2147 // so that write needs to be to a copy, hence the address of a copy works.
2148 //
2149 // - "const in" parameters can just be the r-value, as no writes need occur.
2150 //
2151 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2152 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2153
2154 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002155 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002156 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2157
2158 for (int p = 0; p < (int)parameters.size(); ++p) {
2159 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2160 spv::Id typeId = convertGlslangToSpvType(paramType);
2161 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2162 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2163 else
2164 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002165 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002166 paramTypes.push_back(typeId);
2167 }
2168
2169 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002170 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2171 convertGlslangToSpvType(glslFunction->getType()),
2172 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002173
2174 // Track function to emit/call later
2175 functionMap[glslFunction->getName().c_str()] = function;
2176
2177 // Set the parameter id's
2178 for (int p = 0; p < (int)parameters.size(); ++p) {
2179 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2180 // give a name too
2181 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2182 }
2183 }
2184}
2185
2186// Process all the initializers, while skipping the functions and link objects
2187void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2188{
2189 builder.setBuildPoint(shaderEntry->getLastBlock());
2190 for (int i = 0; i < (int)initializers.size(); ++i) {
2191 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2192 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2193
2194 // We're on a top-level node that's not a function. Treat as an initializer, whose
2195 // code goes into the beginning of main.
2196 initializer->traverse(this);
2197 }
2198 }
2199}
2200
2201// Process all the functions, while skipping initializers.
2202void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2203{
2204 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2205 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2206 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2207 node->traverse(this);
2208 }
2209}
2210
2211void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2212{
2213 // SPIR-V functions should already be in the functionMap from the prepass
2214 // that called makeFunctions().
2215 spv::Function* function = functionMap[node->getName().c_str()];
2216 spv::Block* functionBlock = function->getEntryBlock();
2217 builder.setBuildPoint(functionBlock);
2218}
2219
Rex Xu04db3f52015-09-16 11:44:02 +08002220void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002221{
Rex Xufc618912015-09-09 16:42:49 +08002222 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002223
2224 glslang::TSampler sampler = {};
2225 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002226 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002227 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2228 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2229 }
2230
John Kessenich140f3df2015-06-26 16:58:36 -06002231 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2232 builder.clearAccessChain();
2233 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002234
2235 // Special case l-value operands
2236 bool lvalue = false;
2237 switch (node.getOp()) {
2238 case glslang::EOpImageAtomicAdd:
2239 case glslang::EOpImageAtomicMin:
2240 case glslang::EOpImageAtomicMax:
2241 case glslang::EOpImageAtomicAnd:
2242 case glslang::EOpImageAtomicOr:
2243 case glslang::EOpImageAtomicXor:
2244 case glslang::EOpImageAtomicExchange:
2245 case glslang::EOpImageAtomicCompSwap:
2246 if (i == 0)
2247 lvalue = true;
2248 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002249 case glslang::EOpSparseImageLoad:
2250 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2251 lvalue = true;
2252 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002253 case glslang::EOpSparseTexture:
2254 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2255 lvalue = true;
2256 break;
2257 case glslang::EOpSparseTextureClamp:
2258 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2259 lvalue = true;
2260 break;
2261 case glslang::EOpSparseTextureLod:
2262 case glslang::EOpSparseTextureOffset:
2263 if (i == 3)
2264 lvalue = true;
2265 break;
2266 case glslang::EOpSparseTextureFetch:
2267 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2268 lvalue = true;
2269 break;
2270 case glslang::EOpSparseTextureFetchOffset:
2271 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2272 lvalue = true;
2273 break;
2274 case glslang::EOpSparseTextureLodOffset:
2275 case glslang::EOpSparseTextureGrad:
2276 case glslang::EOpSparseTextureOffsetClamp:
2277 if (i == 4)
2278 lvalue = true;
2279 break;
2280 case glslang::EOpSparseTextureGradOffset:
2281 case glslang::EOpSparseTextureGradClamp:
2282 if (i == 5)
2283 lvalue = true;
2284 break;
2285 case glslang::EOpSparseTextureGradOffsetClamp:
2286 if (i == 6)
2287 lvalue = true;
2288 break;
2289 case glslang::EOpSparseTextureGather:
2290 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2291 lvalue = true;
2292 break;
2293 case glslang::EOpSparseTextureGatherOffset:
2294 case glslang::EOpSparseTextureGatherOffsets:
2295 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2296 lvalue = true;
2297 break;
Rex Xufc618912015-09-09 16:42:49 +08002298 default:
2299 break;
2300 }
2301
Rex Xu6b86d492015-09-16 17:48:22 +08002302 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002303 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002304 else
John Kessenich32cfd492016-02-02 12:37:46 -07002305 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002306 }
2307}
2308
John Kessenichfc51d282015-08-19 13:34:18 -06002309void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002310{
John Kessenichfc51d282015-08-19 13:34:18 -06002311 builder.clearAccessChain();
2312 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002313 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002314}
John Kessenich140f3df2015-06-26 16:58:36 -06002315
John Kessenichfc51d282015-08-19 13:34:18 -06002316spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2317{
Rex Xufc618912015-09-09 16:42:49 +08002318 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002319 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002320 }
2321
John Kessenichfc51d282015-08-19 13:34:18 -06002322 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002323 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2324 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2325 std::vector<spv::Id> arguments;
2326 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002327 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002328 else
2329 translateArguments(*node->getAsUnaryNode(), arguments);
2330 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2331
2332 spv::Builder::TextureParameters params = { };
2333 params.sampler = arguments[0];
2334
Rex Xu04db3f52015-09-16 11:44:02 +08002335 glslang::TCrackedTextureOp cracked;
2336 node->crackTexture(sampler, cracked);
2337
John Kessenichfc51d282015-08-19 13:34:18 -06002338 // Check for queries
2339 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002340 // a sampled image needs to have the image extracted first
2341 if (builder.isSampledImage(params.sampler))
2342 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002343 switch (node->getOp()) {
2344 case glslang::EOpImageQuerySize:
2345 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002346 if (arguments.size() > 1) {
2347 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002348 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002349 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002350 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002351 case glslang::EOpImageQuerySamples:
2352 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002353 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002354 case glslang::EOpTextureQueryLod:
2355 params.coords = arguments[1];
2356 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2357 case glslang::EOpTextureQueryLevels:
2358 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002359 case glslang::EOpSparseTexelsResident:
2360 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002361 default:
2362 assert(0);
2363 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002364 }
John Kessenich140f3df2015-06-26 16:58:36 -06002365 }
2366
Rex Xufc618912015-09-09 16:42:49 +08002367 // Check for image functions other than queries
2368 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002369 std::vector<spv::Id> operands;
2370 auto opIt = arguments.begin();
2371 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002372
2373 // Handle subpass operations
2374 // TODO: GLSL should change to have the "MS" only on the type rather than the
2375 // built-in function.
2376 if (cracked.subpass) {
2377 // add on the (0,0) coordinate
2378 spv::Id zero = builder.makeIntConstant(0);
2379 std::vector<spv::Id> comps;
2380 comps.push_back(zero);
2381 comps.push_back(zero);
2382 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2383 if (sampler.ms) {
2384 operands.push_back(spv::ImageOperandsSampleMask);
2385 operands.push_back(*(opIt++));
2386 }
2387 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2388 }
2389
John Kessenich56bab042015-09-16 10:54:31 -06002390 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002391 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002392 if (sampler.ms) {
2393 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002394 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002395 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002396 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2397 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002398 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002399 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002400 if (sampler.ms) {
2401 operands.push_back(*(opIt + 1));
2402 operands.push_back(spv::ImageOperandsSampleMask);
2403 operands.push_back(*opIt);
2404 } else
2405 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002406 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002407 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2408 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002409 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002410 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2411 builder.addCapability(spv::CapabilitySparseResidency);
2412 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2413 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2414
2415 if (sampler.ms) {
2416 operands.push_back(spv::ImageOperandsSampleMask);
2417 operands.push_back(*opIt++);
2418 }
2419
2420 // Create the return type that was a special structure
2421 spv::Id texelOut = *opIt;
2422 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2423 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2424 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2425
2426 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2427
2428 // Decode the return type
2429 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2430 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002431 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002432 // Process image atomic operations
2433
2434 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2435 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002436 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002437
Rex Xufc618912015-09-09 16:42:49 +08002438 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002439 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002440
2441 std::vector<spv::Id> operands;
2442 operands.push_back(pointer);
2443 for (; opIt != arguments.end(); ++opIt)
2444 operands.push_back(*opIt);
2445
Rex Xu04db3f52015-09-16 11:44:02 +08002446 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002447 }
2448 }
2449
2450 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002451 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002452 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2453
John Kessenichfc51d282015-08-19 13:34:18 -06002454 // check for bias argument
2455 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002456 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002457 int nonBiasArgCount = 2;
2458 if (cracked.offset)
2459 ++nonBiasArgCount;
2460 if (cracked.grad)
2461 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002462 if (cracked.lodClamp)
2463 ++nonBiasArgCount;
2464 if (sparse)
2465 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002466
2467 if ((int)arguments.size() > nonBiasArgCount)
2468 bias = true;
2469 }
2470
John Kessenichfc51d282015-08-19 13:34:18 -06002471 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002472
John Kessenichfc51d282015-08-19 13:34:18 -06002473 params.coords = arguments[1];
2474 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002475 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002476
2477 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002478 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002479 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002480 ++extraArgs;
2481 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002482 params.Dref = arguments[2];
2483 ++extraArgs;
2484 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002485 std::vector<spv::Id> indexes;
2486 int comp;
2487 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002488 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002489 else
2490 comp = builder.getNumComponents(params.coords) - 1;
2491 indexes.push_back(comp);
2492 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2493 }
2494 if (cracked.lod) {
2495 params.lod = arguments[2];
2496 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002497 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2498 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2499 noImplicitLod = true;
2500 }
2501 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002502 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002503 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002504 }
2505 if (cracked.grad) {
2506 params.gradX = arguments[2 + extraArgs];
2507 params.gradY = arguments[3 + extraArgs];
2508 extraArgs += 2;
2509 }
John Kessenich55e7d112015-11-15 21:33:39 -07002510 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002511 params.offset = arguments[2 + extraArgs];
2512 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002513 } else if (cracked.offsets) {
2514 params.offsets = arguments[2 + extraArgs];
2515 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002516 }
Rex Xu48edadf2015-12-31 16:11:41 +08002517 if (cracked.lodClamp) {
2518 params.lodClamp = arguments[2 + extraArgs];
2519 ++extraArgs;
2520 }
2521 if (sparse) {
2522 params.texelOut = arguments[2 + extraArgs];
2523 ++extraArgs;
2524 }
John Kessenichfc51d282015-08-19 13:34:18 -06002525 if (bias) {
2526 params.bias = arguments[2 + extraArgs];
2527 ++extraArgs;
2528 }
John Kessenich55e7d112015-11-15 21:33:39 -07002529 if (cracked.gather && ! sampler.shadow) {
2530 // default component is 0, if missing, otherwise an argument
2531 if (2 + extraArgs < (int)arguments.size()) {
2532 params.comp = arguments[2 + extraArgs];
2533 ++extraArgs;
2534 } else {
2535 params.comp = builder.makeIntConstant(0);
2536 }
2537 }
John Kessenichfc51d282015-08-19 13:34:18 -06002538
John Kessenich019f08f2016-02-15 15:40:42 -07002539 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002540}
2541
2542spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2543{
2544 // Grab the function's pointer from the previously created function
2545 spv::Function* function = functionMap[node->getName().c_str()];
2546 if (! function)
2547 return 0;
2548
2549 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2550 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2551
2552 // See comments in makeFunctions() for details about the semantics for parameter passing.
2553 //
2554 // These imply we need a four step process:
2555 // 1. Evaluate the arguments
2556 // 2. Allocate and make copies of in, out, and inout arguments
2557 // 3. Make the call
2558 // 4. Copy back the results
2559
2560 // 1. Evaluate the arguments
2561 std::vector<spv::Builder::AccessChain> lValues;
2562 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002563 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002564 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2565 // build l-value
2566 builder.clearAccessChain();
2567 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002568 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002569 // keep outputs as l-values, evaluate input-only as r-values
2570 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2571 // save l-value
2572 lValues.push_back(builder.getAccessChain());
2573 } else {
2574 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002575 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002576 }
2577 }
2578
2579 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2580 // copy the original into that space.
2581 //
2582 // Also, build up the list of actual arguments to pass in for the call
2583 int lValueCount = 0;
2584 int rValueCount = 0;
2585 std::vector<spv::Id> spvArgs;
2586 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2587 spv::Id arg;
2588 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2589 // need space to hold the copy
2590 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2591 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2592 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2593 // need to copy the input into output space
2594 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002595 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002596 builder.createStore(copy, arg);
2597 }
2598 ++lValueCount;
2599 } else {
2600 arg = rValues[rValueCount];
2601 ++rValueCount;
2602 }
2603 spvArgs.push_back(arg);
2604 }
2605
2606 // 3. Make the call.
2607 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002608 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002609
2610 // 4. Copy back out an "out" arguments.
2611 lValueCount = 0;
2612 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2613 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2614 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2615 spv::Id copy = builder.createLoad(spvArgs[a]);
2616 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002617 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002618 }
2619 ++lValueCount;
2620 }
2621 }
2622
2623 return result;
2624}
2625
2626// Translate AST operation to SPV operation, already having SPV-based operands/types.
2627spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2628 spv::Id typeId, spv::Id left, spv::Id right,
2629 glslang::TBasicType typeProxy, bool reduceComparison)
2630{
2631 bool isUnsigned = typeProxy == glslang::EbtUint;
2632 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2633
2634 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002635 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002636 bool comparison = false;
2637
2638 switch (op) {
2639 case glslang::EOpAdd:
2640 case glslang::EOpAddAssign:
2641 if (isFloat)
2642 binOp = spv::OpFAdd;
2643 else
2644 binOp = spv::OpIAdd;
2645 break;
2646 case glslang::EOpSub:
2647 case glslang::EOpSubAssign:
2648 if (isFloat)
2649 binOp = spv::OpFSub;
2650 else
2651 binOp = spv::OpISub;
2652 break;
2653 case glslang::EOpMul:
2654 case glslang::EOpMulAssign:
2655 if (isFloat)
2656 binOp = spv::OpFMul;
2657 else
2658 binOp = spv::OpIMul;
2659 break;
2660 case glslang::EOpVectorTimesScalar:
2661 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002662 if (isFloat) {
2663 if (builder.isVector(right))
2664 std::swap(left, right);
2665 assert(builder.isScalar(right));
2666 needMatchingVectors = false;
2667 binOp = spv::OpVectorTimesScalar;
2668 } else
2669 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002670 break;
2671 case glslang::EOpVectorTimesMatrix:
2672 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002673 binOp = spv::OpVectorTimesMatrix;
2674 break;
2675 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002676 binOp = spv::OpMatrixTimesVector;
2677 break;
2678 case glslang::EOpMatrixTimesScalar:
2679 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002680 binOp = spv::OpMatrixTimesScalar;
2681 break;
2682 case glslang::EOpMatrixTimesMatrix:
2683 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002684 binOp = spv::OpMatrixTimesMatrix;
2685 break;
2686 case glslang::EOpOuterProduct:
2687 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002688 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002689 break;
2690
2691 case glslang::EOpDiv:
2692 case glslang::EOpDivAssign:
2693 if (isFloat)
2694 binOp = spv::OpFDiv;
2695 else if (isUnsigned)
2696 binOp = spv::OpUDiv;
2697 else
2698 binOp = spv::OpSDiv;
2699 break;
2700 case glslang::EOpMod:
2701 case glslang::EOpModAssign:
2702 if (isFloat)
2703 binOp = spv::OpFMod;
2704 else if (isUnsigned)
2705 binOp = spv::OpUMod;
2706 else
2707 binOp = spv::OpSMod;
2708 break;
2709 case glslang::EOpRightShift:
2710 case glslang::EOpRightShiftAssign:
2711 if (isUnsigned)
2712 binOp = spv::OpShiftRightLogical;
2713 else
2714 binOp = spv::OpShiftRightArithmetic;
2715 break;
2716 case glslang::EOpLeftShift:
2717 case glslang::EOpLeftShiftAssign:
2718 binOp = spv::OpShiftLeftLogical;
2719 break;
2720 case glslang::EOpAnd:
2721 case glslang::EOpAndAssign:
2722 binOp = spv::OpBitwiseAnd;
2723 break;
2724 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002725 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002726 binOp = spv::OpLogicalAnd;
2727 break;
2728 case glslang::EOpInclusiveOr:
2729 case glslang::EOpInclusiveOrAssign:
2730 binOp = spv::OpBitwiseOr;
2731 break;
2732 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002733 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002734 binOp = spv::OpLogicalOr;
2735 break;
2736 case glslang::EOpExclusiveOr:
2737 case glslang::EOpExclusiveOrAssign:
2738 binOp = spv::OpBitwiseXor;
2739 break;
2740 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002741 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002742 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002743 break;
2744
2745 case glslang::EOpLessThan:
2746 case glslang::EOpGreaterThan:
2747 case glslang::EOpLessThanEqual:
2748 case glslang::EOpGreaterThanEqual:
2749 case glslang::EOpEqual:
2750 case glslang::EOpNotEqual:
2751 case glslang::EOpVectorEqual:
2752 case glslang::EOpVectorNotEqual:
2753 comparison = true;
2754 break;
2755 default:
2756 break;
2757 }
2758
John Kessenich7c1aa102015-10-15 13:29:11 -06002759 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002760 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002761 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002762 if (builder.isMatrix(left) || builder.isMatrix(right))
2763 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002764
2765 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002766 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002767 builder.promoteScalar(precision, left, right);
2768
John Kessenich32cfd492016-02-02 12:37:46 -07002769 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002770 }
2771
2772 if (! comparison)
2773 return 0;
2774
John Kessenich7c1aa102015-10-15 13:29:11 -06002775 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002776
2777 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2778 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2779
John Kessenich22118352015-12-21 20:54:09 -07002780 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002781 }
2782
2783 switch (op) {
2784 case glslang::EOpLessThan:
2785 if (isFloat)
2786 binOp = spv::OpFOrdLessThan;
2787 else if (isUnsigned)
2788 binOp = spv::OpULessThan;
2789 else
2790 binOp = spv::OpSLessThan;
2791 break;
2792 case glslang::EOpGreaterThan:
2793 if (isFloat)
2794 binOp = spv::OpFOrdGreaterThan;
2795 else if (isUnsigned)
2796 binOp = spv::OpUGreaterThan;
2797 else
2798 binOp = spv::OpSGreaterThan;
2799 break;
2800 case glslang::EOpLessThanEqual:
2801 if (isFloat)
2802 binOp = spv::OpFOrdLessThanEqual;
2803 else if (isUnsigned)
2804 binOp = spv::OpULessThanEqual;
2805 else
2806 binOp = spv::OpSLessThanEqual;
2807 break;
2808 case glslang::EOpGreaterThanEqual:
2809 if (isFloat)
2810 binOp = spv::OpFOrdGreaterThanEqual;
2811 else if (isUnsigned)
2812 binOp = spv::OpUGreaterThanEqual;
2813 else
2814 binOp = spv::OpSGreaterThanEqual;
2815 break;
2816 case glslang::EOpEqual:
2817 case glslang::EOpVectorEqual:
2818 if (isFloat)
2819 binOp = spv::OpFOrdEqual;
2820 else
2821 binOp = spv::OpIEqual;
2822 break;
2823 case glslang::EOpNotEqual:
2824 case glslang::EOpVectorNotEqual:
2825 if (isFloat)
2826 binOp = spv::OpFOrdNotEqual;
2827 else
2828 binOp = spv::OpINotEqual;
2829 break;
2830 default:
2831 break;
2832 }
2833
John Kessenich32cfd492016-02-02 12:37:46 -07002834 if (binOp != spv::OpNop)
2835 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002836
2837 return 0;
2838}
2839
John Kessenich04bb8a02015-12-12 12:28:14 -07002840//
2841// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2842// These can be any of:
2843//
2844// matrix * scalar
2845// scalar * matrix
2846// matrix * matrix linear algebraic
2847// matrix * vector
2848// vector * matrix
2849// matrix * matrix componentwise
2850// matrix op matrix op in {+, -, /}
2851// matrix op scalar op in {+, -, /}
2852// scalar op matrix op in {+, -, /}
2853//
2854spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2855{
2856 bool firstClass = true;
2857
2858 // First, handle first-class matrix operations (* and matrix/scalar)
2859 switch (op) {
2860 case spv::OpFDiv:
2861 if (builder.isMatrix(left) && builder.isScalar(right)) {
2862 // turn matrix / scalar into a multiply...
2863 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2864 op = spv::OpMatrixTimesScalar;
2865 } else
2866 firstClass = false;
2867 break;
2868 case spv::OpMatrixTimesScalar:
2869 if (builder.isMatrix(right))
2870 std::swap(left, right);
2871 assert(builder.isScalar(right));
2872 break;
2873 case spv::OpVectorTimesMatrix:
2874 assert(builder.isVector(left));
2875 assert(builder.isMatrix(right));
2876 break;
2877 case spv::OpMatrixTimesVector:
2878 assert(builder.isMatrix(left));
2879 assert(builder.isVector(right));
2880 break;
2881 case spv::OpMatrixTimesMatrix:
2882 assert(builder.isMatrix(left));
2883 assert(builder.isMatrix(right));
2884 break;
2885 default:
2886 firstClass = false;
2887 break;
2888 }
2889
John Kessenich32cfd492016-02-02 12:37:46 -07002890 if (firstClass)
2891 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002892
2893 // Handle component-wise +, -, *, and / for all combinations of type.
2894 // The result type of all of them is the same type as the (a) matrix operand.
2895 // The algorithm is to:
2896 // - break the matrix(es) into vectors
2897 // - smear any scalar to a vector
2898 // - do vector operations
2899 // - make a matrix out the vector results
2900 switch (op) {
2901 case spv::OpFAdd:
2902 case spv::OpFSub:
2903 case spv::OpFDiv:
2904 case spv::OpFMul:
2905 {
2906 // one time set up...
2907 bool leftMat = builder.isMatrix(left);
2908 bool rightMat = builder.isMatrix(right);
2909 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2910 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2911 spv::Id scalarType = builder.getScalarTypeId(typeId);
2912 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2913 std::vector<spv::Id> results;
2914 spv::Id smearVec = spv::NoResult;
2915 if (builder.isScalar(left))
2916 smearVec = builder.smearScalar(precision, left, vecType);
2917 else if (builder.isScalar(right))
2918 smearVec = builder.smearScalar(precision, right, vecType);
2919
2920 // do each vector op
2921 for (unsigned int c = 0; c < numCols; ++c) {
2922 std::vector<unsigned int> indexes;
2923 indexes.push_back(c);
2924 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2925 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2926 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2927 builder.setPrecision(results.back(), precision);
2928 }
2929
2930 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002931 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002932 }
2933 default:
2934 assert(0);
2935 return spv::NoResult;
2936 }
2937}
2938
Rex Xu04db3f52015-09-16 11:44:02 +08002939spv::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 -06002940{
2941 spv::Op unaryOp = spv::OpNop;
2942 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002943 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002944 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002945
2946 switch (op) {
2947 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002948 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002949 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002950 if (builder.isMatrixType(typeId))
2951 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2952 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002953 unaryOp = spv::OpSNegate;
2954 break;
2955
2956 case glslang::EOpLogicalNot:
2957 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002958 unaryOp = spv::OpLogicalNot;
2959 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002960 case glslang::EOpBitwiseNot:
2961 unaryOp = spv::OpNot;
2962 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002963
John Kessenich140f3df2015-06-26 16:58:36 -06002964 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002968 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 case glslang::EOpTranspose:
2971 unaryOp = spv::OpTranspose;
2972 break;
2973
2974 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002975 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002982 break;
2983 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002984 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002985 break;
2986 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002988 break;
2989 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002990 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002991 break;
2992 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
2995 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002996 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002997 break;
2998
2999 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003000 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003001 break;
3002 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003003 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003004 break;
3005 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003013 break;
3014 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003015 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003016 break;
3017
3018 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003019 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 break;
3021 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003022 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003023 break;
3024
3025 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003026 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003027 break;
3028 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003029 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003030 break;
3031 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003032 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003033 break;
3034 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003035 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 break;
3037 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043
3044 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003045 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003046 break;
3047 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003048 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 break;
3050 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003051 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003052 break;
3053 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003054 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003055 break;
3056 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003057 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003058 break;
3059 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003060 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003061 break;
3062
3063 case glslang::EOpIsNan:
3064 unaryOp = spv::OpIsNan;
3065 break;
3066 case glslang::EOpIsInf:
3067 unaryOp = spv::OpIsInf;
3068 break;
3069
Rex Xucbc426e2015-12-15 16:03:10 +08003070 case glslang::EOpFloatBitsToInt:
3071 case glslang::EOpFloatBitsToUint:
3072 case glslang::EOpIntBitsToFloat:
3073 case glslang::EOpUintBitsToFloat:
3074 unaryOp = spv::OpBitcast;
3075 break;
3076
John Kessenich140f3df2015-06-26 16:58:36 -06003077 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003078 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003079 break;
3080 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003081 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003082 break;
3083 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003084 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003085 break;
3086 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003087 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
3089 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003090 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003091 break;
3092 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003093 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003094 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003095 case glslang::EOpPackSnorm4x8:
3096 libCall = spv::GLSLstd450PackSnorm4x8;
3097 break;
3098 case glslang::EOpUnpackSnorm4x8:
3099 libCall = spv::GLSLstd450UnpackSnorm4x8;
3100 break;
3101 case glslang::EOpPackUnorm4x8:
3102 libCall = spv::GLSLstd450PackUnorm4x8;
3103 break;
3104 case glslang::EOpUnpackUnorm4x8:
3105 libCall = spv::GLSLstd450UnpackUnorm4x8;
3106 break;
3107 case glslang::EOpPackDouble2x32:
3108 libCall = spv::GLSLstd450PackDouble2x32;
3109 break;
3110 case glslang::EOpUnpackDouble2x32:
3111 libCall = spv::GLSLstd450UnpackDouble2x32;
3112 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003113
3114 case glslang::EOpDPdx:
3115 unaryOp = spv::OpDPdx;
3116 break;
3117 case glslang::EOpDPdy:
3118 unaryOp = spv::OpDPdy;
3119 break;
3120 case glslang::EOpFwidth:
3121 unaryOp = spv::OpFwidth;
3122 break;
3123 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003124 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003125 unaryOp = spv::OpDPdxFine;
3126 break;
3127 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003128 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003129 unaryOp = spv::OpDPdyFine;
3130 break;
3131 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003132 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003133 unaryOp = spv::OpFwidthFine;
3134 break;
3135 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003136 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003137 unaryOp = spv::OpDPdxCoarse;
3138 break;
3139 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003140 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003141 unaryOp = spv::OpDPdyCoarse;
3142 break;
3143 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003144 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003145 unaryOp = spv::OpFwidthCoarse;
3146 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003147 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003148 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003149 libCall = spv::GLSLstd450InterpolateAtCentroid;
3150 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003151 case glslang::EOpAny:
3152 unaryOp = spv::OpAny;
3153 break;
3154 case glslang::EOpAll:
3155 unaryOp = spv::OpAll;
3156 break;
3157
3158 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003159 if (isFloat)
3160 libCall = spv::GLSLstd450FAbs;
3161 else
3162 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 if (isFloat)
3166 libCall = spv::GLSLstd450FSign;
3167 else
3168 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170
John Kessenichfc51d282015-08-19 13:34:18 -06003171 case glslang::EOpAtomicCounterIncrement:
3172 case glslang::EOpAtomicCounterDecrement:
3173 case glslang::EOpAtomicCounter:
3174 {
3175 // Handle all of the atomics in one place, in createAtomicOperation()
3176 std::vector<spv::Id> operands;
3177 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003178 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003179 }
3180
John Kessenichfc51d282015-08-19 13:34:18 -06003181 case glslang::EOpBitFieldReverse:
3182 unaryOp = spv::OpBitReverse;
3183 break;
3184 case glslang::EOpBitCount:
3185 unaryOp = spv::OpBitCount;
3186 break;
3187 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003188 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003189 break;
3190 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003191 if (isUnsigned)
3192 libCall = spv::GLSLstd450FindUMsb;
3193 else
3194 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003195 break;
3196
John Kessenich140f3df2015-06-26 16:58:36 -06003197 default:
3198 return 0;
3199 }
3200
3201 spv::Id id;
3202 if (libCall >= 0) {
3203 std::vector<spv::Id> args;
3204 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003205 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003206 } else
3207 id = builder.createUnaryOp(unaryOp, typeId, operand);
3208
John Kessenich32cfd492016-02-02 12:37:46 -07003209 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003210}
3211
John Kessenich7a53f762016-01-20 11:19:27 -07003212// Create a unary operation on a matrix
3213spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3214{
3215 // Handle unary operations vector by vector.
3216 // The result type is the same type as the original type.
3217 // The algorithm is to:
3218 // - break the matrix into vectors
3219 // - apply the operation to each vector
3220 // - make a matrix out the vector results
3221
3222 // get the types sorted out
3223 int numCols = builder.getNumColumns(operand);
3224 int numRows = builder.getNumRows(operand);
3225 spv::Id scalarType = builder.getScalarTypeId(typeId);
3226 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3227 std::vector<spv::Id> results;
3228
3229 // do each vector op
3230 for (int c = 0; c < numCols; ++c) {
3231 std::vector<unsigned int> indexes;
3232 indexes.push_back(c);
3233 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3234 results.push_back(builder.createUnaryOp(op, vecType, vec));
3235 builder.setPrecision(results.back(), precision);
3236 }
3237
3238 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003239 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003240}
3241
John Kessenich140f3df2015-06-26 16:58:36 -06003242spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3243{
3244 spv::Op convOp = spv::OpNop;
3245 spv::Id zero = 0;
3246 spv::Id one = 0;
3247
3248 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3249
3250 switch (op) {
3251 case glslang::EOpConvIntToBool:
3252 case glslang::EOpConvUintToBool:
3253 zero = builder.makeUintConstant(0);
3254 zero = makeSmearedConstant(zero, vectorSize);
3255 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3256
3257 case glslang::EOpConvFloatToBool:
3258 zero = builder.makeFloatConstant(0.0F);
3259 zero = makeSmearedConstant(zero, vectorSize);
3260 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3261
3262 case glslang::EOpConvDoubleToBool:
3263 zero = builder.makeDoubleConstant(0.0);
3264 zero = makeSmearedConstant(zero, vectorSize);
3265 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3266
3267 case glslang::EOpConvBoolToFloat:
3268 convOp = spv::OpSelect;
3269 zero = builder.makeFloatConstant(0.0);
3270 one = builder.makeFloatConstant(1.0);
3271 break;
3272 case glslang::EOpConvBoolToDouble:
3273 convOp = spv::OpSelect;
3274 zero = builder.makeDoubleConstant(0.0);
3275 one = builder.makeDoubleConstant(1.0);
3276 break;
3277 case glslang::EOpConvBoolToInt:
3278 zero = builder.makeIntConstant(0);
3279 one = builder.makeIntConstant(1);
3280 convOp = spv::OpSelect;
3281 break;
3282 case glslang::EOpConvBoolToUint:
3283 zero = builder.makeUintConstant(0);
3284 one = builder.makeUintConstant(1);
3285 convOp = spv::OpSelect;
3286 break;
3287
3288 case glslang::EOpConvIntToFloat:
3289 case glslang::EOpConvIntToDouble:
3290 convOp = spv::OpConvertSToF;
3291 break;
3292
3293 case glslang::EOpConvUintToFloat:
3294 case glslang::EOpConvUintToDouble:
3295 convOp = spv::OpConvertUToF;
3296 break;
3297
3298 case glslang::EOpConvDoubleToFloat:
3299 case glslang::EOpConvFloatToDouble:
3300 convOp = spv::OpFConvert;
3301 break;
3302
3303 case glslang::EOpConvFloatToInt:
3304 case glslang::EOpConvDoubleToInt:
3305 convOp = spv::OpConvertFToS;
3306 break;
3307
3308 case glslang::EOpConvUintToInt:
qininge24aa5e2016-04-07 15:40:27 -04003309 if (builder.isInSpecConstCodeGenMode()) {
3310 // Build zero scalar or vector for OpIAdd to do the conversion when
3311 // generating for OpSpecConstantOp instruction.
3312 zero = builder.makeIntConstant(0);
3313 zero = makeSmearedConstant(zero, vectorSize);
3314 }
3315 // Don't 'break' here as this case should be grouped together with
3316 // EOpConvIntToUint when generating normal run-time conversion
3317 // instruction.
John Kessenich140f3df2015-06-26 16:58:36 -06003318 case glslang::EOpConvIntToUint:
qininge24aa5e2016-04-07 15:40:27 -04003319 if (builder.isInSpecConstCodeGenMode()) {
3320 // Build zero scalar or vector for OpIAdd.
3321 if (zero == 0) {
3322 zero = builder.makeUintConstant(0);
3323 zero = makeSmearedConstant(zero, vectorSize);
3324 }
3325 // Use OpIAdd, instead of OpBitcast to do the conversion when
3326 // generating for OpSpecConstantOp instruction.
3327 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3328 }
3329 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003330 convOp = spv::OpBitcast;
3331 break;
3332
3333 case glslang::EOpConvFloatToUint:
3334 case glslang::EOpConvDoubleToUint:
3335 convOp = spv::OpConvertFToU;
3336 break;
3337 default:
3338 break;
3339 }
3340
3341 spv::Id result = 0;
3342 if (convOp == spv::OpNop)
3343 return result;
3344
3345 if (convOp == spv::OpSelect) {
3346 zero = makeSmearedConstant(zero, vectorSize);
3347 one = makeSmearedConstant(one, vectorSize);
3348 result = builder.createTriOp(convOp, destType, operand, one, zero);
3349 } else
3350 result = builder.createUnaryOp(convOp, destType, operand);
3351
John Kessenich32cfd492016-02-02 12:37:46 -07003352 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003353}
3354
3355spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3356{
3357 if (vectorSize == 0)
3358 return constant;
3359
3360 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3361 std::vector<spv::Id> components;
3362 for (int c = 0; c < vectorSize; ++c)
3363 components.push_back(constant);
3364 return builder.makeCompositeConstant(vectorTypeId, components);
3365}
3366
John Kessenich426394d2015-07-23 10:22:48 -06003367// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003368spv::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 -06003369{
3370 spv::Op opCode = spv::OpNop;
3371
3372 switch (op) {
3373 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003374 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003375 opCode = spv::OpAtomicIAdd;
3376 break;
3377 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003378 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003379 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003380 break;
3381 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003382 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003383 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003384 break;
3385 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003386 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003387 opCode = spv::OpAtomicAnd;
3388 break;
3389 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003390 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003391 opCode = spv::OpAtomicOr;
3392 break;
3393 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003394 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003395 opCode = spv::OpAtomicXor;
3396 break;
3397 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003398 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003399 opCode = spv::OpAtomicExchange;
3400 break;
3401 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003402 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003403 opCode = spv::OpAtomicCompareExchange;
3404 break;
3405 case glslang::EOpAtomicCounterIncrement:
3406 opCode = spv::OpAtomicIIncrement;
3407 break;
3408 case glslang::EOpAtomicCounterDecrement:
3409 opCode = spv::OpAtomicIDecrement;
3410 break;
3411 case glslang::EOpAtomicCounter:
3412 opCode = spv::OpAtomicLoad;
3413 break;
3414 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003415 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003416 break;
3417 }
3418
3419 // Sort out the operands
3420 // - mapping from glslang -> SPV
3421 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003422 // - compare-exchange swaps the value and comparator
3423 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003424 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3425 auto opIt = operands.begin(); // walk the glslang operands
3426 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003427 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3428 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3429 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003430 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3431 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003432 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003433 spvAtomicOperands.push_back(*(opIt + 1));
3434 spvAtomicOperands.push_back(*opIt);
3435 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003436 }
John Kessenich426394d2015-07-23 10:22:48 -06003437
John Kessenich3e60a6f2015-09-14 22:45:16 -06003438 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003439 for (; opIt != operands.end(); ++opIt)
3440 spvAtomicOperands.push_back(*opIt);
3441
3442 return builder.createOp(opCode, typeId, spvAtomicOperands);
3443}
3444
John Kessenich5e4b1242015-08-06 22:53:06 -06003445spv::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 -06003446{
John Kessenich5e4b1242015-08-06 22:53:06 -06003447 bool isUnsigned = typeProxy == glslang::EbtUint;
3448 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3449
John Kessenich140f3df2015-06-26 16:58:36 -06003450 spv::Op opCode = spv::OpNop;
3451 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003452 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003453 spv::Id typeId0 = 0;
3454 if (consumedOperands > 0)
3455 typeId0 = builder.getTypeId(operands[0]);
3456 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003457
3458 switch (op) {
3459 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003460 if (isFloat)
3461 libCall = spv::GLSLstd450FMin;
3462 else if (isUnsigned)
3463 libCall = spv::GLSLstd450UMin;
3464 else
3465 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003466 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003469 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003470 break;
3471 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003472 if (isFloat)
3473 libCall = spv::GLSLstd450FMax;
3474 else if (isUnsigned)
3475 libCall = spv::GLSLstd450UMax;
3476 else
3477 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003478 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
3480 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003481 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 break;
3483 case glslang::EOpDot:
3484 opCode = spv::OpDot;
3485 break;
3486 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003487 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003488 break;
3489
3490 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003491 if (isFloat)
3492 libCall = spv::GLSLstd450FClamp;
3493 else if (isUnsigned)
3494 libCall = spv::GLSLstd450UClamp;
3495 else
3496 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003497 builder.promoteScalar(precision, operands.front(), operands[1]);
3498 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003501 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3502 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003503 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003504 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003505 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003506 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003507 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003508 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003509 break;
3510 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003512 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003513 break;
3514 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003515 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003516 builder.promoteScalar(precision, operands[0], operands[2]);
3517 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003518 break;
3519
3520 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003521 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003522 break;
3523 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003524 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003525 break;
3526 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003527 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003528 break;
3529 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003530 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003531 break;
3532 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003533 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003534 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003535 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003536 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003537 libCall = spv::GLSLstd450InterpolateAtSample;
3538 break;
3539 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003540 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003541 libCall = spv::GLSLstd450InterpolateAtOffset;
3542 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003543 case glslang::EOpAddCarry:
3544 opCode = spv::OpIAddCarry;
3545 typeId = builder.makeStructResultType(typeId0, typeId0);
3546 consumedOperands = 2;
3547 break;
3548 case glslang::EOpSubBorrow:
3549 opCode = spv::OpISubBorrow;
3550 typeId = builder.makeStructResultType(typeId0, typeId0);
3551 consumedOperands = 2;
3552 break;
3553 case glslang::EOpUMulExtended:
3554 opCode = spv::OpUMulExtended;
3555 typeId = builder.makeStructResultType(typeId0, typeId0);
3556 consumedOperands = 2;
3557 break;
3558 case glslang::EOpIMulExtended:
3559 opCode = spv::OpSMulExtended;
3560 typeId = builder.makeStructResultType(typeId0, typeId0);
3561 consumedOperands = 2;
3562 break;
3563 case glslang::EOpBitfieldExtract:
3564 if (isUnsigned)
3565 opCode = spv::OpBitFieldUExtract;
3566 else
3567 opCode = spv::OpBitFieldSExtract;
3568 break;
3569 case glslang::EOpBitfieldInsert:
3570 opCode = spv::OpBitFieldInsert;
3571 break;
3572
3573 case glslang::EOpFma:
3574 libCall = spv::GLSLstd450Fma;
3575 break;
3576 case glslang::EOpFrexp:
3577 libCall = spv::GLSLstd450FrexpStruct;
3578 if (builder.getNumComponents(operands[0]) == 1)
3579 frexpIntType = builder.makeIntegerType(32, true);
3580 else
3581 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3582 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3583 consumedOperands = 1;
3584 break;
3585 case glslang::EOpLdexp:
3586 libCall = spv::GLSLstd450Ldexp;
3587 break;
3588
John Kessenich140f3df2015-06-26 16:58:36 -06003589 default:
3590 return 0;
3591 }
3592
3593 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003594 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003595 // Use an extended instruction from the standard library.
3596 // Construct the call arguments, without modifying the original operands vector.
3597 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3598 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003599 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003600 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003601 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003602 case 0:
3603 // should all be handled by visitAggregate and createNoArgOperation
3604 assert(0);
3605 return 0;
3606 case 1:
3607 // should all be handled by createUnaryOperation
3608 assert(0);
3609 return 0;
3610 case 2:
3611 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3612 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003613 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003614 // anything 3 or over doesn't have l-value operands, so all should be consumed
3615 assert(consumedOperands == operands.size());
3616 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003617 break;
3618 }
3619 }
3620
John Kessenich55e7d112015-11-15 21:33:39 -07003621 // Decode the return types that were structures
3622 switch (op) {
3623 case glslang::EOpAddCarry:
3624 case glslang::EOpSubBorrow:
3625 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3626 id = builder.createCompositeExtract(id, typeId0, 0);
3627 break;
3628 case glslang::EOpUMulExtended:
3629 case glslang::EOpIMulExtended:
3630 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3631 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3632 break;
3633 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003634 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003635 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3636 id = builder.createCompositeExtract(id, typeId0, 0);
3637 break;
3638 default:
3639 break;
3640 }
3641
John Kessenich32cfd492016-02-02 12:37:46 -07003642 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003643}
3644
3645// Intrinsics with no arguments, no return value, and no precision.
3646spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3647{
3648 // TODO: get the barrier operands correct
3649
3650 switch (op) {
3651 case glslang::EOpEmitVertex:
3652 builder.createNoResultOp(spv::OpEmitVertex);
3653 return 0;
3654 case glslang::EOpEndPrimitive:
3655 builder.createNoResultOp(spv::OpEndPrimitive);
3656 return 0;
3657 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003658 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3659 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003660 return 0;
3661 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003662 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003663 return 0;
3664 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003665 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003666 return 0;
3667 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003668 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003669 return 0;
3670 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003671 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003672 return 0;
3673 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003674 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003675 return 0;
3676 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003677 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003678 return 0;
3679 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003680 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003681 return 0;
3682 }
3683}
3684
3685spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3686{
John Kessenich2f273362015-07-18 22:34:27 -06003687 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003688 spv::Id id;
3689 if (symbolValues.end() != iter) {
3690 id = iter->second;
3691 return id;
3692 }
3693
3694 // it was not found, create it
3695 id = createSpvVariable(symbol);
3696 symbolValues[symbol->getId()] = id;
3697
3698 if (! symbol->getType().isStruct()) {
3699 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003700 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003701 if (symbol->getType().getQualifier().hasSpecConstantId())
3702 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003703 if (symbol->getQualifier().hasLocation())
3704 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3705 if (symbol->getQualifier().hasIndex())
3706 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3707 if (symbol->getQualifier().hasComponent())
3708 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3709 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003710 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003711 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003713 if (symbol->getQualifier().hasXfbBuffer())
3714 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3715 if (symbol->getQualifier().hasXfbOffset())
3716 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3717 }
3718 }
3719
John Kesseniche0b6cad2015-12-24 10:30:13 -07003720 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003721 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003722 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003723 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003724 }
John Kessenich140f3df2015-06-26 16:58:36 -06003725 if (symbol->getQualifier().hasSet())
3726 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003727 else if (IsDescriptorResource(symbol->getType())) {
3728 // default to 0
3729 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3730 }
John Kessenich140f3df2015-06-26 16:58:36 -06003731 if (symbol->getQualifier().hasBinding())
3732 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003733 if (symbol->getQualifier().hasAttachment())
3734 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003735 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003736 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003737 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003738 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003739 if (symbol->getQualifier().hasXfbBuffer())
3740 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3741 }
3742
Rex Xu1da878f2016-02-21 20:59:01 +08003743 if (symbol->getType().isImage()) {
3744 std::vector<spv::Decoration> memory;
3745 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3746 for (unsigned int i = 0; i < memory.size(); ++i)
3747 addDecoration(id, memory[i]);
3748 }
3749
John Kessenich140f3df2015-06-26 16:58:36 -06003750 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003751 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003752 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003753 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003754
John Kessenich140f3df2015-06-26 16:58:36 -06003755 return id;
3756}
3757
John Kessenich55e7d112015-11-15 21:33:39 -07003758// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003759void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3760{
3761 if (dec != spv::BadValue)
3762 builder.addDecoration(id, dec);
3763}
3764
John Kessenich55e7d112015-11-15 21:33:39 -07003765// If 'dec' is valid, add a one-operand decoration to an object
3766void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3767{
3768 if (dec != spv::BadValue)
3769 builder.addDecoration(id, dec, value);
3770}
3771
3772// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003773void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3774{
3775 if (dec != spv::BadValue)
3776 builder.addMemberDecoration(id, (unsigned)member, dec);
3777}
3778
John Kessenich92187592016-02-01 13:45:25 -07003779// If 'dec' is valid, add a one-operand decoration to a struct member
3780void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3781{
3782 if (dec != spv::BadValue)
3783 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3784}
3785
John Kessenich55e7d112015-11-15 21:33:39 -07003786// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003787// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003788//
3789// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3790//
3791// Recursively walk the nodes. The nodes form a tree whose leaves are
3792// regular constants, which themselves are trees that createSpvConstant()
3793// recursively walks. So, this function walks the "top" of the tree:
3794// - emit specialization constant-building instructions for specConstant
3795// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003796spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003797{
John Kessenich7cc0e282016-03-20 00:46:02 -06003798 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003799
qining4f4bb812016-04-03 23:55:17 -04003800 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003801 if (! node.getQualifier().specConstant) {
3802 // hand off to the non-spec-constant path
3803 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3804 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003805 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003806 nextConst, false);
3807 }
3808
3809 // We now know we have a specialization constant to build
3810
qining4f4bb812016-04-03 23:55:17 -04003811 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3812 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3813 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3814 std::vector<spv::Id> dimConstId;
3815 for (int dim = 0; dim < 3; ++dim) {
3816 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3817 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3818 if (specConst)
3819 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3820 }
3821 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3822 }
3823
3824 // An AST node labelled as specialization constant should be a symbol node.
3825 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3826 if (auto* sn = node.getAsSymbolNode()) {
3827 if (auto* sub_tree = sn->getConstSubtree()) {
3828 return createSpvConstantFromConstSubTree(sub_tree);
3829 } else if (auto* const_union_array = &sn->getConstArray()){
3830 int nextConst = 0;
3831 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003832 }
3833 }
qining4f4bb812016-04-03 23:55:17 -04003834
3835 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3836 // constant sub tree as initializer.
3837 spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
3838 exit(1);
3839 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003840}
3841
John Kessenich140f3df2015-06-26 16:58:36 -06003842// Use 'consts' as the flattened glslang source of scalar constants to recursively
3843// build the aggregate SPIR-V constant.
3844//
3845// If there are not enough elements present in 'consts', 0 will be substituted;
3846// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3847//
qining08408382016-03-21 09:51:37 -04003848spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003849{
3850 // vector of constants for SPIR-V
3851 std::vector<spv::Id> spvConsts;
3852
3853 // Type is used for struct and array constants
3854 spv::Id typeId = convertGlslangToSpvType(glslangType);
3855
3856 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003857 glslang::TType elementType(glslangType, 0);
3858 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003859 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003860 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003861 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003862 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003863 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003864 } else if (glslangType.getStruct()) {
3865 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3866 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003867 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003868 } else if (glslangType.isVector()) {
3869 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3870 bool zero = nextConst >= consts.size();
3871 switch (glslangType.getBasicType()) {
3872 case glslang::EbtInt:
3873 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3874 break;
3875 case glslang::EbtUint:
3876 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3877 break;
3878 case glslang::EbtFloat:
3879 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3880 break;
3881 case glslang::EbtDouble:
3882 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3883 break;
3884 case glslang::EbtBool:
3885 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3886 break;
3887 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003888 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003889 break;
3890 }
3891 ++nextConst;
3892 }
3893 } else {
3894 // we have a non-aggregate (scalar) constant
3895 bool zero = nextConst >= consts.size();
3896 spv::Id scalar = 0;
3897 switch (glslangType.getBasicType()) {
3898 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003899 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003900 break;
3901 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003902 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003903 break;
3904 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003905 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003906 break;
3907 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003908 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003909 break;
3910 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003911 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003912 break;
3913 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003914 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003915 break;
3916 }
3917 ++nextConst;
3918 return scalar;
3919 }
3920
3921 return builder.makeCompositeConstant(typeId, spvConsts);
3922}
3923
qining08408382016-03-21 09:51:37 -04003924// Create constant ID from const initializer sub tree.
3925spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstSubTree(
qining5c61d8e2016-03-31 13:57:28 -04003926 glslang::TIntermTyped* subTree)
3927{
qining08408382016-03-21 09:51:37 -04003928 const glslang::TType& glslangType = subTree->getType();
3929 spv::Id typeId = convertGlslangToSpvType(glslangType);
3930 bool is_spec_const = subTree->getType().getQualifier().isSpecConstant();
3931 if (const glslang::TIntermAggregate* an = subTree->getAsAggregate()) {
3932 // Aggregate node, we should generate OpConstantComposite or
3933 // OpSpecConstantComposite instruction.
qining13545202016-03-21 09:51:37 -04003934
qining08408382016-03-21 09:51:37 -04003935 std::vector<spv::Id> const_constituents;
3936 for (auto NI = an->getSequence().begin(); NI != an->getSequence().end();
3937 NI++) {
3938 const_constituents.push_back(
3939 createSpvConstantFromConstSubTree((*NI)->getAsTyped()));
3940 }
3941 // Note that constructors are aggregate nodes, so expressions like:
3942 // float x = float(y) will become an aggregate node. If 'x' is declared
3943 // as a constant, the aggregate node representing 'float(y)' will be
3944 // processed here.
3945 if (builder.isVectorType(typeId) || builder.isMatrixType(typeId) ||
3946 builder.isAggregateType(typeId)) {
3947 return builder.makeCompositeConstant(typeId, const_constituents, is_spec_const);
3948 } else {
3949 assert(builder.isScalarType(typeId) && const_constituents.size() == 1);
3950 return const_constituents.front();
3951 }
3952
qining13545202016-03-21 09:51:37 -04003953 } else if (glslang::TIntermBinary* bn = subTree->getAsBinaryNode()) {
qining08408382016-03-21 09:51:37 -04003954 // Binary operation node, we should generate OpSpecConstantOp <binary op>
3955 // This case should only happen when Specialization Constants are involved.
qining13545202016-03-21 09:51:37 -04003956 bn->traverse(this);
3957 return accessChainLoad(bn->getType());
3958
3959 } else if (glslang::TIntermUnary* un = subTree->getAsUnaryNode()) {
qining08408382016-03-21 09:51:37 -04003960 // Unary operation node, similar to binary operation node, should only
3961 // happen when specialization constants are involved.
qining13545202016-03-21 09:51:37 -04003962 un->traverse(this);
3963 return accessChainLoad(un->getType());
qining08408382016-03-21 09:51:37 -04003964
3965 } else if (const glslang::TIntermConstantUnion* cn = subTree->getAsConstantUnion()) {
3966 // ConstantUnion node, should redirect to
3967 // createSpvConstantFromConstUnionArray
3968 int nextConst = 0;
3969 return createSpvConstantFromConstUnionArray(
3970 glslangType, cn->getConstArray(), nextConst, is_spec_const);
3971
3972 } else if (const glslang::TIntermSymbol* sn = subTree->getAsSymbolNode()) {
3973 // Symbol node. Call getSymbolId(). This should cover both cases 1) the
3974 // symbol has already been assigned an ID, 2) need a new ID for this
3975 // symbol.
3976 return getSymbolId(sn);
3977
3978 } else {
3979 spv::MissingFunctionality(
3980 "createSpvConstantFromConstSubTree() not covered TIntermTyped* const "
3981 "initializer subtree.");
3982 return spv::NoResult;
3983 }
3984}
3985
John Kessenich7c1aa102015-10-15 13:29:11 -06003986// Return true if the node is a constant or symbol whose reading has no
3987// non-trivial observable cost or effect.
3988bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3989{
3990 // don't know what this is
3991 if (node == nullptr)
3992 return false;
3993
3994 // a constant is safe
3995 if (node->getAsConstantUnion() != nullptr)
3996 return true;
3997
3998 // not a symbol means non-trivial
3999 if (node->getAsSymbolNode() == nullptr)
4000 return false;
4001
4002 // a symbol, depends on what's being read
4003 switch (node->getType().getQualifier().storage) {
4004 case glslang::EvqTemporary:
4005 case glslang::EvqGlobal:
4006 case glslang::EvqIn:
4007 case glslang::EvqInOut:
4008 case glslang::EvqConst:
4009 case glslang::EvqConstReadOnly:
4010 case glslang::EvqUniform:
4011 return true;
4012 default:
4013 return false;
4014 }
4015}
4016
4017// A node is trivial if it is a single operation with no side effects.
4018// Error on the side of saying non-trivial.
4019// Return true if trivial.
4020bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4021{
4022 if (node == nullptr)
4023 return false;
4024
4025 // symbols and constants are trivial
4026 if (isTrivialLeaf(node))
4027 return true;
4028
4029 // otherwise, it needs to be a simple operation or one or two leaf nodes
4030
4031 // not a simple operation
4032 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4033 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4034 if (binaryNode == nullptr && unaryNode == nullptr)
4035 return false;
4036
4037 // not on leaf nodes
4038 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4039 return false;
4040
4041 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4042 return false;
4043 }
4044
4045 switch (node->getAsOperator()->getOp()) {
4046 case glslang::EOpLogicalNot:
4047 case glslang::EOpConvIntToBool:
4048 case glslang::EOpConvUintToBool:
4049 case glslang::EOpConvFloatToBool:
4050 case glslang::EOpConvDoubleToBool:
4051 case glslang::EOpEqual:
4052 case glslang::EOpNotEqual:
4053 case glslang::EOpLessThan:
4054 case glslang::EOpGreaterThan:
4055 case glslang::EOpLessThanEqual:
4056 case glslang::EOpGreaterThanEqual:
4057 case glslang::EOpIndexDirect:
4058 case glslang::EOpIndexDirectStruct:
4059 case glslang::EOpLogicalXor:
4060 case glslang::EOpAny:
4061 case glslang::EOpAll:
4062 return true;
4063 default:
4064 return false;
4065 }
4066}
4067
4068// Emit short-circuiting code, where 'right' is never evaluated unless
4069// the left side is true (for &&) or false (for ||).
4070spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4071{
4072 spv::Id boolTypeId = builder.makeBoolType();
4073
4074 // emit left operand
4075 builder.clearAccessChain();
4076 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004077 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004078
4079 // Operands to accumulate OpPhi operands
4080 std::vector<spv::Id> phiOperands;
4081 // accumulate left operand's phi information
4082 phiOperands.push_back(leftId);
4083 phiOperands.push_back(builder.getBuildPoint()->getId());
4084
4085 // Make the two kinds of operation symmetric with a "!"
4086 // || => emit "if (! left) result = right"
4087 // && => emit "if ( left) result = right"
4088 //
4089 // TODO: this runtime "not" for || could be avoided by adding functionality
4090 // to 'builder' to have an "else" without an "then"
4091 if (op == glslang::EOpLogicalOr)
4092 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4093
4094 // make an "if" based on the left value
4095 spv::Builder::If ifBuilder(leftId, builder);
4096
4097 // emit right operand as the "then" part of the "if"
4098 builder.clearAccessChain();
4099 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004100 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004101
4102 // accumulate left operand's phi information
4103 phiOperands.push_back(rightId);
4104 phiOperands.push_back(builder.getBuildPoint()->getId());
4105
4106 // finish the "if"
4107 ifBuilder.makeEndIf();
4108
4109 // phi together the two results
4110 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4111}
4112
John Kessenich140f3df2015-06-26 16:58:36 -06004113}; // end anonymous namespace
4114
4115namespace glslang {
4116
John Kessenich68d78fd2015-07-12 19:28:10 -06004117void GetSpirvVersion(std::string& version)
4118{
John Kessenich9e55f632015-07-15 10:03:39 -06004119 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004120 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004121 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004122 version = buf;
4123}
4124
John Kessenich140f3df2015-06-26 16:58:36 -06004125// Write SPIR-V out to a binary file
4126void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4127{
4128 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004129 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004130 for (int i = 0; i < (int)spirv.size(); ++i) {
4131 unsigned int word = spirv[i];
4132 out.write((const char*)&word, 4);
4133 }
4134 out.close();
4135}
4136
4137//
4138// Set up the glslang traversal
4139//
4140void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4141{
4142 TIntermNode* root = intermediate.getTreeRoot();
4143
4144 if (root == 0)
4145 return;
4146
4147 glslang::GetThreadPoolAllocator().push();
4148
4149 TGlslangToSpvTraverser it(&intermediate);
4150
4151 root->traverse(&it);
4152
4153 it.dumpSpv(spirv);
4154
4155 glslang::GetThreadPoolAllocator().pop();
4156}
4157
4158}; // end namespace glslang