blob: 147a4bd051ca4b0e24946130f7fe03d7a0220e1c [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{
781 // getSymbolId() will set up all the IO decorations on the first call.
782 // Formal function parameters were mapped during makeFunctions().
783 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700784
785 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
786 if (builder.isPointer(id)) {
787 spv::StorageClass sc = builder.getStorageClass(id);
788 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
789 iOSet.insert(id);
790 }
791
792 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700793 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600794 // Prepare to generate code for the access
795
796 // L-value chains will be computed left to right. We're on the symbol now,
797 // which is the left-most part of the access chain, so now is "clear" time,
798 // followed by setting the base.
799 builder.clearAccessChain();
800
801 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700802 // except for
803 // A) "const in" arguments to a function, which are an intermediate object.
804 // See comments in handleUserFunctionCall().
805 // B) Specialization constants (normal constant don't even come in as a variable),
806 // These are also pure R-values.
807 glslang::TQualifier qualifier = symbol->getQualifier();
808 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
809 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600810 builder.setAccessChainRValue(id);
811 else
812 builder.setAccessChainLValue(id);
813 }
814}
815
816bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
817{
qining40887662016-04-03 22:20:42 -0400818 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
819 if (node->getType().getQualifier().isSpecConstant())
820 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
821
John Kessenich140f3df2015-06-26 16:58:36 -0600822 // First, handle special cases
823 switch (node->getOp()) {
824 case glslang::EOpAssign:
825 case glslang::EOpAddAssign:
826 case glslang::EOpSubAssign:
827 case glslang::EOpMulAssign:
828 case glslang::EOpVectorTimesMatrixAssign:
829 case glslang::EOpVectorTimesScalarAssign:
830 case glslang::EOpMatrixTimesScalarAssign:
831 case glslang::EOpMatrixTimesMatrixAssign:
832 case glslang::EOpDivAssign:
833 case glslang::EOpModAssign:
834 case glslang::EOpAndAssign:
835 case glslang::EOpInclusiveOrAssign:
836 case glslang::EOpExclusiveOrAssign:
837 case glslang::EOpLeftShiftAssign:
838 case glslang::EOpRightShiftAssign:
839 // A bin-op assign "a += b" means the same thing as "a = a + b"
840 // where a is evaluated before b. For a simple assignment, GLSL
841 // says to evaluate the left before the right. So, always, left
842 // node then right node.
843 {
844 // get the left l-value, save it away
845 builder.clearAccessChain();
846 node->getLeft()->traverse(this);
847 spv::Builder::AccessChain lValue = builder.getAccessChain();
848
849 // evaluate the right
850 builder.clearAccessChain();
851 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700852 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600853
854 if (node->getOp() != glslang::EOpAssign) {
855 // the left is also an r-value
856 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700857 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600858
859 // do the operation
860 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
861 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
862 node->getType().getBasicType());
863
864 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700865 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600866 }
867
868 // store the result
869 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800870 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600871
872 // assignments are expressions having an rValue after they are evaluated...
873 builder.clearAccessChain();
874 builder.setAccessChainRValue(rValue);
875 }
876 return false;
877 case glslang::EOpIndexDirect:
878 case glslang::EOpIndexDirectStruct:
879 {
880 // Get the left part of the access chain.
881 node->getLeft()->traverse(this);
882
883 // Add the next element in the chain
884
John Kessenich55e7d112015-11-15 21:33:39 -0700885 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600886 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
887 // This may be, e.g., an anonymous block-member selection, which generally need
888 // index remapping due to hidden members in anonymous blocks.
889 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700890 assert(remapper.size() > 0);
891 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600892 }
893
894 if (! node->getLeft()->getType().isArray() &&
895 node->getLeft()->getType().isVector() &&
896 node->getOp() == glslang::EOpIndexDirect) {
897 // This is essentially a hard-coded vector swizzle of size 1,
898 // so short circuit the access-chain stuff with a swizzle.
899 std::vector<unsigned> swizzle;
900 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600901 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600902 } else {
903 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600904 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600905 }
906 }
907 return false;
908 case glslang::EOpIndexIndirect:
909 {
910 // Structure or array or vector indirection.
911 // Will use native SPIR-V access-chain for struct and array indirection;
912 // matrices are arrays of vectors, so will also work for a matrix.
913 // Will use the access chain's 'component' for variable index into a vector.
914
915 // This adapter is building access chains left to right.
916 // Set up the access chain to the left.
917 node->getLeft()->traverse(this);
918
919 // save it so that computing the right side doesn't trash it
920 spv::Builder::AccessChain partial = builder.getAccessChain();
921
922 // compute the next index in the chain
923 builder.clearAccessChain();
924 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700925 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600926
927 // restore the saved access chain
928 builder.setAccessChain(partial);
929
930 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600931 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600932 else
John Kessenichfa668da2015-09-13 14:46:30 -0600933 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600934 }
935 return false;
936 case glslang::EOpVectorSwizzle:
937 {
938 node->getLeft()->traverse(this);
939 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
940 std::vector<unsigned> swizzle;
941 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
942 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600943 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600944 }
945 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600946 case glslang::EOpLogicalOr:
947 case glslang::EOpLogicalAnd:
948 {
949
950 // These may require short circuiting, but can sometimes be done as straight
951 // binary operations. The right operand must be short circuited if it has
952 // side effects, and should probably be if it is complex.
953 if (isTrivial(node->getRight()->getAsTyped()))
954 break; // handle below as a normal binary operation
955 // otherwise, we need to do dynamic short circuiting on the right operand
956 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
957 builder.clearAccessChain();
958 builder.setAccessChainRValue(result);
959 }
960 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600961 default:
962 break;
963 }
964
965 // Assume generic binary op...
966
John Kessenich32cfd492016-02-02 12:37:46 -0700967 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600968 builder.clearAccessChain();
969 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700970 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600971
John Kessenich32cfd492016-02-02 12:37:46 -0700972 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600973 builder.clearAccessChain();
974 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700975 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600976
John Kessenich32cfd492016-02-02 12:37:46 -0700977 // get result
978 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
979 convertGlslangToSpvType(node->getType()), left, right,
980 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600981
John Kessenich50e57562015-12-21 21:21:11 -0700982 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600983 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700984 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700985 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600986 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600987 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600988 return false;
989 }
John Kessenich140f3df2015-06-26 16:58:36 -0600990}
991
992bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
993{
qining40887662016-04-03 22:20:42 -0400994 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
995 if (node->getType().getQualifier().isSpecConstant())
996 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
997
John Kessenichfc51d282015-08-19 13:34:18 -0600998 spv::Id result = spv::NoResult;
999
1000 // try texturing first
1001 result = createImageTextureFunctionCall(node);
1002 if (result != spv::NoResult) {
1003 builder.clearAccessChain();
1004 builder.setAccessChainRValue(result);
1005
1006 return false; // done with this node
1007 }
1008
1009 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001010
1011 if (node->getOp() == glslang::EOpArrayLength) {
1012 // Quite special; won't want to evaluate the operand.
1013
1014 // Normal .length() would have been constant folded by the front-end.
1015 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001016 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001017 assert(node->getOperand()->getType().isRuntimeSizedArray());
1018 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1019 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001020 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1021 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001022
1023 builder.clearAccessChain();
1024 builder.setAccessChainRValue(length);
1025
1026 return false;
1027 }
1028
John Kessenichfc51d282015-08-19 13:34:18 -06001029 // Start by evaluating the operand
1030
John Kessenich140f3df2015-06-26 16:58:36 -06001031 builder.clearAccessChain();
1032 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001033
Rex Xufc618912015-09-09 16:42:49 +08001034 spv::Id operand = spv::NoResult;
1035
1036 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1037 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001038 node->getOp() == glslang::EOpAtomicCounter ||
1039 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001040 operand = builder.accessChainGetLValue(); // Special case l-value operands
1041 else
John Kessenich32cfd492016-02-02 12:37:46 -07001042 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001043
1044 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1045
1046 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001047 if (! result)
1048 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001049
1050 // if not, then possibly an operation
1051 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001052 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001053
1054 if (result) {
1055 builder.clearAccessChain();
1056 builder.setAccessChainRValue(result);
1057
1058 return false; // done with this node
1059 }
1060
1061 // it must be a special case, check...
1062 switch (node->getOp()) {
1063 case glslang::EOpPostIncrement:
1064 case glslang::EOpPostDecrement:
1065 case glslang::EOpPreIncrement:
1066 case glslang::EOpPreDecrement:
1067 {
1068 // we need the integer value "1" or the floating point "1.0" to add/subtract
1069 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1070 builder.makeFloatConstant(1.0F) :
1071 builder.makeIntConstant(1);
1072 glslang::TOperator op;
1073 if (node->getOp() == glslang::EOpPreIncrement ||
1074 node->getOp() == glslang::EOpPostIncrement)
1075 op = glslang::EOpAdd;
1076 else
1077 op = glslang::EOpSub;
1078
1079 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1080 convertGlslangToSpvType(node->getType()), operand, one,
1081 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001082 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001083
1084 // The result of operation is always stored, but conditionally the
1085 // consumed result. The consumed result is always an r-value.
1086 builder.accessChainStore(result);
1087 builder.clearAccessChain();
1088 if (node->getOp() == glslang::EOpPreIncrement ||
1089 node->getOp() == glslang::EOpPreDecrement)
1090 builder.setAccessChainRValue(result);
1091 else
1092 builder.setAccessChainRValue(operand);
1093 }
1094
1095 return false;
1096
1097 case glslang::EOpEmitStreamVertex:
1098 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1099 return false;
1100 case glslang::EOpEndStreamPrimitive:
1101 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1102 return false;
1103
1104 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001105 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001106 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001107 }
John Kessenich140f3df2015-06-26 16:58:36 -06001108}
1109
1110bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1111{
John Kessenichfc51d282015-08-19 13:34:18 -06001112 spv::Id result = spv::NoResult;
1113
1114 // try texturing
1115 result = createImageTextureFunctionCall(node);
1116 if (result != spv::NoResult) {
1117 builder.clearAccessChain();
1118 builder.setAccessChainRValue(result);
1119
1120 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001121 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001122 // "imageStore" is a special case, which has no result
1123 return false;
1124 }
John Kessenichfc51d282015-08-19 13:34:18 -06001125
John Kessenich140f3df2015-06-26 16:58:36 -06001126 glslang::TOperator binOp = glslang::EOpNull;
1127 bool reduceComparison = true;
1128 bool isMatrix = false;
1129 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001130 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001131
1132 assert(node->getOp());
1133
1134 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1135
1136 switch (node->getOp()) {
1137 case glslang::EOpSequence:
1138 {
1139 if (preVisit)
1140 ++sequenceDepth;
1141 else
1142 --sequenceDepth;
1143
1144 if (sequenceDepth == 1) {
1145 // If this is the parent node of all the functions, we want to see them
1146 // early, so all call points have actual SPIR-V functions to reference.
1147 // In all cases, still let the traverser visit the children for us.
1148 makeFunctions(node->getAsAggregate()->getSequence());
1149
1150 // Also, we want all globals initializers to go into the entry of main(), before
1151 // anything else gets there, so visit out of order, doing them all now.
1152 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1153
1154 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1155 // so do them manually.
1156 visitFunctions(node->getAsAggregate()->getSequence());
1157
1158 return false;
1159 }
1160
1161 return true;
1162 }
1163 case glslang::EOpLinkerObjects:
1164 {
1165 if (visit == glslang::EvPreVisit)
1166 linkageOnly = true;
1167 else
1168 linkageOnly = false;
1169
1170 return true;
1171 }
1172 case glslang::EOpComma:
1173 {
1174 // processing from left to right naturally leaves the right-most
1175 // lying around in the access chain
1176 glslang::TIntermSequence& glslangOperands = node->getSequence();
1177 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1178 glslangOperands[i]->traverse(this);
1179
1180 return false;
1181 }
1182 case glslang::EOpFunction:
1183 if (visit == glslang::EvPreVisit) {
1184 if (isShaderEntrypoint(node)) {
1185 inMain = true;
1186 builder.setBuildPoint(shaderEntry->getLastBlock());
1187 } else {
1188 handleFunctionEntry(node);
1189 }
1190 } else {
1191 if (inMain)
1192 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001193 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001194 inMain = false;
1195 }
1196
1197 return true;
1198 case glslang::EOpParameters:
1199 // Parameters will have been consumed by EOpFunction processing, but not
1200 // the body, so we still visited the function node's children, making this
1201 // child redundant.
1202 return false;
1203 case glslang::EOpFunctionCall:
1204 {
1205 if (node->isUserDefined())
1206 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001207 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1208 if (result) {
1209 builder.clearAccessChain();
1210 builder.setAccessChainRValue(result);
1211 } else
1212 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001213
1214 return false;
1215 }
1216 case glslang::EOpConstructMat2x2:
1217 case glslang::EOpConstructMat2x3:
1218 case glslang::EOpConstructMat2x4:
1219 case glslang::EOpConstructMat3x2:
1220 case glslang::EOpConstructMat3x3:
1221 case glslang::EOpConstructMat3x4:
1222 case glslang::EOpConstructMat4x2:
1223 case glslang::EOpConstructMat4x3:
1224 case glslang::EOpConstructMat4x4:
1225 case glslang::EOpConstructDMat2x2:
1226 case glslang::EOpConstructDMat2x3:
1227 case glslang::EOpConstructDMat2x4:
1228 case glslang::EOpConstructDMat3x2:
1229 case glslang::EOpConstructDMat3x3:
1230 case glslang::EOpConstructDMat3x4:
1231 case glslang::EOpConstructDMat4x2:
1232 case glslang::EOpConstructDMat4x3:
1233 case glslang::EOpConstructDMat4x4:
1234 isMatrix = true;
1235 // fall through
1236 case glslang::EOpConstructFloat:
1237 case glslang::EOpConstructVec2:
1238 case glslang::EOpConstructVec3:
1239 case glslang::EOpConstructVec4:
1240 case glslang::EOpConstructDouble:
1241 case glslang::EOpConstructDVec2:
1242 case glslang::EOpConstructDVec3:
1243 case glslang::EOpConstructDVec4:
1244 case glslang::EOpConstructBool:
1245 case glslang::EOpConstructBVec2:
1246 case glslang::EOpConstructBVec3:
1247 case glslang::EOpConstructBVec4:
1248 case glslang::EOpConstructInt:
1249 case glslang::EOpConstructIVec2:
1250 case glslang::EOpConstructIVec3:
1251 case glslang::EOpConstructIVec4:
1252 case glslang::EOpConstructUint:
1253 case glslang::EOpConstructUVec2:
1254 case glslang::EOpConstructUVec3:
1255 case glslang::EOpConstructUVec4:
1256 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001257 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001258 {
1259 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001260 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1262 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001263 if (node->getOp() == glslang::EOpConstructTextureSampler)
1264 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1265 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001266 std::vector<spv::Id> constituents;
1267 for (int c = 0; c < (int)arguments.size(); ++c)
1268 constituents.push_back(arguments[c]);
1269 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001270 } else if (isMatrix)
1271 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1272 else
1273 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001274
1275 builder.clearAccessChain();
1276 builder.setAccessChainRValue(constructed);
1277
1278 return false;
1279 }
1280
1281 // These six are component-wise compares with component-wise results.
1282 // Forward on to createBinaryOperation(), requesting a vector result.
1283 case glslang::EOpLessThan:
1284 case glslang::EOpGreaterThan:
1285 case glslang::EOpLessThanEqual:
1286 case glslang::EOpGreaterThanEqual:
1287 case glslang::EOpVectorEqual:
1288 case glslang::EOpVectorNotEqual:
1289 {
1290 // Map the operation to a binary
1291 binOp = node->getOp();
1292 reduceComparison = false;
1293 switch (node->getOp()) {
1294 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1295 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1296 default: binOp = node->getOp(); break;
1297 }
1298
1299 break;
1300 }
1301 case glslang::EOpMul:
1302 // compontent-wise matrix multiply
1303 binOp = glslang::EOpMul;
1304 break;
1305 case glslang::EOpOuterProduct:
1306 // two vectors multiplied to make a matrix
1307 binOp = glslang::EOpOuterProduct;
1308 break;
1309 case glslang::EOpDot:
1310 {
1311 // for scalar dot product, use multiply
1312 glslang::TIntermSequence& glslangOperands = node->getSequence();
1313 if (! glslangOperands[0]->getAsTyped()->isVector())
1314 binOp = glslang::EOpMul;
1315 break;
1316 }
1317 case glslang::EOpMod:
1318 // when an aggregate, this is the floating-point mod built-in function,
1319 // which can be emitted by the one in createBinaryOperation()
1320 binOp = glslang::EOpMod;
1321 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001322 case glslang::EOpEmitVertex:
1323 case glslang::EOpEndPrimitive:
1324 case glslang::EOpBarrier:
1325 case glslang::EOpMemoryBarrier:
1326 case glslang::EOpMemoryBarrierAtomicCounter:
1327 case glslang::EOpMemoryBarrierBuffer:
1328 case glslang::EOpMemoryBarrierImage:
1329 case glslang::EOpMemoryBarrierShared:
1330 case glslang::EOpGroupMemoryBarrier:
1331 noReturnValue = true;
1332 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1333 break;
1334
John Kessenich426394d2015-07-23 10:22:48 -06001335 case glslang::EOpAtomicAdd:
1336 case glslang::EOpAtomicMin:
1337 case glslang::EOpAtomicMax:
1338 case glslang::EOpAtomicAnd:
1339 case glslang::EOpAtomicOr:
1340 case glslang::EOpAtomicXor:
1341 case glslang::EOpAtomicExchange:
1342 case glslang::EOpAtomicCompSwap:
1343 atomic = true;
1344 break;
1345
John Kessenich140f3df2015-06-26 16:58:36 -06001346 default:
1347 break;
1348 }
1349
1350 //
1351 // See if it maps to a regular operation.
1352 //
John Kessenich140f3df2015-06-26 16:58:36 -06001353 if (binOp != glslang::EOpNull) {
1354 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1355 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1356 assert(left && right);
1357
1358 builder.clearAccessChain();
1359 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001360 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001361
1362 builder.clearAccessChain();
1363 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001364 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001365
1366 result = createBinaryOperation(binOp, precision,
1367 convertGlslangToSpvType(node->getType()), leftId, rightId,
1368 left->getType().getBasicType(), reduceComparison);
1369
1370 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001371 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001372 builder.clearAccessChain();
1373 builder.setAccessChainRValue(result);
1374
1375 return false;
1376 }
1377
John Kessenich426394d2015-07-23 10:22:48 -06001378 //
1379 // Create the list of operands.
1380 //
John Kessenich140f3df2015-06-26 16:58:36 -06001381 glslang::TIntermSequence& glslangOperands = node->getSequence();
1382 std::vector<spv::Id> operands;
1383 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1384 builder.clearAccessChain();
1385 glslangOperands[arg]->traverse(this);
1386
1387 // special case l-value operands; there are just a few
1388 bool lvalue = false;
1389 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001390 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001391 case glslang::EOpModf:
1392 if (arg == 1)
1393 lvalue = true;
1394 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001395 case glslang::EOpInterpolateAtSample:
1396 case glslang::EOpInterpolateAtOffset:
1397 if (arg == 0)
1398 lvalue = true;
1399 break;
Rex Xud4782c12015-09-06 16:30:11 +08001400 case glslang::EOpAtomicAdd:
1401 case glslang::EOpAtomicMin:
1402 case glslang::EOpAtomicMax:
1403 case glslang::EOpAtomicAnd:
1404 case glslang::EOpAtomicOr:
1405 case glslang::EOpAtomicXor:
1406 case glslang::EOpAtomicExchange:
1407 case glslang::EOpAtomicCompSwap:
1408 if (arg == 0)
1409 lvalue = true;
1410 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001411 case glslang::EOpAddCarry:
1412 case glslang::EOpSubBorrow:
1413 if (arg == 2)
1414 lvalue = true;
1415 break;
1416 case glslang::EOpUMulExtended:
1417 case glslang::EOpIMulExtended:
1418 if (arg >= 2)
1419 lvalue = true;
1420 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001421 default:
1422 break;
1423 }
1424 if (lvalue)
1425 operands.push_back(builder.accessChainGetLValue());
1426 else
John Kessenich32cfd492016-02-02 12:37:46 -07001427 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001428 }
John Kessenich426394d2015-07-23 10:22:48 -06001429
1430 if (atomic) {
1431 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001432 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001433 } else {
1434 // Pass through to generic operations.
1435 switch (glslangOperands.size()) {
1436 case 0:
1437 result = createNoArgOperation(node->getOp());
1438 break;
1439 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001440 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001441 break;
1442 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001443 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001444 break;
1445 }
John Kessenich140f3df2015-06-26 16:58:36 -06001446 }
1447
1448 if (noReturnValue)
1449 return false;
1450
1451 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001452 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001453 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001454 } else {
1455 builder.clearAccessChain();
1456 builder.setAccessChainRValue(result);
1457 return false;
1458 }
1459}
1460
1461bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1462{
1463 // This path handles both if-then-else and ?:
1464 // The if-then-else has a node type of void, while
1465 // ?: has a non-void node type
1466 spv::Id result = 0;
1467 if (node->getBasicType() != glslang::EbtVoid) {
1468 // don't handle this as just on-the-fly temporaries, because there will be two names
1469 // and better to leave SSA to later passes
1470 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1471 }
1472
1473 // emit the condition before doing anything with selection
1474 node->getCondition()->traverse(this);
1475
1476 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001477 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001478
1479 if (node->getTrueBlock()) {
1480 // emit the "then" statement
1481 node->getTrueBlock()->traverse(this);
1482 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001483 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001484 }
1485
1486 if (node->getFalseBlock()) {
1487 ifBuilder.makeBeginElse();
1488 // emit the "else" statement
1489 node->getFalseBlock()->traverse(this);
1490 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001491 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001492 }
1493
1494 ifBuilder.makeEndIf();
1495
1496 if (result) {
1497 // GLSL only has r-values as the result of a :?, but
1498 // if we have an l-value, that can be more efficient if it will
1499 // become the base of a complex r-value expression, because the
1500 // next layer copies r-values into memory to use the access-chain mechanism
1501 builder.clearAccessChain();
1502 builder.setAccessChainLValue(result);
1503 }
1504
1505 return false;
1506}
1507
1508bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1509{
1510 // emit and get the condition before doing anything with switch
1511 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001512 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001513
1514 // browse the children to sort out code segments
1515 int defaultSegment = -1;
1516 std::vector<TIntermNode*> codeSegments;
1517 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1518 std::vector<int> caseValues;
1519 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1520 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1521 TIntermNode* child = *c;
1522 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001523 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001524 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001525 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001526 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1527 } else
1528 codeSegments.push_back(child);
1529 }
1530
1531 // handle the case where the last code segment is missing, due to no code
1532 // statements between the last case and the end of the switch statement
1533 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1534 (int)codeSegments.size() == defaultSegment)
1535 codeSegments.push_back(nullptr);
1536
1537 // make the switch statement
1538 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001539 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001540
1541 // emit all the code in the segments
1542 breakForLoop.push(false);
1543 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1544 builder.nextSwitchSegment(segmentBlocks, s);
1545 if (codeSegments[s])
1546 codeSegments[s]->traverse(this);
1547 else
1548 builder.addSwitchBreak();
1549 }
1550 breakForLoop.pop();
1551
1552 builder.endSwitch(segmentBlocks);
1553
1554 return false;
1555}
1556
1557void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1558{
1559 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001560 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001561
1562 builder.clearAccessChain();
1563 builder.setAccessChainRValue(constant);
1564}
1565
1566bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1567{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001568 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001569 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001570 // Spec requires back edges to target header blocks, and every header block
1571 // must dominate its merge block. Make a header block first to ensure these
1572 // conditions are met. By definition, it will contain OpLoopMerge, followed
1573 // by a block-ending branch. But we don't want to put any other body/test
1574 // instructions in it, since the body/test may have arbitrary instructions,
1575 // including merges of its own.
1576 builder.setBuildPoint(&blocks.head);
1577 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001578 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001579 spv::Block& test = builder.makeNewBlock();
1580 builder.createBranch(&test);
1581
1582 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001584 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001585 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001586 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1587
1588 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001589 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001590 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001591 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001592 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001593 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001594
1595 builder.setBuildPoint(&blocks.continue_target);
1596 if (node->getTerminal())
1597 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001598 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001599 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001600 builder.createBranch(&blocks.body);
1601
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001602 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001603 builder.setBuildPoint(&blocks.body);
1604 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001605 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001606 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001607 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001608
1609 builder.setBuildPoint(&blocks.continue_target);
1610 if (node->getTerminal())
1611 node->getTerminal()->traverse(this);
1612 if (node->getTest()) {
1613 node->getTest()->traverse(this);
1614 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001615 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001616 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001617 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001618 // TODO: unless there was a break/return/discard instruction
1619 // somewhere in the body, this is an infinite loop, so we should
1620 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001621 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001622 }
John Kessenich140f3df2015-06-26 16:58:36 -06001623 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001624 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001625 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001626 return false;
1627}
1628
1629bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1630{
1631 if (node->getExpression())
1632 node->getExpression()->traverse(this);
1633
1634 switch (node->getFlowOp()) {
1635 case glslang::EOpKill:
1636 builder.makeDiscard();
1637 break;
1638 case glslang::EOpBreak:
1639 if (breakForLoop.top())
1640 builder.createLoopExit();
1641 else
1642 builder.addSwitchBreak();
1643 break;
1644 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001645 builder.createLoopContinue();
1646 break;
1647 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001648 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001649 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001650 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001651 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001652
1653 builder.clearAccessChain();
1654 break;
1655
1656 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001657 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001658 break;
1659 }
1660
1661 return false;
1662}
1663
1664spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1665{
1666 // First, steer off constants, which are not SPIR-V variables, but
1667 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001668 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001669 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001670 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001671 }
1672
1673 // Now, handle actual variables
1674 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1675 spv::Id spvType = convertGlslangToSpvType(node->getType());
1676
1677 const char* name = node->getName().c_str();
1678 if (glslang::IsAnonymous(name))
1679 name = "";
1680
1681 return builder.createVariable(storageClass, spvType, name);
1682}
1683
1684// Return type Id of the sampled type.
1685spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1686{
1687 switch (sampler.type) {
1688 case glslang::EbtFloat: return builder.makeFloatType(32);
1689 case glslang::EbtInt: return builder.makeIntType(32);
1690 case glslang::EbtUint: return builder.makeUintType(32);
1691 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001692 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001693 return builder.makeFloatType(32);
1694 }
1695}
1696
John Kessenich3ac051e2015-12-20 11:29:16 -07001697// Convert from a glslang type to an SPV type, by calling into a
1698// recursive version of this function. This establishes the inherited
1699// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001700spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1701{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001702 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001703}
1704
1705// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001706// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001707spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001708{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001709 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001710
1711 switch (type.getBasicType()) {
1712 case glslang::EbtVoid:
1713 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001714 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001715 break;
1716 case glslang::EbtFloat:
1717 spvType = builder.makeFloatType(32);
1718 break;
1719 case glslang::EbtDouble:
1720 spvType = builder.makeFloatType(64);
1721 break;
1722 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001723 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1724 // a 32-bit int where non-0 means true.
1725 if (explicitLayout != glslang::ElpNone)
1726 spvType = builder.makeUintType(32);
1727 else
1728 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001729 break;
1730 case glslang::EbtInt:
1731 spvType = builder.makeIntType(32);
1732 break;
1733 case glslang::EbtUint:
1734 spvType = builder.makeUintType(32);
1735 break;
John Kessenich426394d2015-07-23 10:22:48 -06001736 case glslang::EbtAtomicUint:
1737 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1738 spvType = builder.makeUintType(32);
1739 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001740 case glslang::EbtSampler:
1741 {
1742 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001743 if (sampler.sampler) {
1744 // pure sampler
1745 spvType = builder.makeSamplerType();
1746 } else {
1747 // an image is present, make its type
1748 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1749 sampler.image ? 2 : 1, TranslateImageFormat(type));
1750 if (sampler.combined) {
1751 // already has both image and sampler, make the combined type
1752 spvType = builder.makeSampledImageType(spvType);
1753 }
John Kessenich55e7d112015-11-15 21:33:39 -07001754 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001755 }
John Kessenich140f3df2015-06-26 16:58:36 -06001756 break;
1757 case glslang::EbtStruct:
1758 case glslang::EbtBlock:
1759 {
1760 // If we've seen this struct type, return it
1761 const glslang::TTypeList* glslangStruct = type.getStruct();
1762 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001763
1764 // Try to share structs for different layouts, but not yet for other
1765 // kinds of qualification (primarily not yet including interpolant qualification).
1766 if (! HasNonLayoutQualifiers(qualifier))
1767 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1768 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001769 break;
1770
1771 // else, we haven't seen it...
1772
1773 // Create a vector of struct types for SPIR-V to consume
1774 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1775 if (type.getBasicType() == glslang::EbtBlock)
1776 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001777 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001778 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1779 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1780 if (glslangType.hiddenMember()) {
1781 ++memberDelta;
1782 if (type.getBasicType() == glslang::EbtBlock)
1783 memberRemapper[glslangStruct][i] = -1;
1784 } else {
1785 if (type.getBasicType() == glslang::EbtBlock)
1786 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001787 // modify just this child's view of the qualifier
1788 glslang::TQualifier subQualifier = glslangType.getQualifier();
1789 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001790
1791 // manually inherit location; it's more complex
1792 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1793 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1794 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001795 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001796
1797 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001798 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001799 }
1800 }
1801
1802 // Make the SPIR-V type
1803 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001804 if (! HasNonLayoutQualifiers(qualifier))
1805 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001806
1807 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001808 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001809 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001810 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1811 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1812 int member = i;
1813 if (type.getBasicType() == glslang::EbtBlock)
1814 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001815
John Kesseniche0b6cad2015-12-24 10:30:13 -07001816 // modify just this child's view of the qualifier
1817 glslang::TQualifier subQualifier = glslangType.getQualifier();
1818 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001819
John Kessenich140f3df2015-06-26 16:58:36 -06001820 // using -1 above to indicate a hidden member
1821 if (member >= 0) {
1822 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001823 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001824 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001825 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1826 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001827
Rex Xu1da878f2016-02-21 20:59:01 +08001828 if (qualifier.storage == glslang::EvqBuffer) {
1829 std::vector<spv::Decoration> memory;
1830 TranslateMemoryDecoration(subQualifier, memory);
1831 for (unsigned int i = 0; i < memory.size(); ++i)
1832 addMemberDecoration(spvType, member, memory[i]);
1833 }
1834
John Kessenich09677482016-02-19 12:21:50 -07001835 // compute location decoration; tricky based on whether inheritance is at play
1836 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1837 // probably move to the linker stage of the front end proper, and just have the
1838 // answer sitting already distributed throughout the individual member locations.
1839 int location = -1; // will only decorate if present or inherited
1840 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1841 location = subQualifier.layoutLocation;
1842 else if (qualifier.hasLocation()) // inheritance
1843 location = qualifier.layoutLocation + locationOffset;
1844 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001845 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001846 if (location >= 0)
1847 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1848
1849 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001850 if (glslangType.getQualifier().hasComponent())
1851 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1852 if (glslangType.getQualifier().hasXfbOffset())
1853 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001854 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001855 // figure out what to do with offset, which is accumulating
1856 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001857 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001858 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001859 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001860 offset = nextOffset;
1861 }
John Kessenich140f3df2015-06-26 16:58:36 -06001862
John Kessenichf85e8062015-12-19 13:57:10 -07001863 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001864 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001865
John Kessenich140f3df2015-06-26 16:58:36 -06001866 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001867 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1868 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001869 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001870 }
1871 }
1872
1873 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001874 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001875 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001876 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001877 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001878 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001879 }
John Kessenich140f3df2015-06-26 16:58:36 -06001880 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001881 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001882 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001883 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001884 if (type.getQualifier().hasXfbBuffer())
1885 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1886 }
1887 }
1888 break;
1889 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001890 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001891 break;
1892 }
1893
1894 if (type.isMatrix())
1895 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1896 else {
1897 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1898 if (type.getVectorSize() > 1)
1899 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1900 }
1901
1902 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001903 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1904
John Kessenichc9a80832015-09-12 12:17:44 -06001905 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001906 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001907 // We need to decorate array strides for types needing explicit layout, except blocks.
1908 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001909 // Use a dummy glslang type for querying internal strides of
1910 // arrays of arrays, but using just a one-dimensional array.
1911 glslang::TType simpleArrayType(type, 0); // deference type of the array
1912 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1913 simpleArrayType.getArraySizes().dereference();
1914
1915 // Will compute the higher-order strides here, rather than making a whole
1916 // pile of types and doing repetitive recursion on their contents.
1917 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1918 }
John Kessenichf8842e52016-01-04 19:22:56 -07001919
1920 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001921 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001922 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001923 if (stride > 0)
1924 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001925 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001926 }
1927 } else {
1928 // single-dimensional array, and don't yet have stride
1929
John Kessenichf8842e52016-01-04 19:22:56 -07001930 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001931 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1932 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001933 }
John Kessenich31ed4832015-09-09 17:51:38 -06001934
John Kessenichc9a80832015-09-12 12:17:44 -06001935 // Do the outer dimension, which might not be known for a runtime-sized array
1936 if (type.isRuntimeSizedArray()) {
1937 spvType = builder.makeRuntimeArray(spvType);
1938 } else {
1939 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001940 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001941 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001942 if (stride > 0)
1943 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001944 }
1945
1946 return spvType;
1947}
1948
John Kessenich6c292d32016-02-15 20:58:50 -07001949// Turn the expression forming the array size into an id.
1950// This is not quite trivial, because of specialization constants.
1951// Sometimes, a raw constant is turned into an Id, and sometimes
1952// a specialization constant expression is.
1953spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1954{
1955 // First, see if this is sized with a node, meaning a specialization constant:
1956 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1957 if (specNode != nullptr) {
1958 builder.clearAccessChain();
qining40887662016-04-03 22:20:42 -04001959 // SpecConstantOpModeGuard set_to_spec_const_mode(&builder);
John Kessenich6c292d32016-02-15 20:58:50 -07001960 specNode->traverse(this);
1961 return accessChainLoad(specNode->getAsTyped()->getType());
1962 }
1963
1964 // Otherwise, need a compile-time (front end) size, get it:
1965 int size = arraySizes.getDimSize(dim);
1966 assert(size > 0);
1967 return builder.makeUintConstant(size);
1968}
1969
John Kessenich103bef92016-02-08 21:38:15 -07001970// Wrap the builder's accessChainLoad to:
1971// - localize handling of RelaxedPrecision
1972// - use the SPIR-V inferred type instead of another conversion of the glslang type
1973// (avoids unnecessary work and possible type punning for structures)
1974// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001975spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1976{
John Kessenich103bef92016-02-08 21:38:15 -07001977 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1978 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1979
1980 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001981 if (type.getBasicType() == glslang::EbtBool) {
1982 if (builder.isScalarType(nominalTypeId)) {
1983 // Conversion for bool
1984 spv::Id boolType = builder.makeBoolType();
1985 if (nominalTypeId != boolType)
1986 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1987 } else if (builder.isVectorType(nominalTypeId)) {
1988 // Conversion for bvec
1989 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1990 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1991 if (nominalTypeId != bvecType)
1992 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1993 }
1994 }
John Kessenich103bef92016-02-08 21:38:15 -07001995
1996 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001997}
1998
Rex Xu27253232016-02-23 17:51:09 +08001999// Wrap the builder's accessChainStore to:
2000// - do conversion of concrete to abstract type
2001void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2002{
2003 // Need to convert to abstract types when necessary
2004 if (type.getBasicType() == glslang::EbtBool) {
2005 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2006
2007 if (builder.isScalarType(nominalTypeId)) {
2008 // Conversion for bool
2009 spv::Id boolType = builder.makeBoolType();
2010 if (nominalTypeId != boolType) {
2011 spv::Id zero = builder.makeUintConstant(0);
2012 spv::Id one = builder.makeUintConstant(1);
2013 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2014 }
2015 } else if (builder.isVectorType(nominalTypeId)) {
2016 // Conversion for bvec
2017 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2018 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2019 if (nominalTypeId != bvecType) {
2020 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2021 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2022 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2023 }
2024 }
2025 }
2026
2027 builder.accessChainStore(rvalue);
2028}
2029
John Kessenichf85e8062015-12-19 13:57:10 -07002030// Decide whether or not this type should be
2031// decorated with offsets and strides, and if so
2032// whether std140 or std430 rules should be applied.
2033glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002034{
John Kessenichf85e8062015-12-19 13:57:10 -07002035 // has to be a block
2036 if (type.getBasicType() != glslang::EbtBlock)
2037 return glslang::ElpNone;
2038
2039 // has to be a uniform or buffer block
2040 if (type.getQualifier().storage != glslang::EvqUniform &&
2041 type.getQualifier().storage != glslang::EvqBuffer)
2042 return glslang::ElpNone;
2043
2044 // return the layout to use
2045 switch (type.getQualifier().layoutPacking) {
2046 case glslang::ElpStd140:
2047 case glslang::ElpStd430:
2048 return type.getQualifier().layoutPacking;
2049 default:
2050 return glslang::ElpNone;
2051 }
John Kessenich31ed4832015-09-09 17:51:38 -06002052}
2053
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002054// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002055int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002056{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002057 int size;
John Kessenich49987892015-12-29 17:11:44 -07002058 int stride;
2059 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002060
2061 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002062}
2063
John Kessenich49987892015-12-29 17:11:44 -07002064// 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 -07002065// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002066int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002067{
John Kessenich49987892015-12-29 17:11:44 -07002068 glslang::TType elementType;
2069 elementType.shallowCopy(matrixType);
2070 elementType.clearArraySizes();
2071
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002072 int size;
John Kessenich49987892015-12-29 17:11:44 -07002073 int stride;
2074 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2075
2076 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002077}
2078
John Kessenich5e4b1242015-08-06 22:53:06 -06002079// Given a member type of a struct, realign the current offset for it, and compute
2080// the next (not yet aligned) offset for the next member, which will get aligned
2081// on the next call.
2082// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2083// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2084// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002085void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002086 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002087{
2088 // this will get a positive value when deemed necessary
2089 nextOffset = -1;
2090
John Kessenich5e4b1242015-08-06 22:53:06 -06002091 // override anything in currentOffset with user-set offset
2092 if (memberType.getQualifier().hasOffset())
2093 currentOffset = memberType.getQualifier().layoutOffset;
2094
2095 // It could be that current linker usage in glslang updated all the layoutOffset,
2096 // in which case the following code does not matter. But, that's not quite right
2097 // once cross-compilation unit GLSL validation is done, as the original user
2098 // settings are needed in layoutOffset, and then the following will come into play.
2099
John Kessenichf85e8062015-12-19 13:57:10 -07002100 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002101 if (! memberType.getQualifier().hasOffset())
2102 currentOffset = -1;
2103
2104 return;
2105 }
2106
John Kessenichf85e8062015-12-19 13:57:10 -07002107 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002108 if (currentOffset < 0)
2109 currentOffset = 0;
2110
2111 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2112 // but possibly not yet correctly aligned.
2113
2114 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002115 int dummyStride;
2116 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002117 glslang::RoundToPow2(currentOffset, memberAlignment);
2118 nextOffset = currentOffset + memberSize;
2119}
2120
John Kessenich140f3df2015-06-26 16:58:36 -06002121bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2122{
John Kessenich4d65ee32016-03-12 18:17:47 -07002123 // have to ignore mangling and just look at the base name
2124 int firstOpen = node->getName().find('(');
2125 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002126}
2127
2128// Make all the functions, skeletally, without actually visiting their bodies.
2129void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2130{
2131 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2132 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2133 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2134 continue;
2135
2136 // We're on a user function. Set up the basic interface for the function now,
2137 // so that it's available to call.
2138 // Translating the body will happen later.
2139 //
2140 // Typically (except for a "const in" parameter), an address will be passed to the
2141 // function. What it is an address of varies:
2142 //
2143 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2144 // so that write needs to be to a copy, hence the address of a copy works.
2145 //
2146 // - "const in" parameters can just be the r-value, as no writes need occur.
2147 //
2148 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2149 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2150
2151 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002152 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002153 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2154
2155 for (int p = 0; p < (int)parameters.size(); ++p) {
2156 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2157 spv::Id typeId = convertGlslangToSpvType(paramType);
2158 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2159 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2160 else
2161 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002162 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002163 paramTypes.push_back(typeId);
2164 }
2165
2166 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002167 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2168 convertGlslangToSpvType(glslFunction->getType()),
2169 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002170
2171 // Track function to emit/call later
2172 functionMap[glslFunction->getName().c_str()] = function;
2173
2174 // Set the parameter id's
2175 for (int p = 0; p < (int)parameters.size(); ++p) {
2176 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2177 // give a name too
2178 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2179 }
2180 }
2181}
2182
2183// Process all the initializers, while skipping the functions and link objects
2184void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2185{
2186 builder.setBuildPoint(shaderEntry->getLastBlock());
2187 for (int i = 0; i < (int)initializers.size(); ++i) {
2188 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2189 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2190
2191 // We're on a top-level node that's not a function. Treat as an initializer, whose
2192 // code goes into the beginning of main.
2193 initializer->traverse(this);
2194 }
2195 }
2196}
2197
2198// Process all the functions, while skipping initializers.
2199void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2200{
2201 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2202 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2203 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2204 node->traverse(this);
2205 }
2206}
2207
2208void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2209{
2210 // SPIR-V functions should already be in the functionMap from the prepass
2211 // that called makeFunctions().
2212 spv::Function* function = functionMap[node->getName().c_str()];
2213 spv::Block* functionBlock = function->getEntryBlock();
2214 builder.setBuildPoint(functionBlock);
2215}
2216
Rex Xu04db3f52015-09-16 11:44:02 +08002217void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002218{
Rex Xufc618912015-09-09 16:42:49 +08002219 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002220
2221 glslang::TSampler sampler = {};
2222 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002223 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002224 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2225 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2226 }
2227
John Kessenich140f3df2015-06-26 16:58:36 -06002228 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2229 builder.clearAccessChain();
2230 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002231
2232 // Special case l-value operands
2233 bool lvalue = false;
2234 switch (node.getOp()) {
2235 case glslang::EOpImageAtomicAdd:
2236 case glslang::EOpImageAtomicMin:
2237 case glslang::EOpImageAtomicMax:
2238 case glslang::EOpImageAtomicAnd:
2239 case glslang::EOpImageAtomicOr:
2240 case glslang::EOpImageAtomicXor:
2241 case glslang::EOpImageAtomicExchange:
2242 case glslang::EOpImageAtomicCompSwap:
2243 if (i == 0)
2244 lvalue = true;
2245 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002246 case glslang::EOpSparseImageLoad:
2247 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2248 lvalue = true;
2249 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002250 case glslang::EOpSparseTexture:
2251 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2252 lvalue = true;
2253 break;
2254 case glslang::EOpSparseTextureClamp:
2255 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2256 lvalue = true;
2257 break;
2258 case glslang::EOpSparseTextureLod:
2259 case glslang::EOpSparseTextureOffset:
2260 if (i == 3)
2261 lvalue = true;
2262 break;
2263 case glslang::EOpSparseTextureFetch:
2264 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2265 lvalue = true;
2266 break;
2267 case glslang::EOpSparseTextureFetchOffset:
2268 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2269 lvalue = true;
2270 break;
2271 case glslang::EOpSparseTextureLodOffset:
2272 case glslang::EOpSparseTextureGrad:
2273 case glslang::EOpSparseTextureOffsetClamp:
2274 if (i == 4)
2275 lvalue = true;
2276 break;
2277 case glslang::EOpSparseTextureGradOffset:
2278 case glslang::EOpSparseTextureGradClamp:
2279 if (i == 5)
2280 lvalue = true;
2281 break;
2282 case glslang::EOpSparseTextureGradOffsetClamp:
2283 if (i == 6)
2284 lvalue = true;
2285 break;
2286 case glslang::EOpSparseTextureGather:
2287 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2288 lvalue = true;
2289 break;
2290 case glslang::EOpSparseTextureGatherOffset:
2291 case glslang::EOpSparseTextureGatherOffsets:
2292 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2293 lvalue = true;
2294 break;
Rex Xufc618912015-09-09 16:42:49 +08002295 default:
2296 break;
2297 }
2298
Rex Xu6b86d492015-09-16 17:48:22 +08002299 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002300 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002301 else
John Kessenich32cfd492016-02-02 12:37:46 -07002302 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002303 }
2304}
2305
John Kessenichfc51d282015-08-19 13:34:18 -06002306void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002307{
John Kessenichfc51d282015-08-19 13:34:18 -06002308 builder.clearAccessChain();
2309 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002310 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002311}
John Kessenich140f3df2015-06-26 16:58:36 -06002312
John Kessenichfc51d282015-08-19 13:34:18 -06002313spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2314{
Rex Xufc618912015-09-09 16:42:49 +08002315 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002316 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002317 }
2318
John Kessenichfc51d282015-08-19 13:34:18 -06002319 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002320 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2321 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2322 std::vector<spv::Id> arguments;
2323 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002324 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002325 else
2326 translateArguments(*node->getAsUnaryNode(), arguments);
2327 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2328
2329 spv::Builder::TextureParameters params = { };
2330 params.sampler = arguments[0];
2331
Rex Xu04db3f52015-09-16 11:44:02 +08002332 glslang::TCrackedTextureOp cracked;
2333 node->crackTexture(sampler, cracked);
2334
John Kessenichfc51d282015-08-19 13:34:18 -06002335 // Check for queries
2336 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002337 // a sampled image needs to have the image extracted first
2338 if (builder.isSampledImage(params.sampler))
2339 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002340 switch (node->getOp()) {
2341 case glslang::EOpImageQuerySize:
2342 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002343 if (arguments.size() > 1) {
2344 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002345 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002346 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002347 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002348 case glslang::EOpImageQuerySamples:
2349 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002350 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002351 case glslang::EOpTextureQueryLod:
2352 params.coords = arguments[1];
2353 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2354 case glslang::EOpTextureQueryLevels:
2355 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002356 case glslang::EOpSparseTexelsResident:
2357 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002358 default:
2359 assert(0);
2360 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002361 }
John Kessenich140f3df2015-06-26 16:58:36 -06002362 }
2363
Rex Xufc618912015-09-09 16:42:49 +08002364 // Check for image functions other than queries
2365 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002366 std::vector<spv::Id> operands;
2367 auto opIt = arguments.begin();
2368 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002369
2370 // Handle subpass operations
2371 // TODO: GLSL should change to have the "MS" only on the type rather than the
2372 // built-in function.
2373 if (cracked.subpass) {
2374 // add on the (0,0) coordinate
2375 spv::Id zero = builder.makeIntConstant(0);
2376 std::vector<spv::Id> comps;
2377 comps.push_back(zero);
2378 comps.push_back(zero);
2379 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2380 if (sampler.ms) {
2381 operands.push_back(spv::ImageOperandsSampleMask);
2382 operands.push_back(*(opIt++));
2383 }
2384 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2385 }
2386
John Kessenich56bab042015-09-16 10:54:31 -06002387 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002388 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002389 if (sampler.ms) {
2390 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002391 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002392 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002393 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2394 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002395 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002396 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002397 if (sampler.ms) {
2398 operands.push_back(*(opIt + 1));
2399 operands.push_back(spv::ImageOperandsSampleMask);
2400 operands.push_back(*opIt);
2401 } else
2402 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002403 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002404 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2405 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002406 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002407 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2408 builder.addCapability(spv::CapabilitySparseResidency);
2409 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2410 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2411
2412 if (sampler.ms) {
2413 operands.push_back(spv::ImageOperandsSampleMask);
2414 operands.push_back(*opIt++);
2415 }
2416
2417 // Create the return type that was a special structure
2418 spv::Id texelOut = *opIt;
2419 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2420 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2421 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2422
2423 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2424
2425 // Decode the return type
2426 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2427 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002428 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002429 // Process image atomic operations
2430
2431 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2432 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002433 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002434
Rex Xufc618912015-09-09 16:42:49 +08002435 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002436 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002437
2438 std::vector<spv::Id> operands;
2439 operands.push_back(pointer);
2440 for (; opIt != arguments.end(); ++opIt)
2441 operands.push_back(*opIt);
2442
Rex Xu04db3f52015-09-16 11:44:02 +08002443 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002444 }
2445 }
2446
2447 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002448 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002449 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2450
John Kessenichfc51d282015-08-19 13:34:18 -06002451 // check for bias argument
2452 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002453 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002454 int nonBiasArgCount = 2;
2455 if (cracked.offset)
2456 ++nonBiasArgCount;
2457 if (cracked.grad)
2458 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002459 if (cracked.lodClamp)
2460 ++nonBiasArgCount;
2461 if (sparse)
2462 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002463
2464 if ((int)arguments.size() > nonBiasArgCount)
2465 bias = true;
2466 }
2467
John Kessenichfc51d282015-08-19 13:34:18 -06002468 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002469
John Kessenichfc51d282015-08-19 13:34:18 -06002470 params.coords = arguments[1];
2471 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002472 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002473
2474 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002475 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002476 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002477 ++extraArgs;
2478 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002479 params.Dref = arguments[2];
2480 ++extraArgs;
2481 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002482 std::vector<spv::Id> indexes;
2483 int comp;
2484 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002485 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002486 else
2487 comp = builder.getNumComponents(params.coords) - 1;
2488 indexes.push_back(comp);
2489 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2490 }
2491 if (cracked.lod) {
2492 params.lod = arguments[2];
2493 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002494 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2495 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2496 noImplicitLod = true;
2497 }
2498 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002499 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002500 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002501 }
2502 if (cracked.grad) {
2503 params.gradX = arguments[2 + extraArgs];
2504 params.gradY = arguments[3 + extraArgs];
2505 extraArgs += 2;
2506 }
John Kessenich55e7d112015-11-15 21:33:39 -07002507 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002508 params.offset = arguments[2 + extraArgs];
2509 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002510 } else if (cracked.offsets) {
2511 params.offsets = arguments[2 + extraArgs];
2512 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002513 }
Rex Xu48edadf2015-12-31 16:11:41 +08002514 if (cracked.lodClamp) {
2515 params.lodClamp = arguments[2 + extraArgs];
2516 ++extraArgs;
2517 }
2518 if (sparse) {
2519 params.texelOut = arguments[2 + extraArgs];
2520 ++extraArgs;
2521 }
John Kessenichfc51d282015-08-19 13:34:18 -06002522 if (bias) {
2523 params.bias = arguments[2 + extraArgs];
2524 ++extraArgs;
2525 }
John Kessenich55e7d112015-11-15 21:33:39 -07002526 if (cracked.gather && ! sampler.shadow) {
2527 // default component is 0, if missing, otherwise an argument
2528 if (2 + extraArgs < (int)arguments.size()) {
2529 params.comp = arguments[2 + extraArgs];
2530 ++extraArgs;
2531 } else {
2532 params.comp = builder.makeIntConstant(0);
2533 }
2534 }
John Kessenichfc51d282015-08-19 13:34:18 -06002535
John Kessenich019f08f2016-02-15 15:40:42 -07002536 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002537}
2538
2539spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2540{
2541 // Grab the function's pointer from the previously created function
2542 spv::Function* function = functionMap[node->getName().c_str()];
2543 if (! function)
2544 return 0;
2545
2546 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2547 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2548
2549 // See comments in makeFunctions() for details about the semantics for parameter passing.
2550 //
2551 // These imply we need a four step process:
2552 // 1. Evaluate the arguments
2553 // 2. Allocate and make copies of in, out, and inout arguments
2554 // 3. Make the call
2555 // 4. Copy back the results
2556
2557 // 1. Evaluate the arguments
2558 std::vector<spv::Builder::AccessChain> lValues;
2559 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002560 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002561 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2562 // build l-value
2563 builder.clearAccessChain();
2564 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002565 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002566 // keep outputs as l-values, evaluate input-only as r-values
2567 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2568 // save l-value
2569 lValues.push_back(builder.getAccessChain());
2570 } else {
2571 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002572 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002573 }
2574 }
2575
2576 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2577 // copy the original into that space.
2578 //
2579 // Also, build up the list of actual arguments to pass in for the call
2580 int lValueCount = 0;
2581 int rValueCount = 0;
2582 std::vector<spv::Id> spvArgs;
2583 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2584 spv::Id arg;
2585 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2586 // need space to hold the copy
2587 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2588 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2589 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2590 // need to copy the input into output space
2591 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002592 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002593 builder.createStore(copy, arg);
2594 }
2595 ++lValueCount;
2596 } else {
2597 arg = rValues[rValueCount];
2598 ++rValueCount;
2599 }
2600 spvArgs.push_back(arg);
2601 }
2602
2603 // 3. Make the call.
2604 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002605 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002606
2607 // 4. Copy back out an "out" arguments.
2608 lValueCount = 0;
2609 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2610 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2611 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2612 spv::Id copy = builder.createLoad(spvArgs[a]);
2613 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002614 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002615 }
2616 ++lValueCount;
2617 }
2618 }
2619
2620 return result;
2621}
2622
2623// Translate AST operation to SPV operation, already having SPV-based operands/types.
2624spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2625 spv::Id typeId, spv::Id left, spv::Id right,
2626 glslang::TBasicType typeProxy, bool reduceComparison)
2627{
2628 bool isUnsigned = typeProxy == glslang::EbtUint;
2629 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2630
2631 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002632 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002633 bool comparison = false;
2634
2635 switch (op) {
2636 case glslang::EOpAdd:
2637 case glslang::EOpAddAssign:
2638 if (isFloat)
2639 binOp = spv::OpFAdd;
2640 else
2641 binOp = spv::OpIAdd;
2642 break;
2643 case glslang::EOpSub:
2644 case glslang::EOpSubAssign:
2645 if (isFloat)
2646 binOp = spv::OpFSub;
2647 else
2648 binOp = spv::OpISub;
2649 break;
2650 case glslang::EOpMul:
2651 case glslang::EOpMulAssign:
2652 if (isFloat)
2653 binOp = spv::OpFMul;
2654 else
2655 binOp = spv::OpIMul;
2656 break;
2657 case glslang::EOpVectorTimesScalar:
2658 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002659 if (isFloat) {
2660 if (builder.isVector(right))
2661 std::swap(left, right);
2662 assert(builder.isScalar(right));
2663 needMatchingVectors = false;
2664 binOp = spv::OpVectorTimesScalar;
2665 } else
2666 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002667 break;
2668 case glslang::EOpVectorTimesMatrix:
2669 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002670 binOp = spv::OpVectorTimesMatrix;
2671 break;
2672 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002673 binOp = spv::OpMatrixTimesVector;
2674 break;
2675 case glslang::EOpMatrixTimesScalar:
2676 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002677 binOp = spv::OpMatrixTimesScalar;
2678 break;
2679 case glslang::EOpMatrixTimesMatrix:
2680 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002681 binOp = spv::OpMatrixTimesMatrix;
2682 break;
2683 case glslang::EOpOuterProduct:
2684 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002685 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002686 break;
2687
2688 case glslang::EOpDiv:
2689 case glslang::EOpDivAssign:
2690 if (isFloat)
2691 binOp = spv::OpFDiv;
2692 else if (isUnsigned)
2693 binOp = spv::OpUDiv;
2694 else
2695 binOp = spv::OpSDiv;
2696 break;
2697 case glslang::EOpMod:
2698 case glslang::EOpModAssign:
2699 if (isFloat)
2700 binOp = spv::OpFMod;
2701 else if (isUnsigned)
2702 binOp = spv::OpUMod;
2703 else
2704 binOp = spv::OpSMod;
2705 break;
2706 case glslang::EOpRightShift:
2707 case glslang::EOpRightShiftAssign:
2708 if (isUnsigned)
2709 binOp = spv::OpShiftRightLogical;
2710 else
2711 binOp = spv::OpShiftRightArithmetic;
2712 break;
2713 case glslang::EOpLeftShift:
2714 case glslang::EOpLeftShiftAssign:
2715 binOp = spv::OpShiftLeftLogical;
2716 break;
2717 case glslang::EOpAnd:
2718 case glslang::EOpAndAssign:
2719 binOp = spv::OpBitwiseAnd;
2720 break;
2721 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002722 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002723 binOp = spv::OpLogicalAnd;
2724 break;
2725 case glslang::EOpInclusiveOr:
2726 case glslang::EOpInclusiveOrAssign:
2727 binOp = spv::OpBitwiseOr;
2728 break;
2729 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002730 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002731 binOp = spv::OpLogicalOr;
2732 break;
2733 case glslang::EOpExclusiveOr:
2734 case glslang::EOpExclusiveOrAssign:
2735 binOp = spv::OpBitwiseXor;
2736 break;
2737 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002738 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002739 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002740 break;
2741
2742 case glslang::EOpLessThan:
2743 case glslang::EOpGreaterThan:
2744 case glslang::EOpLessThanEqual:
2745 case glslang::EOpGreaterThanEqual:
2746 case glslang::EOpEqual:
2747 case glslang::EOpNotEqual:
2748 case glslang::EOpVectorEqual:
2749 case glslang::EOpVectorNotEqual:
2750 comparison = true;
2751 break;
2752 default:
2753 break;
2754 }
2755
John Kessenich7c1aa102015-10-15 13:29:11 -06002756 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002757 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002758 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002759 if (builder.isMatrix(left) || builder.isMatrix(right))
2760 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002761
2762 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002763 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002764 builder.promoteScalar(precision, left, right);
2765
John Kessenich32cfd492016-02-02 12:37:46 -07002766 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002767 }
2768
2769 if (! comparison)
2770 return 0;
2771
John Kessenich7c1aa102015-10-15 13:29:11 -06002772 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002773
2774 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2775 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2776
John Kessenich22118352015-12-21 20:54:09 -07002777 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002778 }
2779
2780 switch (op) {
2781 case glslang::EOpLessThan:
2782 if (isFloat)
2783 binOp = spv::OpFOrdLessThan;
2784 else if (isUnsigned)
2785 binOp = spv::OpULessThan;
2786 else
2787 binOp = spv::OpSLessThan;
2788 break;
2789 case glslang::EOpGreaterThan:
2790 if (isFloat)
2791 binOp = spv::OpFOrdGreaterThan;
2792 else if (isUnsigned)
2793 binOp = spv::OpUGreaterThan;
2794 else
2795 binOp = spv::OpSGreaterThan;
2796 break;
2797 case glslang::EOpLessThanEqual:
2798 if (isFloat)
2799 binOp = spv::OpFOrdLessThanEqual;
2800 else if (isUnsigned)
2801 binOp = spv::OpULessThanEqual;
2802 else
2803 binOp = spv::OpSLessThanEqual;
2804 break;
2805 case glslang::EOpGreaterThanEqual:
2806 if (isFloat)
2807 binOp = spv::OpFOrdGreaterThanEqual;
2808 else if (isUnsigned)
2809 binOp = spv::OpUGreaterThanEqual;
2810 else
2811 binOp = spv::OpSGreaterThanEqual;
2812 break;
2813 case glslang::EOpEqual:
2814 case glslang::EOpVectorEqual:
2815 if (isFloat)
2816 binOp = spv::OpFOrdEqual;
2817 else
2818 binOp = spv::OpIEqual;
2819 break;
2820 case glslang::EOpNotEqual:
2821 case glslang::EOpVectorNotEqual:
2822 if (isFloat)
2823 binOp = spv::OpFOrdNotEqual;
2824 else
2825 binOp = spv::OpINotEqual;
2826 break;
2827 default:
2828 break;
2829 }
2830
John Kessenich32cfd492016-02-02 12:37:46 -07002831 if (binOp != spv::OpNop)
2832 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002833
2834 return 0;
2835}
2836
John Kessenich04bb8a02015-12-12 12:28:14 -07002837//
2838// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2839// These can be any of:
2840//
2841// matrix * scalar
2842// scalar * matrix
2843// matrix * matrix linear algebraic
2844// matrix * vector
2845// vector * matrix
2846// matrix * matrix componentwise
2847// matrix op matrix op in {+, -, /}
2848// matrix op scalar op in {+, -, /}
2849// scalar op matrix op in {+, -, /}
2850//
2851spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2852{
2853 bool firstClass = true;
2854
2855 // First, handle first-class matrix operations (* and matrix/scalar)
2856 switch (op) {
2857 case spv::OpFDiv:
2858 if (builder.isMatrix(left) && builder.isScalar(right)) {
2859 // turn matrix / scalar into a multiply...
2860 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2861 op = spv::OpMatrixTimesScalar;
2862 } else
2863 firstClass = false;
2864 break;
2865 case spv::OpMatrixTimesScalar:
2866 if (builder.isMatrix(right))
2867 std::swap(left, right);
2868 assert(builder.isScalar(right));
2869 break;
2870 case spv::OpVectorTimesMatrix:
2871 assert(builder.isVector(left));
2872 assert(builder.isMatrix(right));
2873 break;
2874 case spv::OpMatrixTimesVector:
2875 assert(builder.isMatrix(left));
2876 assert(builder.isVector(right));
2877 break;
2878 case spv::OpMatrixTimesMatrix:
2879 assert(builder.isMatrix(left));
2880 assert(builder.isMatrix(right));
2881 break;
2882 default:
2883 firstClass = false;
2884 break;
2885 }
2886
John Kessenich32cfd492016-02-02 12:37:46 -07002887 if (firstClass)
2888 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002889
2890 // Handle component-wise +, -, *, and / for all combinations of type.
2891 // The result type of all of them is the same type as the (a) matrix operand.
2892 // The algorithm is to:
2893 // - break the matrix(es) into vectors
2894 // - smear any scalar to a vector
2895 // - do vector operations
2896 // - make a matrix out the vector results
2897 switch (op) {
2898 case spv::OpFAdd:
2899 case spv::OpFSub:
2900 case spv::OpFDiv:
2901 case spv::OpFMul:
2902 {
2903 // one time set up...
2904 bool leftMat = builder.isMatrix(left);
2905 bool rightMat = builder.isMatrix(right);
2906 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2907 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2908 spv::Id scalarType = builder.getScalarTypeId(typeId);
2909 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2910 std::vector<spv::Id> results;
2911 spv::Id smearVec = spv::NoResult;
2912 if (builder.isScalar(left))
2913 smearVec = builder.smearScalar(precision, left, vecType);
2914 else if (builder.isScalar(right))
2915 smearVec = builder.smearScalar(precision, right, vecType);
2916
2917 // do each vector op
2918 for (unsigned int c = 0; c < numCols; ++c) {
2919 std::vector<unsigned int> indexes;
2920 indexes.push_back(c);
2921 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2922 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2923 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2924 builder.setPrecision(results.back(), precision);
2925 }
2926
2927 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002928 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002929 }
2930 default:
2931 assert(0);
2932 return spv::NoResult;
2933 }
2934}
2935
Rex Xu04db3f52015-09-16 11:44:02 +08002936spv::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 -06002937{
2938 spv::Op unaryOp = spv::OpNop;
2939 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002940 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002941 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002942
2943 switch (op) {
2944 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002945 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002946 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002947 if (builder.isMatrixType(typeId))
2948 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2949 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002950 unaryOp = spv::OpSNegate;
2951 break;
2952
2953 case glslang::EOpLogicalNot:
2954 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002955 unaryOp = spv::OpLogicalNot;
2956 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002957 case glslang::EOpBitwiseNot:
2958 unaryOp = spv::OpNot;
2959 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002960
John Kessenich140f3df2015-06-26 16:58:36 -06002961 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002962 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967 case glslang::EOpTranspose:
2968 unaryOp = spv::OpTranspose;
2969 break;
2970
2971 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002972 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002973 break;
2974 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002975 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002982 break;
2983 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002984 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002985 break;
2986 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002988 break;
2989 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002990 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002991 break;
2992 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
2995
2996 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002997 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002998 break;
2999 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003000 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003001 break;
3002 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003003 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003004 break;
3005 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003013 break;
3014
3015 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003017 break;
3018 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003019 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003020 break;
3021
3022 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003023 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003024 break;
3025 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003026 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003027 break;
3028 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003029 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003030 break;
3031 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003032 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003033 break;
3034 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003035 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 break;
3037 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040
3041 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003042 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003043 break;
3044 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003045 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003046 break;
3047 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003048 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 break;
3050 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003051 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003052 break;
3053 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003054 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003055 break;
3056 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003057 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003058 break;
3059
3060 case glslang::EOpIsNan:
3061 unaryOp = spv::OpIsNan;
3062 break;
3063 case glslang::EOpIsInf:
3064 unaryOp = spv::OpIsInf;
3065 break;
3066
Rex Xucbc426e2015-12-15 16:03:10 +08003067 case glslang::EOpFloatBitsToInt:
3068 case glslang::EOpFloatBitsToUint:
3069 case glslang::EOpIntBitsToFloat:
3070 case glslang::EOpUintBitsToFloat:
3071 unaryOp = spv::OpBitcast;
3072 break;
3073
John Kessenich140f3df2015-06-26 16:58:36 -06003074 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003075 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003076 break;
3077 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003078 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003079 break;
3080 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003081 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003082 break;
3083 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003084 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003085 break;
3086 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003087 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
3089 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003090 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003091 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003092 case glslang::EOpPackSnorm4x8:
3093 libCall = spv::GLSLstd450PackSnorm4x8;
3094 break;
3095 case glslang::EOpUnpackSnorm4x8:
3096 libCall = spv::GLSLstd450UnpackSnorm4x8;
3097 break;
3098 case glslang::EOpPackUnorm4x8:
3099 libCall = spv::GLSLstd450PackUnorm4x8;
3100 break;
3101 case glslang::EOpUnpackUnorm4x8:
3102 libCall = spv::GLSLstd450UnpackUnorm4x8;
3103 break;
3104 case glslang::EOpPackDouble2x32:
3105 libCall = spv::GLSLstd450PackDouble2x32;
3106 break;
3107 case glslang::EOpUnpackDouble2x32:
3108 libCall = spv::GLSLstd450UnpackDouble2x32;
3109 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003110
3111 case glslang::EOpDPdx:
3112 unaryOp = spv::OpDPdx;
3113 break;
3114 case glslang::EOpDPdy:
3115 unaryOp = spv::OpDPdy;
3116 break;
3117 case glslang::EOpFwidth:
3118 unaryOp = spv::OpFwidth;
3119 break;
3120 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003121 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003122 unaryOp = spv::OpDPdxFine;
3123 break;
3124 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003125 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003126 unaryOp = spv::OpDPdyFine;
3127 break;
3128 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003129 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003130 unaryOp = spv::OpFwidthFine;
3131 break;
3132 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003133 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003134 unaryOp = spv::OpDPdxCoarse;
3135 break;
3136 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003137 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003138 unaryOp = spv::OpDPdyCoarse;
3139 break;
3140 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003141 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003142 unaryOp = spv::OpFwidthCoarse;
3143 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003144 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003145 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003146 libCall = spv::GLSLstd450InterpolateAtCentroid;
3147 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003148 case glslang::EOpAny:
3149 unaryOp = spv::OpAny;
3150 break;
3151 case glslang::EOpAll:
3152 unaryOp = spv::OpAll;
3153 break;
3154
3155 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003156 if (isFloat)
3157 libCall = spv::GLSLstd450FAbs;
3158 else
3159 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003160 break;
3161 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003162 if (isFloat)
3163 libCall = spv::GLSLstd450FSign;
3164 else
3165 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167
John Kessenichfc51d282015-08-19 13:34:18 -06003168 case glslang::EOpAtomicCounterIncrement:
3169 case glslang::EOpAtomicCounterDecrement:
3170 case glslang::EOpAtomicCounter:
3171 {
3172 // Handle all of the atomics in one place, in createAtomicOperation()
3173 std::vector<spv::Id> operands;
3174 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003175 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003176 }
3177
John Kessenichfc51d282015-08-19 13:34:18 -06003178 case glslang::EOpBitFieldReverse:
3179 unaryOp = spv::OpBitReverse;
3180 break;
3181 case glslang::EOpBitCount:
3182 unaryOp = spv::OpBitCount;
3183 break;
3184 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003185 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003186 break;
3187 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003188 if (isUnsigned)
3189 libCall = spv::GLSLstd450FindUMsb;
3190 else
3191 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003192 break;
3193
John Kessenich140f3df2015-06-26 16:58:36 -06003194 default:
3195 return 0;
3196 }
3197
3198 spv::Id id;
3199 if (libCall >= 0) {
3200 std::vector<spv::Id> args;
3201 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003202 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003203 } else
3204 id = builder.createUnaryOp(unaryOp, typeId, operand);
3205
John Kessenich32cfd492016-02-02 12:37:46 -07003206 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003207}
3208
John Kessenich7a53f762016-01-20 11:19:27 -07003209// Create a unary operation on a matrix
3210spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3211{
3212 // Handle unary operations vector by vector.
3213 // The result type is the same type as the original type.
3214 // The algorithm is to:
3215 // - break the matrix into vectors
3216 // - apply the operation to each vector
3217 // - make a matrix out the vector results
3218
3219 // get the types sorted out
3220 int numCols = builder.getNumColumns(operand);
3221 int numRows = builder.getNumRows(operand);
3222 spv::Id scalarType = builder.getScalarTypeId(typeId);
3223 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3224 std::vector<spv::Id> results;
3225
3226 // do each vector op
3227 for (int c = 0; c < numCols; ++c) {
3228 std::vector<unsigned int> indexes;
3229 indexes.push_back(c);
3230 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3231 results.push_back(builder.createUnaryOp(op, vecType, vec));
3232 builder.setPrecision(results.back(), precision);
3233 }
3234
3235 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003236 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003237}
3238
John Kessenich140f3df2015-06-26 16:58:36 -06003239spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3240{
3241 spv::Op convOp = spv::OpNop;
3242 spv::Id zero = 0;
3243 spv::Id one = 0;
3244
3245 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3246
3247 switch (op) {
3248 case glslang::EOpConvIntToBool:
3249 case glslang::EOpConvUintToBool:
3250 zero = builder.makeUintConstant(0);
3251 zero = makeSmearedConstant(zero, vectorSize);
3252 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3253
3254 case glslang::EOpConvFloatToBool:
3255 zero = builder.makeFloatConstant(0.0F);
3256 zero = makeSmearedConstant(zero, vectorSize);
3257 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3258
3259 case glslang::EOpConvDoubleToBool:
3260 zero = builder.makeDoubleConstant(0.0);
3261 zero = makeSmearedConstant(zero, vectorSize);
3262 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3263
3264 case glslang::EOpConvBoolToFloat:
3265 convOp = spv::OpSelect;
3266 zero = builder.makeFloatConstant(0.0);
3267 one = builder.makeFloatConstant(1.0);
3268 break;
3269 case glslang::EOpConvBoolToDouble:
3270 convOp = spv::OpSelect;
3271 zero = builder.makeDoubleConstant(0.0);
3272 one = builder.makeDoubleConstant(1.0);
3273 break;
3274 case glslang::EOpConvBoolToInt:
3275 zero = builder.makeIntConstant(0);
3276 one = builder.makeIntConstant(1);
3277 convOp = spv::OpSelect;
3278 break;
3279 case glslang::EOpConvBoolToUint:
3280 zero = builder.makeUintConstant(0);
3281 one = builder.makeUintConstant(1);
3282 convOp = spv::OpSelect;
3283 break;
3284
3285 case glslang::EOpConvIntToFloat:
3286 case glslang::EOpConvIntToDouble:
3287 convOp = spv::OpConvertSToF;
3288 break;
3289
3290 case glslang::EOpConvUintToFloat:
3291 case glslang::EOpConvUintToDouble:
3292 convOp = spv::OpConvertUToF;
3293 break;
3294
3295 case glslang::EOpConvDoubleToFloat:
3296 case glslang::EOpConvFloatToDouble:
3297 convOp = spv::OpFConvert;
3298 break;
3299
3300 case glslang::EOpConvFloatToInt:
3301 case glslang::EOpConvDoubleToInt:
3302 convOp = spv::OpConvertFToS;
3303 break;
3304
3305 case glslang::EOpConvUintToInt:
3306 case glslang::EOpConvIntToUint:
3307 convOp = spv::OpBitcast;
3308 break;
3309
3310 case glslang::EOpConvFloatToUint:
3311 case glslang::EOpConvDoubleToUint:
3312 convOp = spv::OpConvertFToU;
3313 break;
3314 default:
3315 break;
3316 }
3317
3318 spv::Id result = 0;
3319 if (convOp == spv::OpNop)
3320 return result;
3321
3322 if (convOp == spv::OpSelect) {
3323 zero = makeSmearedConstant(zero, vectorSize);
3324 one = makeSmearedConstant(one, vectorSize);
3325 result = builder.createTriOp(convOp, destType, operand, one, zero);
3326 } else
3327 result = builder.createUnaryOp(convOp, destType, operand);
3328
John Kessenich32cfd492016-02-02 12:37:46 -07003329 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003330}
3331
3332spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3333{
3334 if (vectorSize == 0)
3335 return constant;
3336
3337 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3338 std::vector<spv::Id> components;
3339 for (int c = 0; c < vectorSize; ++c)
3340 components.push_back(constant);
3341 return builder.makeCompositeConstant(vectorTypeId, components);
3342}
3343
John Kessenich426394d2015-07-23 10:22:48 -06003344// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003345spv::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 -06003346{
3347 spv::Op opCode = spv::OpNop;
3348
3349 switch (op) {
3350 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003351 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003352 opCode = spv::OpAtomicIAdd;
3353 break;
3354 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003355 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003356 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003357 break;
3358 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003359 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003360 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003361 break;
3362 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003363 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003364 opCode = spv::OpAtomicAnd;
3365 break;
3366 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003367 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003368 opCode = spv::OpAtomicOr;
3369 break;
3370 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003371 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003372 opCode = spv::OpAtomicXor;
3373 break;
3374 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003375 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003376 opCode = spv::OpAtomicExchange;
3377 break;
3378 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003379 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003380 opCode = spv::OpAtomicCompareExchange;
3381 break;
3382 case glslang::EOpAtomicCounterIncrement:
3383 opCode = spv::OpAtomicIIncrement;
3384 break;
3385 case glslang::EOpAtomicCounterDecrement:
3386 opCode = spv::OpAtomicIDecrement;
3387 break;
3388 case glslang::EOpAtomicCounter:
3389 opCode = spv::OpAtomicLoad;
3390 break;
3391 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003392 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003393 break;
3394 }
3395
3396 // Sort out the operands
3397 // - mapping from glslang -> SPV
3398 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003399 // - compare-exchange swaps the value and comparator
3400 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003401 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3402 auto opIt = operands.begin(); // walk the glslang operands
3403 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003404 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3405 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3406 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003407 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3408 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003409 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003410 spvAtomicOperands.push_back(*(opIt + 1));
3411 spvAtomicOperands.push_back(*opIt);
3412 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003413 }
John Kessenich426394d2015-07-23 10:22:48 -06003414
John Kessenich3e60a6f2015-09-14 22:45:16 -06003415 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003416 for (; opIt != operands.end(); ++opIt)
3417 spvAtomicOperands.push_back(*opIt);
3418
3419 return builder.createOp(opCode, typeId, spvAtomicOperands);
3420}
3421
John Kessenich5e4b1242015-08-06 22:53:06 -06003422spv::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 -06003423{
John Kessenich5e4b1242015-08-06 22:53:06 -06003424 bool isUnsigned = typeProxy == glslang::EbtUint;
3425 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3426
John Kessenich140f3df2015-06-26 16:58:36 -06003427 spv::Op opCode = spv::OpNop;
3428 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003429 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003430 spv::Id typeId0 = 0;
3431 if (consumedOperands > 0)
3432 typeId0 = builder.getTypeId(operands[0]);
3433 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003434
3435 switch (op) {
3436 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003437 if (isFloat)
3438 libCall = spv::GLSLstd450FMin;
3439 else if (isUnsigned)
3440 libCall = spv::GLSLstd450UMin;
3441 else
3442 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003443 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003444 break;
3445 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003446 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003447 break;
3448 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003449 if (isFloat)
3450 libCall = spv::GLSLstd450FMax;
3451 else if (isUnsigned)
3452 libCall = spv::GLSLstd450UMax;
3453 else
3454 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003455 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003456 break;
3457 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003458 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003459 break;
3460 case glslang::EOpDot:
3461 opCode = spv::OpDot;
3462 break;
3463 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003464 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003465 break;
3466
3467 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003468 if (isFloat)
3469 libCall = spv::GLSLstd450FClamp;
3470 else if (isUnsigned)
3471 libCall = spv::GLSLstd450UClamp;
3472 else
3473 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003474 builder.promoteScalar(precision, operands.front(), operands[1]);
3475 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003476 break;
3477 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003478 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3479 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003480 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003481 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003482 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003483 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003484 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003485 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003488 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003489 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003490 break;
3491 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003492 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003493 builder.promoteScalar(precision, operands[0], operands[2]);
3494 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003495 break;
3496
3497 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003498 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003501 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 break;
3503 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003504 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003505 break;
3506 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003507 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003508 break;
3509 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003510 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003511 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003512 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003513 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003514 libCall = spv::GLSLstd450InterpolateAtSample;
3515 break;
3516 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003517 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003518 libCall = spv::GLSLstd450InterpolateAtOffset;
3519 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003520 case glslang::EOpAddCarry:
3521 opCode = spv::OpIAddCarry;
3522 typeId = builder.makeStructResultType(typeId0, typeId0);
3523 consumedOperands = 2;
3524 break;
3525 case glslang::EOpSubBorrow:
3526 opCode = spv::OpISubBorrow;
3527 typeId = builder.makeStructResultType(typeId0, typeId0);
3528 consumedOperands = 2;
3529 break;
3530 case glslang::EOpUMulExtended:
3531 opCode = spv::OpUMulExtended;
3532 typeId = builder.makeStructResultType(typeId0, typeId0);
3533 consumedOperands = 2;
3534 break;
3535 case glslang::EOpIMulExtended:
3536 opCode = spv::OpSMulExtended;
3537 typeId = builder.makeStructResultType(typeId0, typeId0);
3538 consumedOperands = 2;
3539 break;
3540 case glslang::EOpBitfieldExtract:
3541 if (isUnsigned)
3542 opCode = spv::OpBitFieldUExtract;
3543 else
3544 opCode = spv::OpBitFieldSExtract;
3545 break;
3546 case glslang::EOpBitfieldInsert:
3547 opCode = spv::OpBitFieldInsert;
3548 break;
3549
3550 case glslang::EOpFma:
3551 libCall = spv::GLSLstd450Fma;
3552 break;
3553 case glslang::EOpFrexp:
3554 libCall = spv::GLSLstd450FrexpStruct;
3555 if (builder.getNumComponents(operands[0]) == 1)
3556 frexpIntType = builder.makeIntegerType(32, true);
3557 else
3558 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3559 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3560 consumedOperands = 1;
3561 break;
3562 case glslang::EOpLdexp:
3563 libCall = spv::GLSLstd450Ldexp;
3564 break;
3565
John Kessenich140f3df2015-06-26 16:58:36 -06003566 default:
3567 return 0;
3568 }
3569
3570 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003571 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003572 // Use an extended instruction from the standard library.
3573 // Construct the call arguments, without modifying the original operands vector.
3574 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3575 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003576 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003577 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003578 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003579 case 0:
3580 // should all be handled by visitAggregate and createNoArgOperation
3581 assert(0);
3582 return 0;
3583 case 1:
3584 // should all be handled by createUnaryOperation
3585 assert(0);
3586 return 0;
3587 case 2:
3588 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3589 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003590 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003591 // anything 3 or over doesn't have l-value operands, so all should be consumed
3592 assert(consumedOperands == operands.size());
3593 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003594 break;
3595 }
3596 }
3597
John Kessenich55e7d112015-11-15 21:33:39 -07003598 // Decode the return types that were structures
3599 switch (op) {
3600 case glslang::EOpAddCarry:
3601 case glslang::EOpSubBorrow:
3602 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3603 id = builder.createCompositeExtract(id, typeId0, 0);
3604 break;
3605 case glslang::EOpUMulExtended:
3606 case glslang::EOpIMulExtended:
3607 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3608 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3609 break;
3610 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003611 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003612 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3613 id = builder.createCompositeExtract(id, typeId0, 0);
3614 break;
3615 default:
3616 break;
3617 }
3618
John Kessenich32cfd492016-02-02 12:37:46 -07003619 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003620}
3621
3622// Intrinsics with no arguments, no return value, and no precision.
3623spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3624{
3625 // TODO: get the barrier operands correct
3626
3627 switch (op) {
3628 case glslang::EOpEmitVertex:
3629 builder.createNoResultOp(spv::OpEmitVertex);
3630 return 0;
3631 case glslang::EOpEndPrimitive:
3632 builder.createNoResultOp(spv::OpEndPrimitive);
3633 return 0;
3634 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003635 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3636 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003637 return 0;
3638 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003639 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003640 return 0;
3641 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003642 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003643 return 0;
3644 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003645 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003646 return 0;
3647 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003648 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003649 return 0;
3650 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003651 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003652 return 0;
3653 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003654 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003655 return 0;
3656 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003657 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003658 return 0;
3659 }
3660}
3661
3662spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3663{
John Kessenich2f273362015-07-18 22:34:27 -06003664 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003665 spv::Id id;
3666 if (symbolValues.end() != iter) {
3667 id = iter->second;
3668 return id;
3669 }
3670
3671 // it was not found, create it
3672 id = createSpvVariable(symbol);
3673 symbolValues[symbol->getId()] = id;
3674
3675 if (! symbol->getType().isStruct()) {
3676 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003677 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003678 if (symbol->getType().getQualifier().hasSpecConstantId())
3679 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003680 if (symbol->getQualifier().hasLocation())
3681 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3682 if (symbol->getQualifier().hasIndex())
3683 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3684 if (symbol->getQualifier().hasComponent())
3685 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3686 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003687 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003688 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003689 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003690 if (symbol->getQualifier().hasXfbBuffer())
3691 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3692 if (symbol->getQualifier().hasXfbOffset())
3693 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3694 }
3695 }
3696
John Kesseniche0b6cad2015-12-24 10:30:13 -07003697 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003698 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003699 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003700 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003701 }
John Kessenich140f3df2015-06-26 16:58:36 -06003702 if (symbol->getQualifier().hasSet())
3703 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003704 else if (IsDescriptorResource(symbol->getType())) {
3705 // default to 0
3706 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3707 }
John Kessenich140f3df2015-06-26 16:58:36 -06003708 if (symbol->getQualifier().hasBinding())
3709 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003710 if (symbol->getQualifier().hasAttachment())
3711 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003712 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003713 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003714 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003716 if (symbol->getQualifier().hasXfbBuffer())
3717 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3718 }
3719
Rex Xu1da878f2016-02-21 20:59:01 +08003720 if (symbol->getType().isImage()) {
3721 std::vector<spv::Decoration> memory;
3722 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3723 for (unsigned int i = 0; i < memory.size(); ++i)
3724 addDecoration(id, memory[i]);
3725 }
3726
John Kessenich140f3df2015-06-26 16:58:36 -06003727 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003728 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003729 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003730 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003731
John Kessenich140f3df2015-06-26 16:58:36 -06003732 return id;
3733}
3734
John Kessenich55e7d112015-11-15 21:33:39 -07003735// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003736void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3737{
3738 if (dec != spv::BadValue)
3739 builder.addDecoration(id, dec);
3740}
3741
John Kessenich55e7d112015-11-15 21:33:39 -07003742// If 'dec' is valid, add a one-operand decoration to an object
3743void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3744{
3745 if (dec != spv::BadValue)
3746 builder.addDecoration(id, dec, value);
3747}
3748
3749// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003750void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3751{
3752 if (dec != spv::BadValue)
3753 builder.addMemberDecoration(id, (unsigned)member, dec);
3754}
3755
John Kessenich92187592016-02-01 13:45:25 -07003756// If 'dec' is valid, add a one-operand decoration to a struct member
3757void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3758{
3759 if (dec != spv::BadValue)
3760 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3761}
3762
John Kessenich55e7d112015-11-15 21:33:39 -07003763// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003764// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003765//
3766// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3767//
3768// Recursively walk the nodes. The nodes form a tree whose leaves are
3769// regular constants, which themselves are trees that createSpvConstant()
3770// recursively walks. So, this function walks the "top" of the tree:
3771// - emit specialization constant-building instructions for specConstant
3772// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003773spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003774{
John Kessenich7cc0e282016-03-20 00:46:02 -06003775 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003776
qining4f4bb812016-04-03 23:55:17 -04003777 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003778 if (! node.getQualifier().specConstant) {
3779 // hand off to the non-spec-constant path
3780 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3781 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003782 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003783 nextConst, false);
3784 }
3785
3786 // We now know we have a specialization constant to build
3787
qining4f4bb812016-04-03 23:55:17 -04003788 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3789 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3790 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3791 std::vector<spv::Id> dimConstId;
3792 for (int dim = 0; dim < 3; ++dim) {
3793 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3794 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3795 if (specConst)
3796 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3797 }
3798 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3799 }
3800
3801 // An AST node labelled as specialization constant should be a symbol node.
3802 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3803 if (auto* sn = node.getAsSymbolNode()) {
3804 if (auto* sub_tree = sn->getConstSubtree()) {
3805 return createSpvConstantFromConstSubTree(sub_tree);
3806 } else if (auto* const_union_array = &sn->getConstArray()){
3807 int nextConst = 0;
3808 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003809 }
3810 }
qining4f4bb812016-04-03 23:55:17 -04003811
3812 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3813 // constant sub tree as initializer.
3814 spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
3815 exit(1);
3816 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003817}
3818
John Kessenich140f3df2015-06-26 16:58:36 -06003819// Use 'consts' as the flattened glslang source of scalar constants to recursively
3820// build the aggregate SPIR-V constant.
3821//
3822// If there are not enough elements present in 'consts', 0 will be substituted;
3823// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3824//
qining08408382016-03-21 09:51:37 -04003825spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003826{
3827 // vector of constants for SPIR-V
3828 std::vector<spv::Id> spvConsts;
3829
3830 // Type is used for struct and array constants
3831 spv::Id typeId = convertGlslangToSpvType(glslangType);
3832
3833 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003834 glslang::TType elementType(glslangType, 0);
3835 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003836 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003837 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003838 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003839 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003840 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003841 } else if (glslangType.getStruct()) {
3842 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3843 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003844 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003845 } else if (glslangType.isVector()) {
3846 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3847 bool zero = nextConst >= consts.size();
3848 switch (glslangType.getBasicType()) {
3849 case glslang::EbtInt:
3850 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3851 break;
3852 case glslang::EbtUint:
3853 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3854 break;
3855 case glslang::EbtFloat:
3856 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3857 break;
3858 case glslang::EbtDouble:
3859 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3860 break;
3861 case glslang::EbtBool:
3862 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3863 break;
3864 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003865 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003866 break;
3867 }
3868 ++nextConst;
3869 }
3870 } else {
3871 // we have a non-aggregate (scalar) constant
3872 bool zero = nextConst >= consts.size();
3873 spv::Id scalar = 0;
3874 switch (glslangType.getBasicType()) {
3875 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003876 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003877 break;
3878 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003879 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003880 break;
3881 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003882 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003883 break;
3884 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003885 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003886 break;
3887 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003888 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003889 break;
3890 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003891 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003892 break;
3893 }
3894 ++nextConst;
3895 return scalar;
3896 }
3897
3898 return builder.makeCompositeConstant(typeId, spvConsts);
3899}
3900
qining08408382016-03-21 09:51:37 -04003901// Create constant ID from const initializer sub tree.
3902spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstSubTree(
qining5c61d8e2016-03-31 13:57:28 -04003903 glslang::TIntermTyped* subTree)
3904{
qining08408382016-03-21 09:51:37 -04003905 const glslang::TType& glslangType = subTree->getType();
3906 spv::Id typeId = convertGlslangToSpvType(glslangType);
3907 bool is_spec_const = subTree->getType().getQualifier().isSpecConstant();
3908 if (const glslang::TIntermAggregate* an = subTree->getAsAggregate()) {
3909 // Aggregate node, we should generate OpConstantComposite or
3910 // OpSpecConstantComposite instruction.
qining13545202016-03-21 09:51:37 -04003911
qining08408382016-03-21 09:51:37 -04003912 std::vector<spv::Id> const_constituents;
3913 for (auto NI = an->getSequence().begin(); NI != an->getSequence().end();
3914 NI++) {
3915 const_constituents.push_back(
3916 createSpvConstantFromConstSubTree((*NI)->getAsTyped()));
3917 }
3918 // Note that constructors are aggregate nodes, so expressions like:
3919 // float x = float(y) will become an aggregate node. If 'x' is declared
3920 // as a constant, the aggregate node representing 'float(y)' will be
3921 // processed here.
3922 if (builder.isVectorType(typeId) || builder.isMatrixType(typeId) ||
3923 builder.isAggregateType(typeId)) {
3924 return builder.makeCompositeConstant(typeId, const_constituents, is_spec_const);
3925 } else {
3926 assert(builder.isScalarType(typeId) && const_constituents.size() == 1);
3927 return const_constituents.front();
3928 }
3929
qining13545202016-03-21 09:51:37 -04003930 } else if (glslang::TIntermBinary* bn = subTree->getAsBinaryNode()) {
qining08408382016-03-21 09:51:37 -04003931 // Binary operation node, we should generate OpSpecConstantOp <binary op>
3932 // This case should only happen when Specialization Constants are involved.
qining13545202016-03-21 09:51:37 -04003933 bn->traverse(this);
3934 return accessChainLoad(bn->getType());
3935
3936 } else if (glslang::TIntermUnary* un = subTree->getAsUnaryNode()) {
qining08408382016-03-21 09:51:37 -04003937 // Unary operation node, similar to binary operation node, should only
3938 // happen when specialization constants are involved.
qining13545202016-03-21 09:51:37 -04003939 un->traverse(this);
3940 return accessChainLoad(un->getType());
qining08408382016-03-21 09:51:37 -04003941
3942 } else if (const glslang::TIntermConstantUnion* cn = subTree->getAsConstantUnion()) {
3943 // ConstantUnion node, should redirect to
3944 // createSpvConstantFromConstUnionArray
3945 int nextConst = 0;
3946 return createSpvConstantFromConstUnionArray(
3947 glslangType, cn->getConstArray(), nextConst, is_spec_const);
3948
3949 } else if (const glslang::TIntermSymbol* sn = subTree->getAsSymbolNode()) {
3950 // Symbol node. Call getSymbolId(). This should cover both cases 1) the
3951 // symbol has already been assigned an ID, 2) need a new ID for this
3952 // symbol.
3953 return getSymbolId(sn);
3954
3955 } else {
3956 spv::MissingFunctionality(
3957 "createSpvConstantFromConstSubTree() not covered TIntermTyped* const "
3958 "initializer subtree.");
3959 return spv::NoResult;
3960 }
3961}
3962
John Kessenich7c1aa102015-10-15 13:29:11 -06003963// Return true if the node is a constant or symbol whose reading has no
3964// non-trivial observable cost or effect.
3965bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3966{
3967 // don't know what this is
3968 if (node == nullptr)
3969 return false;
3970
3971 // a constant is safe
3972 if (node->getAsConstantUnion() != nullptr)
3973 return true;
3974
3975 // not a symbol means non-trivial
3976 if (node->getAsSymbolNode() == nullptr)
3977 return false;
3978
3979 // a symbol, depends on what's being read
3980 switch (node->getType().getQualifier().storage) {
3981 case glslang::EvqTemporary:
3982 case glslang::EvqGlobal:
3983 case glslang::EvqIn:
3984 case glslang::EvqInOut:
3985 case glslang::EvqConst:
3986 case glslang::EvqConstReadOnly:
3987 case glslang::EvqUniform:
3988 return true;
3989 default:
3990 return false;
3991 }
3992}
3993
3994// A node is trivial if it is a single operation with no side effects.
3995// Error on the side of saying non-trivial.
3996// Return true if trivial.
3997bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3998{
3999 if (node == nullptr)
4000 return false;
4001
4002 // symbols and constants are trivial
4003 if (isTrivialLeaf(node))
4004 return true;
4005
4006 // otherwise, it needs to be a simple operation or one or two leaf nodes
4007
4008 // not a simple operation
4009 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4010 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4011 if (binaryNode == nullptr && unaryNode == nullptr)
4012 return false;
4013
4014 // not on leaf nodes
4015 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4016 return false;
4017
4018 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4019 return false;
4020 }
4021
4022 switch (node->getAsOperator()->getOp()) {
4023 case glslang::EOpLogicalNot:
4024 case glslang::EOpConvIntToBool:
4025 case glslang::EOpConvUintToBool:
4026 case glslang::EOpConvFloatToBool:
4027 case glslang::EOpConvDoubleToBool:
4028 case glslang::EOpEqual:
4029 case glslang::EOpNotEqual:
4030 case glslang::EOpLessThan:
4031 case glslang::EOpGreaterThan:
4032 case glslang::EOpLessThanEqual:
4033 case glslang::EOpGreaterThanEqual:
4034 case glslang::EOpIndexDirect:
4035 case glslang::EOpIndexDirectStruct:
4036 case glslang::EOpLogicalXor:
4037 case glslang::EOpAny:
4038 case glslang::EOpAll:
4039 return true;
4040 default:
4041 return false;
4042 }
4043}
4044
4045// Emit short-circuiting code, where 'right' is never evaluated unless
4046// the left side is true (for &&) or false (for ||).
4047spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4048{
4049 spv::Id boolTypeId = builder.makeBoolType();
4050
4051 // emit left operand
4052 builder.clearAccessChain();
4053 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004054 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004055
4056 // Operands to accumulate OpPhi operands
4057 std::vector<spv::Id> phiOperands;
4058 // accumulate left operand's phi information
4059 phiOperands.push_back(leftId);
4060 phiOperands.push_back(builder.getBuildPoint()->getId());
4061
4062 // Make the two kinds of operation symmetric with a "!"
4063 // || => emit "if (! left) result = right"
4064 // && => emit "if ( left) result = right"
4065 //
4066 // TODO: this runtime "not" for || could be avoided by adding functionality
4067 // to 'builder' to have an "else" without an "then"
4068 if (op == glslang::EOpLogicalOr)
4069 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4070
4071 // make an "if" based on the left value
4072 spv::Builder::If ifBuilder(leftId, builder);
4073
4074 // emit right operand as the "then" part of the "if"
4075 builder.clearAccessChain();
4076 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004077 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004078
4079 // accumulate left operand's phi information
4080 phiOperands.push_back(rightId);
4081 phiOperands.push_back(builder.getBuildPoint()->getId());
4082
4083 // finish the "if"
4084 ifBuilder.makeEndIf();
4085
4086 // phi together the two results
4087 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4088}
4089
John Kessenich140f3df2015-06-26 16:58:36 -06004090}; // end anonymous namespace
4091
4092namespace glslang {
4093
John Kessenich68d78fd2015-07-12 19:28:10 -06004094void GetSpirvVersion(std::string& version)
4095{
John Kessenich9e55f632015-07-15 10:03:39 -06004096 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004097 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004098 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004099 version = buf;
4100}
4101
John Kessenich140f3df2015-06-26 16:58:36 -06004102// Write SPIR-V out to a binary file
4103void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4104{
4105 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004106 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004107 for (int i = 0; i < (int)spirv.size(); ++i) {
4108 unsigned int word = spirv[i];
4109 out.write((const char*)&word, 4);
4110 }
4111 out.close();
4112}
4113
4114//
4115// Set up the glslang traversal
4116//
4117void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4118{
4119 TIntermNode* root = intermediate.getTreeRoot();
4120
4121 if (root == 0)
4122 return;
4123
4124 glslang::GetThreadPoolAllocator().push();
4125
4126 TGlslangToSpvTraverser it(&intermediate);
4127
4128 root->traverse(&it);
4129
4130 it.dumpSpv(spirv);
4131
4132 glslang::GetThreadPoolAllocator().pop();
4133}
4134
4135}; // end namespace glslang