blob: 0fc57305a143157fbe84ed61613365a107f7fe3b [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
LoopDawg592860c2016-06-09 08:57:35 -06002//Copyright (C) 2014-2016 LunarG, Inc.
John Kessenich6c292d32016-02-15 20:58:50 -07003//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
45 #include "GLSL.std.450.h"
Rex Xu9d93a232016-05-05 12:30:44 +080046#ifdef AMD_EXTENSIONS
47 #include "GLSL.ext.AMD.h"
48#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060049}
John Kessenich140f3df2015-06-26 16:58:36 -060050
51// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020052#include "../glslang/MachineIndependent/localintermediate.h"
53#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060054#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050055#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060056
John Kessenich140f3df2015-06-26 16:58:36 -060057#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050058#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040059#include <list>
60#include <map>
61#include <stack>
62#include <string>
63#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060064
65namespace {
66
John Kessenich55e7d112015-11-15 21:33:39 -070067// For low-order part of the generator's magic number. Bump up
68// when there is a change in the style (e.g., if SSA form changes,
69// or a different instruction sequence to do something gets used).
70const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060071
qining4c912612016-04-01 10:35:16 -040072namespace {
73class SpecConstantOpModeGuard {
74public:
75 SpecConstantOpModeGuard(spv::Builder* builder)
76 : builder_(builder) {
77 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040078 }
79 ~SpecConstantOpModeGuard() {
80 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
81 : builder_->setToNormalCodeGenMode();
82 }
qining40887662016-04-03 22:20:42 -040083 void turnOnSpecConstantOpMode() {
84 builder_->setToSpecConstCodeGenMode();
85 }
qining4c912612016-04-01 10:35:16 -040086
87private:
88 spv::Builder* builder_;
89 bool previous_flag_;
90};
91}
92
John Kessenich140f3df2015-06-26 16:58:36 -060093//
94// The main holder of information for translating glslang to SPIR-V.
95//
96// Derives from the AST walking base class.
97//
98class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
99public:
Lei Zhang17535f72016-05-04 15:55:59 -0400100 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600101 virtual ~TGlslangToSpvTraverser();
102
103 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
104 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
105 void visitConstantUnion(glslang::TIntermConstantUnion*);
106 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
107 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
108 void visitSymbol(glslang::TIntermSymbol* symbol);
109 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
110 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
111 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
112
John Kessenich7ba63412015-12-20 17:37:07 -0700113 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600114
115protected:
Rex Xubbceed72016-05-21 09:40:44 +0800116 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100117 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700118 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600119 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
120 spv::Id getSampledType(const glslang::TSampler&);
121 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700122 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600123 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
124 glslang::TLayoutPacking, const glslang::TQualifier&);
125 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
126 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700127 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700128 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800129 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700130 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700131 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
132 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
133 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100134 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600135
136 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
137 void makeFunctions(const glslang::TIntermSequence&);
138 void makeGlobalInitializers(const glslang::TIntermSequence&);
139 void visitFunctions(const glslang::TIntermSequence&);
140 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800141 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600142 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
143 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600144 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
145
qining25262b32016-05-06 17:25:16 -0400146 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
147 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
148 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
149 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800150 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800152 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800153 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600154 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800155 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600156 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
157 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700158 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600159 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700160 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400161 spv::Id createSpvConstant(const glslang::TIntermTyped&);
162 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600163 bool isTrivialLeaf(const glslang::TIntermTyped* node);
164 bool isTrivial(const glslang::TIntermTyped* node);
165 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800166 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600167
168 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700169 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600170 int sequenceDepth;
171
Lei Zhang17535f72016-05-04 15:55:59 -0400172 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400173
John Kessenich140f3df2015-06-26 16:58:36 -0600174 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
175 spv::Builder builder;
176 bool inMain;
177 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700178 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 -0700179 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600180 const glslang::TIntermediate* glslangIntermediate;
181 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800182 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600183
John Kessenich2f273362015-07-18 22:34:27 -0600184 std::unordered_map<int, spv::Id> symbolValues;
185 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
186 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700187 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600188 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 -0600189 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600190};
191
192//
193// Helper functions for translating glslang representations to SPIR-V enumerants.
194//
195
196// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700197spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600198{
John Kessenich66e2faf2016-03-12 18:34:36 -0700199 switch (source) {
200 case glslang::EShSourceGlsl:
201 switch (profile) {
202 case ENoProfile:
203 case ECoreProfile:
204 case ECompatibilityProfile:
205 return spv::SourceLanguageGLSL;
206 case EEsProfile:
207 return spv::SourceLanguageESSL;
208 default:
209 return spv::SourceLanguageUnknown;
210 }
211 case glslang::EShSourceHlsl:
212 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 default:
214 return spv::SourceLanguageUnknown;
215 }
216}
217
218// Translate glslang language (stage) to SPIR-V execution model.
219spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
220{
221 switch (stage) {
222 case EShLangVertex: return spv::ExecutionModelVertex;
223 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
224 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
225 case EShLangGeometry: return spv::ExecutionModelGeometry;
226 case EShLangFragment: return spv::ExecutionModelFragment;
227 case EShLangCompute: return spv::ExecutionModelGLCompute;
228 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700229 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600230 return spv::ExecutionModelFragment;
231 }
232}
233
234// Translate glslang type to SPIR-V storage class.
235spv::StorageClass TranslateStorageClass(const glslang::TType& type)
236{
237 if (type.getQualifier().isPipeInput())
238 return spv::StorageClassInput;
239 else if (type.getQualifier().isPipeOutput())
240 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700241 else if (type.getBasicType() == glslang::EbtSampler)
242 return spv::StorageClassUniformConstant;
243 else if (type.getBasicType() == glslang::EbtAtomicUint)
244 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600245 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700246 if (type.getQualifier().layoutPushConstant)
247 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600248 if (type.getBasicType() == glslang::EbtBlock)
249 return spv::StorageClassUniform;
250 else
251 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600252 // TODO: how are we distinguishing between default and non-default non-writable uniforms? Do default uniforms even exist?
John Kessenich140f3df2015-06-26 16:58:36 -0600253 } else {
254 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
256 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600257 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
258 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400259 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700260 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600261 return spv::StorageClassFunction;
262 }
263 }
264}
265
266// Translate glslang sampler type to SPIR-V dimensionality.
267spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
268{
269 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700270 case glslang::Esd1D: return spv::Dim1D;
271 case glslang::Esd2D: return spv::Dim2D;
272 case glslang::Esd3D: return spv::Dim3D;
273 case glslang::EsdCube: return spv::DimCube;
274 case glslang::EsdRect: return spv::DimRect;
275 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700276 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600277 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700278 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600279 return spv::Dim2D;
280 }
281}
282
283// Translate glslang type to SPIR-V precision decorations.
284spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
285{
286 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700287 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600288 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
290 return spv::NoPrecision;
291 }
292}
293
294// Translate glslang type to SPIR-V block decorations.
295spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
296{
297 if (type.getBasicType() == glslang::EbtBlock) {
298 switch (type.getQualifier().storage) {
299 case glslang::EvqUniform: return spv::DecorationBlock;
300 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
301 case glslang::EvqVaryingIn: return spv::DecorationBlock;
302 case glslang::EvqVaryingOut: return spv::DecorationBlock;
303 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700304 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600305 break;
306 }
307 }
308
John Kessenich4016e382016-07-15 11:53:56 -0600309 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600310}
311
Rex Xu1da878f2016-02-21 20:59:01 +0800312// Translate glslang type to SPIR-V memory decorations.
313void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
314{
315 if (qualifier.coherent)
316 memory.push_back(spv::DecorationCoherent);
317 if (qualifier.volatil)
318 memory.push_back(spv::DecorationVolatile);
319 if (qualifier.restrict)
320 memory.push_back(spv::DecorationRestrict);
321 if (qualifier.readonly)
322 memory.push_back(spv::DecorationNonWritable);
323 if (qualifier.writeonly)
324 memory.push_back(spv::DecorationNonReadable);
325}
326
John Kessenich140f3df2015-06-26 16:58:36 -0600327// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700328spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600329{
330 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700331 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600332 case glslang::ElmRowMajor:
333 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600335 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700336 default:
337 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600338 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600339 }
340 } else {
341 switch (type.getBasicType()) {
342 default:
John Kessenich4016e382016-07-15 11:53:56 -0600343 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 break;
345 case glslang::EbtBlock:
346 switch (type.getQualifier().storage) {
347 case glslang::EvqUniform:
348 case glslang::EvqBuffer:
349 switch (type.getQualifier().layoutPacking) {
350 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
352 default:
John Kessenich4016e382016-07-15 11:53:56 -0600353 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 }
355 case glslang::EvqVaryingIn:
356 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700357 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600358 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600359 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700360 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 }
363 }
364 }
365}
366
367// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600368// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700369// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800370spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600371{
Rex Xubbceed72016-05-21 09:40:44 +0800372 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700373 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600374 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800375 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700376 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700377 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600378 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800379#ifdef AMD_EXTENSIONS
380 else if (qualifier.explicitInterp)
381 return spv::DecorationExplicitInterpAMD;
382#endif
Rex Xubbceed72016-05-21 09:40:44 +0800383 else
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800385}
386
387// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600388// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800389// should be applied.
390spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
391{
392 if (qualifier.patch)
393 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700394 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600395 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700396 else if (qualifier.sample) {
397 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700399 } else
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401}
402
John Kessenich92187592016-02-01 13:45:25 -0700403// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700404spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600405{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700406 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600407 return spv::DecorationInvariant;
408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410}
411
qining9220dbb2016-05-04 17:34:38 -0400412// If glslang type is noContraction, return SPIR-V NoContraction decoration.
413spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
414{
415 if (qualifier.noContraction)
416 return spv::DecorationNoContraction;
417 else
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400419}
420
David Netoa901ffe2016-06-08 14:11:40 +0100421// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
422// associated capabilities when required. For some built-in variables, a capability
423// is generated only when using the variable in an executable instruction, but not when
424// just declaring a struct member variable with it. This is true for PointSize,
425// ClipDistance, and CullDistance.
426spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600427{
428 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700429 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600430 // Defer adding the capability until the built-in is actually used.
431 if (! memberDeclaration) {
432 switch (glslangIntermediate->getStage()) {
433 case EShLangGeometry:
434 builder.addCapability(spv::CapabilityGeometryPointSize);
435 break;
436 case EShLangTessControl:
437 case EShLangTessEvaluation:
438 builder.addCapability(spv::CapabilityTessellationPointSize);
439 break;
440 default:
441 break;
442 }
John Kessenich92187592016-02-01 13:45:25 -0700443 }
444 return spv::BuiltInPointSize;
445
John Kessenichebb50532016-05-16 19:22:05 -0600446 // These *Distance capabilities logically belong here, but if the member is declared and
447 // then never used, consumers of SPIR-V prefer the capability not be declared.
448 // They are now generated when used, rather than here when declared.
449 // Potentially, the specification should be more clear what the minimum
450 // use needed is to trigger the capability.
451 //
John Kessenich92187592016-02-01 13:45:25 -0700452 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100453 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600454 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700455 return spv::BuiltInClipDistance;
456
457 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100458 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600459 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700460 return spv::BuiltInCullDistance;
461
462 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500463 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700464 return spv::BuiltInViewportIndex;
465
John Kessenich5e801132016-02-15 11:09:46 -0700466 case glslang::EbvSampleId:
467 builder.addCapability(spv::CapabilitySampleRateShading);
468 return spv::BuiltInSampleId;
469
470 case glslang::EbvSamplePosition:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSamplePosition;
473
474 case glslang::EbvSampleMask:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSampleMask;
477
John Kessenich78a45572016-07-08 14:05:15 -0600478 case glslang::EbvLayer:
479 builder.addCapability(spv::CapabilityGeometry);
480 return spv::BuiltInLayer;
481
John Kessenich140f3df2015-06-26 16:58:36 -0600482 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600483 case glslang::EbvVertexId: return spv::BuiltInVertexId;
484 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700485 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
486 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600487 case glslang::EbvBaseVertex:
488 case glslang::EbvBaseInstance:
489 case glslang::EbvDrawId:
490 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600491 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600492 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600493 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
494 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600495 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
496 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
497 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
498 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
499 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
500 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
501 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600502 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
503 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
504 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
505 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
506 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
507 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
508 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
509 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800510 case glslang::EbvSubGroupSize:
511 case glslang::EbvSubGroupInvocation:
512 case glslang::EbvSubGroupEqMask:
513 case glslang::EbvSubGroupGeMask:
514 case glslang::EbvSubGroupGtMask:
515 case glslang::EbvSubGroupLeMask:
516 case glslang::EbvSubGroupLtMask:
517 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600518 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600519 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800520#ifdef AMD_EXTENSIONS
521 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
522 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
523 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
524 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
525 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
526 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
527 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
528#endif
John Kessenich4016e382016-07-15 11:53:56 -0600529 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 }
531}
532
Rex Xufc618912015-09-09 16:42:49 +0800533// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700534spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800535{
536 assert(type.getBasicType() == glslang::EbtSampler);
537
John Kessenich5d0fa972016-02-15 11:57:00 -0700538 // Check for capabilities
539 switch (type.getQualifier().layoutFormat) {
540 case glslang::ElfRg32f:
541 case glslang::ElfRg16f:
542 case glslang::ElfR11fG11fB10f:
543 case glslang::ElfR16f:
544 case glslang::ElfRgba16:
545 case glslang::ElfRgb10A2:
546 case glslang::ElfRg16:
547 case glslang::ElfRg8:
548 case glslang::ElfR16:
549 case glslang::ElfR8:
550 case glslang::ElfRgba16Snorm:
551 case glslang::ElfRg16Snorm:
552 case glslang::ElfRg8Snorm:
553 case glslang::ElfR16Snorm:
554 case glslang::ElfR8Snorm:
555
556 case glslang::ElfRg32i:
557 case glslang::ElfRg16i:
558 case glslang::ElfRg8i:
559 case glslang::ElfR16i:
560 case glslang::ElfR8i:
561
562 case glslang::ElfRgb10a2ui:
563 case glslang::ElfRg32ui:
564 case glslang::ElfRg16ui:
565 case glslang::ElfRg8ui:
566 case glslang::ElfR16ui:
567 case glslang::ElfR8ui:
568 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
569 break;
570
571 default:
572 break;
573 }
574
575 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800576 switch (type.getQualifier().layoutFormat) {
577 case glslang::ElfNone: return spv::ImageFormatUnknown;
578 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
579 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
580 case glslang::ElfR32f: return spv::ImageFormatR32f;
581 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
582 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
583 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
584 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
585 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
586 case glslang::ElfR16f: return spv::ImageFormatR16f;
587 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
588 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
589 case glslang::ElfRg16: return spv::ImageFormatRg16;
590 case glslang::ElfRg8: return spv::ImageFormatRg8;
591 case glslang::ElfR16: return spv::ImageFormatR16;
592 case glslang::ElfR8: return spv::ImageFormatR8;
593 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
594 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
595 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
596 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
597 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
598 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
599 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
600 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
601 case glslang::ElfR32i: return spv::ImageFormatR32i;
602 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
603 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
604 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
605 case glslang::ElfR16i: return spv::ImageFormatR16i;
606 case glslang::ElfR8i: return spv::ImageFormatR8i;
607 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
608 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
609 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
610 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
611 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
612 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
613 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
614 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
615 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
616 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600617 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800618 }
619}
620
qining25262b32016-05-06 17:25:16 -0400621// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700622// descriptor set.
623bool IsDescriptorResource(const glslang::TType& type)
624{
John Kessenichf7497e22016-03-08 21:36:22 -0700625 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700626 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700627 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700628
629 // non block...
630 // basically samplerXXX/subpass/sampler/texture are all included
631 // if they are the global-scope-class, not the function parameter
632 // (or local, if they ever exist) class.
633 if (type.getBasicType() == glslang::EbtSampler)
634 return type.getQualifier().isUniformOrBuffer();
635
636 // None of the above.
637 return false;
638}
639
John Kesseniche0b6cad2015-12-24 10:30:13 -0700640void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
641{
642 if (child.layoutMatrix == glslang::ElmNone)
643 child.layoutMatrix = parent.layoutMatrix;
644
645 if (parent.invariant)
646 child.invariant = true;
647 if (parent.nopersp)
648 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800649#ifdef AMD_EXTENSIONS
650 if (parent.explicitInterp)
651 child.explicitInterp = true;
652#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700653 if (parent.flat)
654 child.flat = true;
655 if (parent.centroid)
656 child.centroid = true;
657 if (parent.patch)
658 child.patch = true;
659 if (parent.sample)
660 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800661 if (parent.coherent)
662 child.coherent = true;
663 if (parent.volatil)
664 child.volatil = true;
665 if (parent.restrict)
666 child.restrict = true;
667 if (parent.readonly)
668 child.readonly = true;
669 if (parent.writeonly)
670 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700671}
672
673bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
674{
John Kessenich7b9fa252016-01-21 18:56:57 -0700675 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700676 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600677 // - affect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700678 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600679 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700680}
681
John Kessenich140f3df2015-06-26 16:58:36 -0600682//
683// Implement the TGlslangToSpvTraverser class.
684//
685
Lei Zhang17535f72016-05-04 15:55:59 -0400686TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
687 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
688 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600689 inMain(false), mainTerminated(false), linkageOnly(false),
690 glslangIntermediate(glslangIntermediate)
691{
692 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
693
694 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700695 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600696 stdBuiltins = builder.import("GLSL.std.450");
697 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700698 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
699 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600700
701 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600702 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
703 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600704 builder.addSourceExtension(it->c_str());
705
706 // Add the top-level modes for this shader.
707
John Kessenich92187592016-02-01 13:45:25 -0700708 if (glslangIntermediate->getXfbMode()) {
709 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600710 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700711 }
John Kessenich140f3df2015-06-26 16:58:36 -0600712
713 unsigned int mode;
714 switch (glslangIntermediate->getStage()) {
715 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600716 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600717 break;
718
719 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600720 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600721 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
722 break;
723
724 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600725 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600726 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700727 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
728 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
729 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600730 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600731 }
John Kessenich4016e382016-07-15 11:53:56 -0600732 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600733 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
734
John Kesseniche6903322015-10-13 16:29:02 -0600735 switch (glslangIntermediate->getVertexSpacing()) {
736 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
737 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
738 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600739 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600740 }
John Kessenich4016e382016-07-15 11:53:56 -0600741 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600742 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
743
744 switch (glslangIntermediate->getVertexOrder()) {
745 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
746 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600747 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600748 }
John Kessenich4016e382016-07-15 11:53:56 -0600749 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600750 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
751
752 if (glslangIntermediate->getPointMode())
753 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600754 break;
755
756 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600757 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600758 switch (glslangIntermediate->getInputPrimitive()) {
759 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
760 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
761 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700762 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600763 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600764 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600765 }
John Kessenich4016e382016-07-15 11:53:56 -0600766 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600767 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600768
John Kessenich140f3df2015-06-26 16:58:36 -0600769 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
770
771 switch (glslangIntermediate->getOutputPrimitive()) {
772 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
773 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
774 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600775 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600776 }
John Kessenich4016e382016-07-15 11:53:56 -0600777 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600778 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
779 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
780 break;
781
782 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600783 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600784 if (glslangIntermediate->getPixelCenterInteger())
785 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600786
John Kessenich140f3df2015-06-26 16:58:36 -0600787 if (glslangIntermediate->getOriginUpperLeft())
788 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600789 else
790 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600791
792 if (glslangIntermediate->getEarlyFragmentTests())
793 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
794
795 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600796 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
797 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600798 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600799 }
John Kessenich4016e382016-07-15 11:53:56 -0600800 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600801 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
802
803 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
804 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600805 break;
806
807 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600808 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600809 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
810 glslangIntermediate->getLocalSize(1),
811 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600812 break;
813
814 default:
815 break;
816 }
817
818}
819
John Kessenich7ba63412015-12-20 17:37:07 -0700820// Finish everything and dump
821void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
822{
823 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100824 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
825 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700826
qiningda397332016-03-09 19:54:03 -0500827 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700828 builder.dump(out);
829}
830
John Kessenich140f3df2015-06-26 16:58:36 -0600831TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
832{
833 if (! mainTerminated) {
834 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
835 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600836 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600837 }
838}
839
840//
841// Implement the traversal functions.
842//
843// Return true from interior nodes to have the external traversal
844// continue on to children. Return false if children were
845// already processed.
846//
847
848//
qining25262b32016-05-06 17:25:16 -0400849// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600850// - uniform/input reads
851// - output writes
852// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
853// - something simple that degenerates into the last bullet
854//
855void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
856{
qining75d1d802016-04-06 14:42:01 -0400857 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
858 if (symbol->getType().getQualifier().isSpecConstant())
859 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
860
John Kessenich140f3df2015-06-26 16:58:36 -0600861 // getSymbolId() will set up all the IO decorations on the first call.
862 // Formal function parameters were mapped during makeFunctions().
863 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700864
865 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
866 if (builder.isPointer(id)) {
867 spv::StorageClass sc = builder.getStorageClass(id);
868 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
869 iOSet.insert(id);
870 }
871
872 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700873 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600874 // Prepare to generate code for the access
875
876 // L-value chains will be computed left to right. We're on the symbol now,
877 // which is the left-most part of the access chain, so now is "clear" time,
878 // followed by setting the base.
879 builder.clearAccessChain();
880
881 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700882 // except for
883 // A) "const in" arguments to a function, which are an intermediate object.
884 // See comments in handleUserFunctionCall().
885 // B) Specialization constants (normal constant don't even come in as a variable),
886 // These are also pure R-values.
887 glslang::TQualifier qualifier = symbol->getQualifier();
888 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
889 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600890 builder.setAccessChainRValue(id);
891 else
892 builder.setAccessChainLValue(id);
893 }
894}
895
896bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
897{
qining40887662016-04-03 22:20:42 -0400898 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
899 if (node->getType().getQualifier().isSpecConstant())
900 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
901
John Kessenich140f3df2015-06-26 16:58:36 -0600902 // First, handle special cases
903 switch (node->getOp()) {
904 case glslang::EOpAssign:
905 case glslang::EOpAddAssign:
906 case glslang::EOpSubAssign:
907 case glslang::EOpMulAssign:
908 case glslang::EOpVectorTimesMatrixAssign:
909 case glslang::EOpVectorTimesScalarAssign:
910 case glslang::EOpMatrixTimesScalarAssign:
911 case glslang::EOpMatrixTimesMatrixAssign:
912 case glslang::EOpDivAssign:
913 case glslang::EOpModAssign:
914 case glslang::EOpAndAssign:
915 case glslang::EOpInclusiveOrAssign:
916 case glslang::EOpExclusiveOrAssign:
917 case glslang::EOpLeftShiftAssign:
918 case glslang::EOpRightShiftAssign:
919 // A bin-op assign "a += b" means the same thing as "a = a + b"
920 // where a is evaluated before b. For a simple assignment, GLSL
921 // says to evaluate the left before the right. So, always, left
922 // node then right node.
923 {
924 // get the left l-value, save it away
925 builder.clearAccessChain();
926 node->getLeft()->traverse(this);
927 spv::Builder::AccessChain lValue = builder.getAccessChain();
928
929 // evaluate the right
930 builder.clearAccessChain();
931 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700932 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600933
934 if (node->getOp() != glslang::EOpAssign) {
935 // the left is also an r-value
936 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700937 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600938
939 // do the operation
qining25262b32016-05-06 17:25:16 -0400940 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
941 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600942 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
943 node->getType().getBasicType());
944
945 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700946 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948
949 // store the result
950 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800951 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600952
953 // assignments are expressions having an rValue after they are evaluated...
954 builder.clearAccessChain();
955 builder.setAccessChainRValue(rValue);
956 }
957 return false;
958 case glslang::EOpIndexDirect:
959 case glslang::EOpIndexDirectStruct:
960 {
961 // Get the left part of the access chain.
962 node->getLeft()->traverse(this);
963
964 // Add the next element in the chain
965
David Netoa901ffe2016-06-08 14:11:40 +0100966 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600967 if (! node->getLeft()->getType().isArray() &&
968 node->getLeft()->getType().isVector() &&
969 node->getOp() == glslang::EOpIndexDirect) {
970 // This is essentially a hard-coded vector swizzle of size 1,
971 // so short circuit the access-chain stuff with a swizzle.
972 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100973 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600974 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600975 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100976 int spvIndex = glslangIndex;
977 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
978 node->getOp() == glslang::EOpIndexDirectStruct)
979 {
980 // This may be, e.g., an anonymous block-member selection, which generally need
981 // index remapping due to hidden members in anonymous blocks.
982 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
983 assert(remapper.size() > 0);
984 spvIndex = remapper[glslangIndex];
985 }
John Kessenichebb50532016-05-16 19:22:05 -0600986
David Netoa901ffe2016-06-08 14:11:40 +0100987 // normal case for indexing array or structure or block
988 builder.accessChainPush(builder.makeIntConstant(spvIndex));
989
990 // Add capabilities here for accessing PointSize and clip/cull distance.
991 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600992 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100993 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600994 }
995 }
996 return false;
997 case glslang::EOpIndexIndirect:
998 {
999 // Structure or array or vector indirection.
1000 // Will use native SPIR-V access-chain for struct and array indirection;
1001 // matrices are arrays of vectors, so will also work for a matrix.
1002 // Will use the access chain's 'component' for variable index into a vector.
1003
1004 // This adapter is building access chains left to right.
1005 // Set up the access chain to the left.
1006 node->getLeft()->traverse(this);
1007
1008 // save it so that computing the right side doesn't trash it
1009 spv::Builder::AccessChain partial = builder.getAccessChain();
1010
1011 // compute the next index in the chain
1012 builder.clearAccessChain();
1013 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001014 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001015
1016 // restore the saved access chain
1017 builder.setAccessChain(partial);
1018
1019 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001020 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001021 else
John Kessenichfa668da2015-09-13 14:46:30 -06001022 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001023 }
1024 return false;
1025 case glslang::EOpVectorSwizzle:
1026 {
1027 node->getLeft()->traverse(this);
1028 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
1029 std::vector<unsigned> swizzle;
1030 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1031 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -06001032 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001033 }
1034 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001035 case glslang::EOpLogicalOr:
1036 case glslang::EOpLogicalAnd:
1037 {
1038
1039 // These may require short circuiting, but can sometimes be done as straight
1040 // binary operations. The right operand must be short circuited if it has
1041 // side effects, and should probably be if it is complex.
1042 if (isTrivial(node->getRight()->getAsTyped()))
1043 break; // handle below as a normal binary operation
1044 // otherwise, we need to do dynamic short circuiting on the right operand
1045 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1046 builder.clearAccessChain();
1047 builder.setAccessChainRValue(result);
1048 }
1049 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001050 default:
1051 break;
1052 }
1053
1054 // Assume generic binary op...
1055
John Kessenich32cfd492016-02-02 12:37:46 -07001056 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001057 builder.clearAccessChain();
1058 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001059 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001060
John Kessenich32cfd492016-02-02 12:37:46 -07001061 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001062 builder.clearAccessChain();
1063 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001064 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001065
John Kessenich32cfd492016-02-02 12:37:46 -07001066 // get result
1067 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001068 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001069 convertGlslangToSpvType(node->getType()), left, right,
1070 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001071
John Kessenich50e57562015-12-21 21:21:11 -07001072 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001073 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001074 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001075 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001076 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001078 return false;
1079 }
John Kessenich140f3df2015-06-26 16:58:36 -06001080}
1081
1082bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1083{
qining40887662016-04-03 22:20:42 -04001084 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1085 if (node->getType().getQualifier().isSpecConstant())
1086 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1087
John Kessenichfc51d282015-08-19 13:34:18 -06001088 spv::Id result = spv::NoResult;
1089
1090 // try texturing first
1091 result = createImageTextureFunctionCall(node);
1092 if (result != spv::NoResult) {
1093 builder.clearAccessChain();
1094 builder.setAccessChainRValue(result);
1095
1096 return false; // done with this node
1097 }
1098
1099 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001100
1101 if (node->getOp() == glslang::EOpArrayLength) {
1102 // Quite special; won't want to evaluate the operand.
1103
1104 // Normal .length() would have been constant folded by the front-end.
1105 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001106 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001107 assert(node->getOperand()->getType().isRuntimeSizedArray());
1108 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1109 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001110 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1111 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001112
1113 builder.clearAccessChain();
1114 builder.setAccessChainRValue(length);
1115
1116 return false;
1117 }
1118
John Kessenichfc51d282015-08-19 13:34:18 -06001119 // Start by evaluating the operand
1120
John Kessenich140f3df2015-06-26 16:58:36 -06001121 builder.clearAccessChain();
1122 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001123
Rex Xufc618912015-09-09 16:42:49 +08001124 spv::Id operand = spv::NoResult;
1125
1126 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1127 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001128 node->getOp() == glslang::EOpAtomicCounter ||
1129 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001130 operand = builder.accessChainGetLValue(); // Special case l-value operands
1131 else
John Kessenich32cfd492016-02-02 12:37:46 -07001132 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001133
1134 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001135 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001136
1137 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001138 if (! result)
Rex Xu73e3ce72016-04-27 18:48:17 +08001139 result = createConversion(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001140
1141 // if not, then possibly an operation
1142 if (! result)
qining25262b32016-05-06 17:25:16 -04001143 result = createUnaryOperation(node->getOp(), precision, noContraction, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 if (result) {
1146 builder.clearAccessChain();
1147 builder.setAccessChainRValue(result);
1148
1149 return false; // done with this node
1150 }
1151
1152 // it must be a special case, check...
1153 switch (node->getOp()) {
1154 case glslang::EOpPostIncrement:
1155 case glslang::EOpPostDecrement:
1156 case glslang::EOpPreIncrement:
1157 case glslang::EOpPreDecrement:
1158 {
1159 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001160 spv::Id one = 0;
1161 if (node->getBasicType() == glslang::EbtFloat)
1162 one = builder.makeFloatConstant(1.0F);
1163 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1164 one = builder.makeInt64Constant(1);
1165 else
1166 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001167 glslang::TOperator op;
1168 if (node->getOp() == glslang::EOpPreIncrement ||
1169 node->getOp() == glslang::EOpPostIncrement)
1170 op = glslang::EOpAdd;
1171 else
1172 op = glslang::EOpSub;
1173
qining25262b32016-05-06 17:25:16 -04001174 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1175 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001176 convertGlslangToSpvType(node->getType()), operand, one,
1177 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001178 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001179
1180 // The result of operation is always stored, but conditionally the
1181 // consumed result. The consumed result is always an r-value.
1182 builder.accessChainStore(result);
1183 builder.clearAccessChain();
1184 if (node->getOp() == glslang::EOpPreIncrement ||
1185 node->getOp() == glslang::EOpPreDecrement)
1186 builder.setAccessChainRValue(result);
1187 else
1188 builder.setAccessChainRValue(operand);
1189 }
1190
1191 return false;
1192
1193 case glslang::EOpEmitStreamVertex:
1194 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1195 return false;
1196 case glslang::EOpEndStreamPrimitive:
1197 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1198 return false;
1199
1200 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001201 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001202 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001203 }
John Kessenich140f3df2015-06-26 16:58:36 -06001204}
1205
1206bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1207{
qining27e04a02016-04-14 16:40:20 -04001208 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1209 if (node->getType().getQualifier().isSpecConstant())
1210 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1211
John Kessenichfc51d282015-08-19 13:34:18 -06001212 spv::Id result = spv::NoResult;
1213
1214 // try texturing
1215 result = createImageTextureFunctionCall(node);
1216 if (result != spv::NoResult) {
1217 builder.clearAccessChain();
1218 builder.setAccessChainRValue(result);
1219
1220 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001221 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001222 // "imageStore" is a special case, which has no result
1223 return false;
1224 }
John Kessenichfc51d282015-08-19 13:34:18 -06001225
John Kessenich140f3df2015-06-26 16:58:36 -06001226 glslang::TOperator binOp = glslang::EOpNull;
1227 bool reduceComparison = true;
1228 bool isMatrix = false;
1229 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001230 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001231
1232 assert(node->getOp());
1233
1234 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1235
1236 switch (node->getOp()) {
1237 case glslang::EOpSequence:
1238 {
1239 if (preVisit)
1240 ++sequenceDepth;
1241 else
1242 --sequenceDepth;
1243
1244 if (sequenceDepth == 1) {
1245 // If this is the parent node of all the functions, we want to see them
1246 // early, so all call points have actual SPIR-V functions to reference.
1247 // In all cases, still let the traverser visit the children for us.
1248 makeFunctions(node->getAsAggregate()->getSequence());
1249
1250 // Also, we want all globals initializers to go into the entry of main(), before
1251 // anything else gets there, so visit out of order, doing them all now.
1252 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1253
1254 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1255 // so do them manually.
1256 visitFunctions(node->getAsAggregate()->getSequence());
1257
1258 return false;
1259 }
1260
1261 return true;
1262 }
1263 case glslang::EOpLinkerObjects:
1264 {
1265 if (visit == glslang::EvPreVisit)
1266 linkageOnly = true;
1267 else
1268 linkageOnly = false;
1269
1270 return true;
1271 }
1272 case glslang::EOpComma:
1273 {
1274 // processing from left to right naturally leaves the right-most
1275 // lying around in the access chain
1276 glslang::TIntermSequence& glslangOperands = node->getSequence();
1277 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1278 glslangOperands[i]->traverse(this);
1279
1280 return false;
1281 }
1282 case glslang::EOpFunction:
1283 if (visit == glslang::EvPreVisit) {
1284 if (isShaderEntrypoint(node)) {
1285 inMain = true;
1286 builder.setBuildPoint(shaderEntry->getLastBlock());
1287 } else {
1288 handleFunctionEntry(node);
1289 }
1290 } else {
1291 if (inMain)
1292 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001293 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001294 inMain = false;
1295 }
1296
1297 return true;
1298 case glslang::EOpParameters:
1299 // Parameters will have been consumed by EOpFunction processing, but not
1300 // the body, so we still visited the function node's children, making this
1301 // child redundant.
1302 return false;
1303 case glslang::EOpFunctionCall:
1304 {
1305 if (node->isUserDefined())
1306 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001307 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1308 if (result) {
1309 builder.clearAccessChain();
1310 builder.setAccessChainRValue(result);
1311 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001312 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001313
1314 return false;
1315 }
1316 case glslang::EOpConstructMat2x2:
1317 case glslang::EOpConstructMat2x3:
1318 case glslang::EOpConstructMat2x4:
1319 case glslang::EOpConstructMat3x2:
1320 case glslang::EOpConstructMat3x3:
1321 case glslang::EOpConstructMat3x4:
1322 case glslang::EOpConstructMat4x2:
1323 case glslang::EOpConstructMat4x3:
1324 case glslang::EOpConstructMat4x4:
1325 case glslang::EOpConstructDMat2x2:
1326 case glslang::EOpConstructDMat2x3:
1327 case glslang::EOpConstructDMat2x4:
1328 case glslang::EOpConstructDMat3x2:
1329 case glslang::EOpConstructDMat3x3:
1330 case glslang::EOpConstructDMat3x4:
1331 case glslang::EOpConstructDMat4x2:
1332 case glslang::EOpConstructDMat4x3:
1333 case glslang::EOpConstructDMat4x4:
1334 isMatrix = true;
1335 // fall through
1336 case glslang::EOpConstructFloat:
1337 case glslang::EOpConstructVec2:
1338 case glslang::EOpConstructVec3:
1339 case glslang::EOpConstructVec4:
1340 case glslang::EOpConstructDouble:
1341 case glslang::EOpConstructDVec2:
1342 case glslang::EOpConstructDVec3:
1343 case glslang::EOpConstructDVec4:
1344 case glslang::EOpConstructBool:
1345 case glslang::EOpConstructBVec2:
1346 case glslang::EOpConstructBVec3:
1347 case glslang::EOpConstructBVec4:
1348 case glslang::EOpConstructInt:
1349 case glslang::EOpConstructIVec2:
1350 case glslang::EOpConstructIVec3:
1351 case glslang::EOpConstructIVec4:
1352 case glslang::EOpConstructUint:
1353 case glslang::EOpConstructUVec2:
1354 case glslang::EOpConstructUVec3:
1355 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001356 case glslang::EOpConstructInt64:
1357 case glslang::EOpConstructI64Vec2:
1358 case glslang::EOpConstructI64Vec3:
1359 case glslang::EOpConstructI64Vec4:
1360 case glslang::EOpConstructUint64:
1361 case glslang::EOpConstructU64Vec2:
1362 case glslang::EOpConstructU64Vec3:
1363 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001364 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001365 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001366 {
1367 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001368 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001369 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1370 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001371 if (node->getOp() == glslang::EOpConstructTextureSampler)
1372 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1373 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001374 std::vector<spv::Id> constituents;
1375 for (int c = 0; c < (int)arguments.size(); ++c)
1376 constituents.push_back(arguments[c]);
1377 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001378 } else if (isMatrix)
1379 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1380 else
1381 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 builder.clearAccessChain();
1384 builder.setAccessChainRValue(constructed);
1385
1386 return false;
1387 }
1388
1389 // These six are component-wise compares with component-wise results.
1390 // Forward on to createBinaryOperation(), requesting a vector result.
1391 case glslang::EOpLessThan:
1392 case glslang::EOpGreaterThan:
1393 case glslang::EOpLessThanEqual:
1394 case glslang::EOpGreaterThanEqual:
1395 case glslang::EOpVectorEqual:
1396 case glslang::EOpVectorNotEqual:
1397 {
1398 // Map the operation to a binary
1399 binOp = node->getOp();
1400 reduceComparison = false;
1401 switch (node->getOp()) {
1402 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1403 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1404 default: binOp = node->getOp(); break;
1405 }
1406
1407 break;
1408 }
1409 case glslang::EOpMul:
qining25262b32016-05-06 17:25:16 -04001410 // compontent-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001411 binOp = glslang::EOpMul;
1412 break;
1413 case glslang::EOpOuterProduct:
1414 // two vectors multiplied to make a matrix
1415 binOp = glslang::EOpOuterProduct;
1416 break;
1417 case glslang::EOpDot:
1418 {
qining25262b32016-05-06 17:25:16 -04001419 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001420 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001421 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001422 binOp = glslang::EOpMul;
1423 break;
1424 }
1425 case glslang::EOpMod:
1426 // when an aggregate, this is the floating-point mod built-in function,
1427 // which can be emitted by the one in createBinaryOperation()
1428 binOp = glslang::EOpMod;
1429 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001430 case glslang::EOpEmitVertex:
1431 case glslang::EOpEndPrimitive:
1432 case glslang::EOpBarrier:
1433 case glslang::EOpMemoryBarrier:
1434 case glslang::EOpMemoryBarrierAtomicCounter:
1435 case glslang::EOpMemoryBarrierBuffer:
1436 case glslang::EOpMemoryBarrierImage:
1437 case glslang::EOpMemoryBarrierShared:
1438 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001439 case glslang::EOpAllMemoryBarrierWithGroupSync:
1440 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1441 case glslang::EOpWorkgroupMemoryBarrier:
1442 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001443 noReturnValue = true;
1444 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1445 break;
1446
John Kessenich426394d2015-07-23 10:22:48 -06001447 case glslang::EOpAtomicAdd:
1448 case glslang::EOpAtomicMin:
1449 case glslang::EOpAtomicMax:
1450 case glslang::EOpAtomicAnd:
1451 case glslang::EOpAtomicOr:
1452 case glslang::EOpAtomicXor:
1453 case glslang::EOpAtomicExchange:
1454 case glslang::EOpAtomicCompSwap:
1455 atomic = true;
1456 break;
1457
John Kessenich140f3df2015-06-26 16:58:36 -06001458 default:
1459 break;
1460 }
1461
1462 //
1463 // See if it maps to a regular operation.
1464 //
John Kessenich140f3df2015-06-26 16:58:36 -06001465 if (binOp != glslang::EOpNull) {
1466 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1467 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1468 assert(left && right);
1469
1470 builder.clearAccessChain();
1471 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001472 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001473
1474 builder.clearAccessChain();
1475 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001476 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001477
qining25262b32016-05-06 17:25:16 -04001478 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
1479 convertGlslangToSpvType(node->getType()), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001480 left->getType().getBasicType(), reduceComparison);
1481
1482 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001483 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001484 builder.clearAccessChain();
1485 builder.setAccessChainRValue(result);
1486
1487 return false;
1488 }
1489
John Kessenich426394d2015-07-23 10:22:48 -06001490 //
1491 // Create the list of operands.
1492 //
John Kessenich140f3df2015-06-26 16:58:36 -06001493 glslang::TIntermSequence& glslangOperands = node->getSequence();
1494 std::vector<spv::Id> operands;
1495 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1496 builder.clearAccessChain();
1497 glslangOperands[arg]->traverse(this);
1498
1499 // special case l-value operands; there are just a few
1500 bool lvalue = false;
1501 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001502 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001503 case glslang::EOpModf:
1504 if (arg == 1)
1505 lvalue = true;
1506 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001507 case glslang::EOpInterpolateAtSample:
1508 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001509#ifdef AMD_EXTENSIONS
1510 case glslang::EOpInterpolateAtVertex:
1511#endif
Rex Xu7a26c172015-12-08 17:12:09 +08001512 if (arg == 0)
1513 lvalue = true;
1514 break;
Rex Xud4782c12015-09-06 16:30:11 +08001515 case glslang::EOpAtomicAdd:
1516 case glslang::EOpAtomicMin:
1517 case glslang::EOpAtomicMax:
1518 case glslang::EOpAtomicAnd:
1519 case glslang::EOpAtomicOr:
1520 case glslang::EOpAtomicXor:
1521 case glslang::EOpAtomicExchange:
1522 case glslang::EOpAtomicCompSwap:
1523 if (arg == 0)
1524 lvalue = true;
1525 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001526 case glslang::EOpAddCarry:
1527 case glslang::EOpSubBorrow:
1528 if (arg == 2)
1529 lvalue = true;
1530 break;
1531 case glslang::EOpUMulExtended:
1532 case glslang::EOpIMulExtended:
1533 if (arg >= 2)
1534 lvalue = true;
1535 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001536 default:
1537 break;
1538 }
1539 if (lvalue)
1540 operands.push_back(builder.accessChainGetLValue());
1541 else
John Kessenich32cfd492016-02-02 12:37:46 -07001542 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001543 }
John Kessenich426394d2015-07-23 10:22:48 -06001544
1545 if (atomic) {
1546 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001547 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001548 } else {
1549 // Pass through to generic operations.
1550 switch (glslangOperands.size()) {
1551 case 0:
Rex Xu9d93a232016-05-05 12:30:44 +08001552 result = createNoArgOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()));
John Kessenich426394d2015-07-23 10:22:48 -06001553 break;
1554 case 1:
qining25262b32016-05-06 17:25:16 -04001555 result = createUnaryOperation(
1556 node->getOp(), precision,
1557 TranslateNoContractionDecoration(node->getType().getQualifier()),
1558 convertGlslangToSpvType(node->getType()), operands.front(),
1559 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001560 break;
1561 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001562 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001563 break;
1564 }
John Kessenich140f3df2015-06-26 16:58:36 -06001565 }
1566
1567 if (noReturnValue)
1568 return false;
1569
1570 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001571 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001572 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001573 } else {
1574 builder.clearAccessChain();
1575 builder.setAccessChainRValue(result);
1576 return false;
1577 }
1578}
1579
1580bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1581{
1582 // This path handles both if-then-else and ?:
1583 // The if-then-else has a node type of void, while
1584 // ?: has a non-void node type
1585 spv::Id result = 0;
1586 if (node->getBasicType() != glslang::EbtVoid) {
1587 // don't handle this as just on-the-fly temporaries, because there will be two names
1588 // and better to leave SSA to later passes
1589 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1590 }
1591
1592 // emit the condition before doing anything with selection
1593 node->getCondition()->traverse(this);
1594
1595 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001596 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001597
1598 if (node->getTrueBlock()) {
1599 // emit the "then" statement
1600 node->getTrueBlock()->traverse(this);
1601 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001602 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001603 }
1604
1605 if (node->getFalseBlock()) {
1606 ifBuilder.makeBeginElse();
1607 // emit the "else" statement
1608 node->getFalseBlock()->traverse(this);
1609 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001610 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001611 }
1612
1613 ifBuilder.makeEndIf();
1614
1615 if (result) {
1616 // GLSL only has r-values as the result of a :?, but
1617 // if we have an l-value, that can be more efficient if it will
1618 // become the base of a complex r-value expression, because the
1619 // next layer copies r-values into memory to use the access-chain mechanism
1620 builder.clearAccessChain();
1621 builder.setAccessChainLValue(result);
1622 }
1623
1624 return false;
1625}
1626
1627bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1628{
1629 // emit and get the condition before doing anything with switch
1630 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001631 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001632
1633 // browse the children to sort out code segments
1634 int defaultSegment = -1;
1635 std::vector<TIntermNode*> codeSegments;
1636 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1637 std::vector<int> caseValues;
1638 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1639 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1640 TIntermNode* child = *c;
1641 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001642 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001643 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001644 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001645 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1646 } else
1647 codeSegments.push_back(child);
1648 }
1649
qining25262b32016-05-06 17:25:16 -04001650 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001651 // statements between the last case and the end of the switch statement
1652 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1653 (int)codeSegments.size() == defaultSegment)
1654 codeSegments.push_back(nullptr);
1655
1656 // make the switch statement
1657 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001658 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001659
1660 // emit all the code in the segments
1661 breakForLoop.push(false);
1662 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1663 builder.nextSwitchSegment(segmentBlocks, s);
1664 if (codeSegments[s])
1665 codeSegments[s]->traverse(this);
1666 else
1667 builder.addSwitchBreak();
1668 }
1669 breakForLoop.pop();
1670
1671 builder.endSwitch(segmentBlocks);
1672
1673 return false;
1674}
1675
1676void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1677{
1678 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001679 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001680
1681 builder.clearAccessChain();
1682 builder.setAccessChainRValue(constant);
1683}
1684
1685bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1686{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001687 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001688 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001689 // Spec requires back edges to target header blocks, and every header block
1690 // must dominate its merge block. Make a header block first to ensure these
1691 // conditions are met. By definition, it will contain OpLoopMerge, followed
1692 // by a block-ending branch. But we don't want to put any other body/test
1693 // instructions in it, since the body/test may have arbitrary instructions,
1694 // including merges of its own.
1695 builder.setBuildPoint(&blocks.head);
1696 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001697 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001698 spv::Block& test = builder.makeNewBlock();
1699 builder.createBranch(&test);
1700
1701 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001702 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001703 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001704 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001705 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1706
1707 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001708 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001709 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001710 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001711 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001712 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001713
1714 builder.setBuildPoint(&blocks.continue_target);
1715 if (node->getTerminal())
1716 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001717 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001718 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001719 builder.createBranch(&blocks.body);
1720
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001721 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001722 builder.setBuildPoint(&blocks.body);
1723 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001724 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001725 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001726 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001727
1728 builder.setBuildPoint(&blocks.continue_target);
1729 if (node->getTerminal())
1730 node->getTerminal()->traverse(this);
1731 if (node->getTest()) {
1732 node->getTest()->traverse(this);
1733 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001734 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001735 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001736 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001737 // TODO: unless there was a break/return/discard instruction
1738 // somewhere in the body, this is an infinite loop, so we should
1739 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001740 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001741 }
John Kessenich140f3df2015-06-26 16:58:36 -06001742 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001743 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001744 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001745 return false;
1746}
1747
1748bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1749{
1750 if (node->getExpression())
1751 node->getExpression()->traverse(this);
1752
1753 switch (node->getFlowOp()) {
1754 case glslang::EOpKill:
1755 builder.makeDiscard();
1756 break;
1757 case glslang::EOpBreak:
1758 if (breakForLoop.top())
1759 builder.createLoopExit();
1760 else
1761 builder.addSwitchBreak();
1762 break;
1763 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001764 builder.createLoopContinue();
1765 break;
1766 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001767 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001768 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001769 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001770 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001771
1772 builder.clearAccessChain();
1773 break;
1774
1775 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001776 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001777 break;
1778 }
1779
1780 return false;
1781}
1782
1783spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1784{
qining25262b32016-05-06 17:25:16 -04001785 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001786 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001787 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001788 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001789 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001790 }
1791
1792 // Now, handle actual variables
1793 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1794 spv::Id spvType = convertGlslangToSpvType(node->getType());
1795
1796 const char* name = node->getName().c_str();
1797 if (glslang::IsAnonymous(name))
1798 name = "";
1799
1800 return builder.createVariable(storageClass, spvType, name);
1801}
1802
1803// Return type Id of the sampled type.
1804spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1805{
1806 switch (sampler.type) {
1807 case glslang::EbtFloat: return builder.makeFloatType(32);
1808 case glslang::EbtInt: return builder.makeIntType(32);
1809 case glslang::EbtUint: return builder.makeUintType(32);
1810 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001811 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001812 return builder.makeFloatType(32);
1813 }
1814}
1815
John Kessenich3ac051e2015-12-20 11:29:16 -07001816// Convert from a glslang type to an SPV type, by calling into a
1817// recursive version of this function. This establishes the inherited
1818// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001819spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1820{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001821 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001822}
1823
1824// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001825// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001826// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001827spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001828{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001829 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001830
1831 switch (type.getBasicType()) {
1832 case glslang::EbtVoid:
1833 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001834 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001835 break;
1836 case glslang::EbtFloat:
1837 spvType = builder.makeFloatType(32);
1838 break;
1839 case glslang::EbtDouble:
1840 spvType = builder.makeFloatType(64);
1841 break;
1842 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001843 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1844 // a 32-bit int where non-0 means true.
1845 if (explicitLayout != glslang::ElpNone)
1846 spvType = builder.makeUintType(32);
1847 else
1848 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001849 break;
1850 case glslang::EbtInt:
1851 spvType = builder.makeIntType(32);
1852 break;
1853 case glslang::EbtUint:
1854 spvType = builder.makeUintType(32);
1855 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001856 case glslang::EbtInt64:
1857 builder.addCapability(spv::CapabilityInt64);
1858 spvType = builder.makeIntType(64);
1859 break;
1860 case glslang::EbtUint64:
1861 builder.addCapability(spv::CapabilityInt64);
1862 spvType = builder.makeUintType(64);
1863 break;
John Kessenich426394d2015-07-23 10:22:48 -06001864 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001865 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001866 spvType = builder.makeUintType(32);
1867 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001868 case glslang::EbtSampler:
1869 {
1870 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001871 if (sampler.sampler) {
1872 // pure sampler
1873 spvType = builder.makeSamplerType();
1874 } else {
1875 // an image is present, make its type
1876 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1877 sampler.image ? 2 : 1, TranslateImageFormat(type));
1878 if (sampler.combined) {
1879 // already has both image and sampler, make the combined type
1880 spvType = builder.makeSampledImageType(spvType);
1881 }
John Kessenich55e7d112015-11-15 21:33:39 -07001882 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001883 }
John Kessenich140f3df2015-06-26 16:58:36 -06001884 break;
1885 case glslang::EbtStruct:
1886 case glslang::EbtBlock:
1887 {
1888 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001889 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001890
1891 // Try to share structs for different layouts, but not yet for other
1892 // kinds of qualification (primarily not yet including interpolant qualification).
1893 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001894 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001895 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001896 break;
1897
1898 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001899 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001900 memberRemapper[glslangMembers].resize(glslangMembers->size());
1901 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001902 }
1903 break;
1904 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001905 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001906 break;
1907 }
1908
1909 if (type.isMatrix())
1910 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1911 else {
1912 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1913 if (type.getVectorSize() > 1)
1914 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1915 }
1916
1917 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001918 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1919
John Kessenichc9a80832015-09-12 12:17:44 -06001920 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001921 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001922 // We need to decorate array strides for types needing explicit layout, except blocks.
1923 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001924 // Use a dummy glslang type for querying internal strides of
1925 // arrays of arrays, but using just a one-dimensional array.
1926 glslang::TType simpleArrayType(type, 0); // deference type of the array
1927 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1928 simpleArrayType.getArraySizes().dereference();
1929
1930 // Will compute the higher-order strides here, rather than making a whole
1931 // pile of types and doing repetitive recursion on their contents.
1932 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1933 }
John Kessenichf8842e52016-01-04 19:22:56 -07001934
1935 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001936 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001937 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001938 if (stride > 0)
1939 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001940 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001941 }
1942 } else {
1943 // single-dimensional array, and don't yet have stride
1944
John Kessenichf8842e52016-01-04 19:22:56 -07001945 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001946 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1947 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001948 }
John Kessenich31ed4832015-09-09 17:51:38 -06001949
John Kessenichc9a80832015-09-12 12:17:44 -06001950 // Do the outer dimension, which might not be known for a runtime-sized array
1951 if (type.isRuntimeSizedArray()) {
1952 spvType = builder.makeRuntimeArray(spvType);
1953 } else {
1954 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001955 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001956 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001957 if (stride > 0)
1958 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001959 }
1960
1961 return spvType;
1962}
1963
John Kessenich6090df02016-06-30 21:18:02 -06001964
1965// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
1966// explicitLayout can be kept the same throughout the hierarchical recursive walk.
1967// Mutually recursive with convertGlslangToSpvType().
1968spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
1969 const glslang::TTypeList* glslangMembers,
1970 glslang::TLayoutPacking explicitLayout,
1971 const glslang::TQualifier& qualifier)
1972{
1973 // Create a vector of struct types for SPIR-V to consume
1974 std::vector<spv::Id> spvMembers;
1975 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1976 int locationOffset = 0; // for use across struct members, when they are called recursively
1977 for (int i = 0; i < (int)glslangMembers->size(); i++) {
1978 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
1979 if (glslangMember.hiddenMember()) {
1980 ++memberDelta;
1981 if (type.getBasicType() == glslang::EbtBlock)
1982 memberRemapper[glslangMembers][i] = -1;
1983 } else {
1984 if (type.getBasicType() == glslang::EbtBlock)
1985 memberRemapper[glslangMembers][i] = i - memberDelta;
1986 // modify just this child's view of the qualifier
1987 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
1988 InheritQualifiers(memberQualifier, qualifier);
1989
1990 // manually inherit location; it's more complex
1991 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
1992 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1993 if (qualifier.hasLocation())
1994 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
1995
1996 // recurse
1997 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
1998 }
1999 }
2000
2001 // Make the SPIR-V type
2002 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
2003 if (! HasNonLayoutQualifiers(qualifier))
2004 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2005
2006 // Decorate it
2007 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2008
2009 return spvType;
2010}
2011
2012void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2013 const glslang::TTypeList* glslangMembers,
2014 glslang::TLayoutPacking explicitLayout,
2015 const glslang::TQualifier& qualifier,
2016 spv::Id spvType)
2017{
2018 // Name and decorate the non-hidden members
2019 int offset = -1;
2020 int locationOffset = 0; // for use within the members of this struct
2021 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2022 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2023 int member = i;
2024 if (type.getBasicType() == glslang::EbtBlock)
2025 member = memberRemapper[glslangMembers][i];
2026
2027 // modify just this child's view of the qualifier
2028 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2029 InheritQualifiers(memberQualifier, qualifier);
2030
2031 // using -1 above to indicate a hidden member
2032 if (member >= 0) {
2033 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2034 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2035 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2036 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2037 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2038 if (type.getBasicType() == glslang::EbtBlock) {
2039 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2040 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2041 }
2042 }
2043 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2044
2045 if (qualifier.storage == glslang::EvqBuffer) {
2046 std::vector<spv::Decoration> memory;
2047 TranslateMemoryDecoration(memberQualifier, memory);
2048 for (unsigned int i = 0; i < memory.size(); ++i)
2049 addMemberDecoration(spvType, member, memory[i]);
2050 }
2051
John Kessenich2f47bc92016-06-30 21:47:35 -06002052 // Compute location decoration; tricky based on whether inheritance is at play and
2053 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002054 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2055 // probably move to the linker stage of the front end proper, and just have the
2056 // answer sitting already distributed throughout the individual member locations.
2057 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002058 // Ignore member locations if the container is an array, as that's
2059 // ill-specified and decisions have been made to not allow this anyway.
2060 // The object itself must have a location, and that comes out from decorating the object,
2061 // not the type (this code decorates types).
2062 if (! type.isArray()) {
2063 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2064 // struct members should not have explicit locations
2065 assert(type.getBasicType() != glslang::EbtStruct);
2066 location = memberQualifier.layoutLocation;
2067 } else if (type.getBasicType() != glslang::EbtBlock) {
2068 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2069 // The members, and their nested types, must not themselves have Location decorations.
2070 } else if (qualifier.hasLocation()) // inheritance
2071 location = qualifier.layoutLocation + locationOffset;
2072 }
John Kessenich6090df02016-06-30 21:18:02 -06002073 if (location >= 0)
2074 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2075
John Kessenich2f47bc92016-06-30 21:47:35 -06002076 if (qualifier.hasLocation()) // track for upcoming inheritance
2077 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2078
John Kessenich6090df02016-06-30 21:18:02 -06002079 // component, XFB, others
2080 if (glslangMember.getQualifier().hasComponent())
2081 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2082 if (glslangMember.getQualifier().hasXfbOffset())
2083 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2084 else if (explicitLayout != glslang::ElpNone) {
2085 // figure out what to do with offset, which is accumulating
2086 int nextOffset;
2087 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2088 if (offset >= 0)
2089 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2090 offset = nextOffset;
2091 }
2092
2093 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2094 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2095
2096 // built-in variable decorations
2097 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002098 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002099 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2100 }
2101 }
2102
2103 // Decorate the structure
2104 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2105 addDecoration(spvType, TranslateBlockDecoration(type));
2106 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2107 builder.addCapability(spv::CapabilityGeometryStreams);
2108 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2109 }
2110 if (glslangIntermediate->getXfbMode()) {
2111 builder.addCapability(spv::CapabilityTransformFeedback);
2112 if (type.getQualifier().hasXfbStride())
2113 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2114 if (type.getQualifier().hasXfbBuffer())
2115 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2116 }
2117}
2118
John Kessenich6c292d32016-02-15 20:58:50 -07002119// Turn the expression forming the array size into an id.
2120// This is not quite trivial, because of specialization constants.
2121// Sometimes, a raw constant is turned into an Id, and sometimes
2122// a specialization constant expression is.
2123spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2124{
2125 // First, see if this is sized with a node, meaning a specialization constant:
2126 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2127 if (specNode != nullptr) {
2128 builder.clearAccessChain();
2129 specNode->traverse(this);
2130 return accessChainLoad(specNode->getAsTyped()->getType());
2131 }
qining25262b32016-05-06 17:25:16 -04002132
John Kessenich6c292d32016-02-15 20:58:50 -07002133 // Otherwise, need a compile-time (front end) size, get it:
2134 int size = arraySizes.getDimSize(dim);
2135 assert(size > 0);
2136 return builder.makeUintConstant(size);
2137}
2138
John Kessenich103bef92016-02-08 21:38:15 -07002139// Wrap the builder's accessChainLoad to:
2140// - localize handling of RelaxedPrecision
2141// - use the SPIR-V inferred type instead of another conversion of the glslang type
2142// (avoids unnecessary work and possible type punning for structures)
2143// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002144spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2145{
John Kessenich103bef92016-02-08 21:38:15 -07002146 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2147 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2148
2149 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002150 if (type.getBasicType() == glslang::EbtBool) {
2151 if (builder.isScalarType(nominalTypeId)) {
2152 // Conversion for bool
2153 spv::Id boolType = builder.makeBoolType();
2154 if (nominalTypeId != boolType)
2155 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2156 } else if (builder.isVectorType(nominalTypeId)) {
2157 // Conversion for bvec
2158 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2159 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2160 if (nominalTypeId != bvecType)
2161 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2162 }
2163 }
John Kessenich103bef92016-02-08 21:38:15 -07002164
2165 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002166}
2167
Rex Xu27253232016-02-23 17:51:09 +08002168// Wrap the builder's accessChainStore to:
2169// - do conversion of concrete to abstract type
2170void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2171{
2172 // Need to convert to abstract types when necessary
2173 if (type.getBasicType() == glslang::EbtBool) {
2174 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2175
2176 if (builder.isScalarType(nominalTypeId)) {
2177 // Conversion for bool
2178 spv::Id boolType = builder.makeBoolType();
2179 if (nominalTypeId != boolType) {
2180 spv::Id zero = builder.makeUintConstant(0);
2181 spv::Id one = builder.makeUintConstant(1);
2182 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2183 }
2184 } else if (builder.isVectorType(nominalTypeId)) {
2185 // Conversion for bvec
2186 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2187 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2188 if (nominalTypeId != bvecType) {
2189 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2190 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2191 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2192 }
2193 }
2194 }
2195
2196 builder.accessChainStore(rvalue);
2197}
2198
John Kessenichf85e8062015-12-19 13:57:10 -07002199// Decide whether or not this type should be
2200// decorated with offsets and strides, and if so
2201// whether std140 or std430 rules should be applied.
2202glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002203{
John Kessenichf85e8062015-12-19 13:57:10 -07002204 // has to be a block
2205 if (type.getBasicType() != glslang::EbtBlock)
2206 return glslang::ElpNone;
2207
2208 // has to be a uniform or buffer block
2209 if (type.getQualifier().storage != glslang::EvqUniform &&
2210 type.getQualifier().storage != glslang::EvqBuffer)
2211 return glslang::ElpNone;
2212
2213 // return the layout to use
2214 switch (type.getQualifier().layoutPacking) {
2215 case glslang::ElpStd140:
2216 case glslang::ElpStd430:
2217 return type.getQualifier().layoutPacking;
2218 default:
2219 return glslang::ElpNone;
2220 }
John Kessenich31ed4832015-09-09 17:51:38 -06002221}
2222
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002223// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002224int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002225{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002226 int size;
John Kessenich49987892015-12-29 17:11:44 -07002227 int stride;
2228 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002229
2230 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002231}
2232
John Kessenich49987892015-12-29 17:11:44 -07002233// 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 -07002234// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002235int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002236{
John Kessenich49987892015-12-29 17:11:44 -07002237 glslang::TType elementType;
2238 elementType.shallowCopy(matrixType);
2239 elementType.clearArraySizes();
2240
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002241 int size;
John Kessenich49987892015-12-29 17:11:44 -07002242 int stride;
2243 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2244
2245 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002246}
2247
John Kessenich5e4b1242015-08-06 22:53:06 -06002248// Given a member type of a struct, realign the current offset for it, and compute
2249// the next (not yet aligned) offset for the next member, which will get aligned
2250// on the next call.
2251// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2252// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2253// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002254void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002255 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002256{
2257 // this will get a positive value when deemed necessary
2258 nextOffset = -1;
2259
John Kessenich5e4b1242015-08-06 22:53:06 -06002260 // override anything in currentOffset with user-set offset
2261 if (memberType.getQualifier().hasOffset())
2262 currentOffset = memberType.getQualifier().layoutOffset;
2263
2264 // It could be that current linker usage in glslang updated all the layoutOffset,
2265 // in which case the following code does not matter. But, that's not quite right
2266 // once cross-compilation unit GLSL validation is done, as the original user
2267 // settings are needed in layoutOffset, and then the following will come into play.
2268
John Kessenichf85e8062015-12-19 13:57:10 -07002269 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002270 if (! memberType.getQualifier().hasOffset())
2271 currentOffset = -1;
2272
2273 return;
2274 }
2275
John Kessenichf85e8062015-12-19 13:57:10 -07002276 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002277 if (currentOffset < 0)
2278 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002279
John Kessenich5e4b1242015-08-06 22:53:06 -06002280 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2281 // but possibly not yet correctly aligned.
2282
2283 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002284 int dummyStride;
2285 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002286 glslang::RoundToPow2(currentOffset, memberAlignment);
2287 nextOffset = currentOffset + memberSize;
2288}
2289
David Netoa901ffe2016-06-08 14:11:40 +01002290void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002291{
David Netoa901ffe2016-06-08 14:11:40 +01002292 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2293 switch (glslangBuiltIn)
2294 {
2295 case glslang::EbvClipDistance:
2296 case glslang::EbvCullDistance:
2297 case glslang::EbvPointSize:
2298 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2299 // Alternately, we could just call this for any glslang built-in, since the
2300 // capability already guards against duplicates.
2301 TranslateBuiltInDecoration(glslangBuiltIn, false);
2302 break;
2303 default:
2304 // Capabilities were already generated when the struct was declared.
2305 break;
2306 }
John Kessenichebb50532016-05-16 19:22:05 -06002307}
2308
John Kessenich140f3df2015-06-26 16:58:36 -06002309bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2310{
John Kessenich4d65ee32016-03-12 18:17:47 -07002311 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002312 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002313 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002314}
2315
2316// Make all the functions, skeletally, without actually visiting their bodies.
2317void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2318{
2319 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2320 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2321 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2322 continue;
2323
2324 // We're on a user function. Set up the basic interface for the function now,
2325 // so that it's available to call.
2326 // Translating the body will happen later.
2327 //
qining25262b32016-05-06 17:25:16 -04002328 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002329 // function. What it is an address of varies:
2330 //
2331 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2332 // so that write needs to be to a copy, hence the address of a copy works.
2333 //
2334 // - "const in" parameters can just be the r-value, as no writes need occur.
2335 //
2336 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2337 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2338
2339 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002340 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002341 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2342
2343 for (int p = 0; p < (int)parameters.size(); ++p) {
2344 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2345 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002346 if (paramType.isOpaque())
2347 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2348 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002349 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2350 else
2351 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002352 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002353 paramTypes.push_back(typeId);
2354 }
2355
2356 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002357 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2358 convertGlslangToSpvType(glslFunction->getType()),
2359 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002360
2361 // Track function to emit/call later
2362 functionMap[glslFunction->getName().c_str()] = function;
2363
2364 // Set the parameter id's
2365 for (int p = 0; p < (int)parameters.size(); ++p) {
2366 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2367 // give a name too
2368 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2369 }
2370 }
2371}
2372
2373// Process all the initializers, while skipping the functions and link objects
2374void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2375{
2376 builder.setBuildPoint(shaderEntry->getLastBlock());
2377 for (int i = 0; i < (int)initializers.size(); ++i) {
2378 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2379 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2380
2381 // We're on a top-level node that's not a function. Treat as an initializer, whose
2382 // code goes into the beginning of main.
2383 initializer->traverse(this);
2384 }
2385 }
2386}
2387
2388// Process all the functions, while skipping initializers.
2389void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2390{
2391 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2392 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2393 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2394 node->traverse(this);
2395 }
2396}
2397
2398void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2399{
qining25262b32016-05-06 17:25:16 -04002400 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002401 // that called makeFunctions().
2402 spv::Function* function = functionMap[node->getName().c_str()];
2403 spv::Block* functionBlock = function->getEntryBlock();
2404 builder.setBuildPoint(functionBlock);
2405}
2406
Rex Xu04db3f52015-09-16 11:44:02 +08002407void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002408{
Rex Xufc618912015-09-09 16:42:49 +08002409 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002410
2411 glslang::TSampler sampler = {};
2412 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002413 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002414 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2415 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2416 }
2417
John Kessenich140f3df2015-06-26 16:58:36 -06002418 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2419 builder.clearAccessChain();
2420 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002421
2422 // Special case l-value operands
2423 bool lvalue = false;
2424 switch (node.getOp()) {
2425 case glslang::EOpImageAtomicAdd:
2426 case glslang::EOpImageAtomicMin:
2427 case glslang::EOpImageAtomicMax:
2428 case glslang::EOpImageAtomicAnd:
2429 case glslang::EOpImageAtomicOr:
2430 case glslang::EOpImageAtomicXor:
2431 case glslang::EOpImageAtomicExchange:
2432 case glslang::EOpImageAtomicCompSwap:
2433 if (i == 0)
2434 lvalue = true;
2435 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002436 case glslang::EOpSparseImageLoad:
2437 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2438 lvalue = true;
2439 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002440 case glslang::EOpSparseTexture:
2441 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2442 lvalue = true;
2443 break;
2444 case glslang::EOpSparseTextureClamp:
2445 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2446 lvalue = true;
2447 break;
2448 case glslang::EOpSparseTextureLod:
2449 case glslang::EOpSparseTextureOffset:
2450 if (i == 3)
2451 lvalue = true;
2452 break;
2453 case glslang::EOpSparseTextureFetch:
2454 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2455 lvalue = true;
2456 break;
2457 case glslang::EOpSparseTextureFetchOffset:
2458 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2459 lvalue = true;
2460 break;
2461 case glslang::EOpSparseTextureLodOffset:
2462 case glslang::EOpSparseTextureGrad:
2463 case glslang::EOpSparseTextureOffsetClamp:
2464 if (i == 4)
2465 lvalue = true;
2466 break;
2467 case glslang::EOpSparseTextureGradOffset:
2468 case glslang::EOpSparseTextureGradClamp:
2469 if (i == 5)
2470 lvalue = true;
2471 break;
2472 case glslang::EOpSparseTextureGradOffsetClamp:
2473 if (i == 6)
2474 lvalue = true;
2475 break;
2476 case glslang::EOpSparseTextureGather:
2477 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2478 lvalue = true;
2479 break;
2480 case glslang::EOpSparseTextureGatherOffset:
2481 case glslang::EOpSparseTextureGatherOffsets:
2482 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2483 lvalue = true;
2484 break;
Rex Xufc618912015-09-09 16:42:49 +08002485 default:
2486 break;
2487 }
2488
Rex Xu6b86d492015-09-16 17:48:22 +08002489 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002490 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002491 else
John Kessenich32cfd492016-02-02 12:37:46 -07002492 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002493 }
2494}
2495
John Kessenichfc51d282015-08-19 13:34:18 -06002496void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002497{
John Kessenichfc51d282015-08-19 13:34:18 -06002498 builder.clearAccessChain();
2499 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002500 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002501}
John Kessenich140f3df2015-06-26 16:58:36 -06002502
John Kessenichfc51d282015-08-19 13:34:18 -06002503spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2504{
Rex Xufc618912015-09-09 16:42:49 +08002505 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002506 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002507 }
2508
John Kessenichfc51d282015-08-19 13:34:18 -06002509 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002510 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2511 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2512 std::vector<spv::Id> arguments;
2513 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002514 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002515 else
2516 translateArguments(*node->getAsUnaryNode(), arguments);
2517 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2518
2519 spv::Builder::TextureParameters params = { };
2520 params.sampler = arguments[0];
2521
Rex Xu04db3f52015-09-16 11:44:02 +08002522 glslang::TCrackedTextureOp cracked;
2523 node->crackTexture(sampler, cracked);
2524
John Kessenichfc51d282015-08-19 13:34:18 -06002525 // Check for queries
2526 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002527 // a sampled image needs to have the image extracted first
2528 if (builder.isSampledImage(params.sampler))
2529 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002530 switch (node->getOp()) {
2531 case glslang::EOpImageQuerySize:
2532 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002533 if (arguments.size() > 1) {
2534 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002535 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002536 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002537 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002538 case glslang::EOpImageQuerySamples:
2539 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002540 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002541 case glslang::EOpTextureQueryLod:
2542 params.coords = arguments[1];
2543 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2544 case glslang::EOpTextureQueryLevels:
2545 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002546 case glslang::EOpSparseTexelsResident:
2547 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002548 default:
2549 assert(0);
2550 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002551 }
John Kessenich140f3df2015-06-26 16:58:36 -06002552 }
2553
Rex Xufc618912015-09-09 16:42:49 +08002554 // Check for image functions other than queries
2555 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002556 std::vector<spv::Id> operands;
2557 auto opIt = arguments.begin();
2558 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002559
2560 // Handle subpass operations
2561 // TODO: GLSL should change to have the "MS" only on the type rather than the
2562 // built-in function.
2563 if (cracked.subpass) {
2564 // add on the (0,0) coordinate
2565 spv::Id zero = builder.makeIntConstant(0);
2566 std::vector<spv::Id> comps;
2567 comps.push_back(zero);
2568 comps.push_back(zero);
2569 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2570 if (sampler.ms) {
2571 operands.push_back(spv::ImageOperandsSampleMask);
2572 operands.push_back(*(opIt++));
2573 }
2574 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2575 }
2576
John Kessenich56bab042015-09-16 10:54:31 -06002577 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002578 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002579 if (sampler.ms) {
2580 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002581 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002582 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002583 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2584 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002585 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002586 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002587 if (sampler.ms) {
2588 operands.push_back(*(opIt + 1));
2589 operands.push_back(spv::ImageOperandsSampleMask);
2590 operands.push_back(*opIt);
2591 } else
2592 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002593 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002594 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2595 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002596 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002597 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2598 builder.addCapability(spv::CapabilitySparseResidency);
2599 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2600 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2601
2602 if (sampler.ms) {
2603 operands.push_back(spv::ImageOperandsSampleMask);
2604 operands.push_back(*opIt++);
2605 }
2606
2607 // Create the return type that was a special structure
2608 spv::Id texelOut = *opIt;
2609 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2610 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2611 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2612
2613 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2614
2615 // Decode the return type
2616 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2617 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002618 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002619 // Process image atomic operations
2620
2621 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2622 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002623 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002624
Rex Xufc618912015-09-09 16:42:49 +08002625 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002626 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002627
2628 std::vector<spv::Id> operands;
2629 operands.push_back(pointer);
2630 for (; opIt != arguments.end(); ++opIt)
2631 operands.push_back(*opIt);
2632
Rex Xu04db3f52015-09-16 11:44:02 +08002633 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002634 }
2635 }
2636
2637 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002638 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002639 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2640
John Kessenichfc51d282015-08-19 13:34:18 -06002641 // check for bias argument
2642 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002643 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002644 int nonBiasArgCount = 2;
2645 if (cracked.offset)
2646 ++nonBiasArgCount;
2647 if (cracked.grad)
2648 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002649 if (cracked.lodClamp)
2650 ++nonBiasArgCount;
2651 if (sparse)
2652 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002653
2654 if ((int)arguments.size() > nonBiasArgCount)
2655 bias = true;
2656 }
2657
John Kessenicha5c33d62016-06-02 23:45:21 -06002658 // See if the sampler param should really be just the SPV image part
2659 if (cracked.fetch) {
2660 // a fetch needs to have the image extracted first
2661 if (builder.isSampledImage(params.sampler))
2662 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2663 }
2664
John Kessenichfc51d282015-08-19 13:34:18 -06002665 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002666
John Kessenichfc51d282015-08-19 13:34:18 -06002667 params.coords = arguments[1];
2668 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002669 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002670
2671 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002672 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002673 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002674 ++extraArgs;
2675 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002676 params.Dref = arguments[2];
2677 ++extraArgs;
2678 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002679 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002680 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002681 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002682 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002683 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002684 dRefComp = builder.getNumComponents(params.coords) - 1;
2685 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002686 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2687 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002688
2689 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002690 if (cracked.lod) {
2691 params.lod = arguments[2];
2692 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002693 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2694 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2695 noImplicitLod = true;
2696 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002697
2698 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002699 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002700 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002701 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002702 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002703
2704 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002705 if (cracked.grad) {
2706 params.gradX = arguments[2 + extraArgs];
2707 params.gradY = arguments[3 + extraArgs];
2708 extraArgs += 2;
2709 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002710
2711 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002712 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002713 params.offset = arguments[2 + extraArgs];
2714 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002715 } else if (cracked.offsets) {
2716 params.offsets = arguments[2 + extraArgs];
2717 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002718 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002719
2720 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002721 if (cracked.lodClamp) {
2722 params.lodClamp = arguments[2 + extraArgs];
2723 ++extraArgs;
2724 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002725
2726 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002727 if (sparse) {
2728 params.texelOut = arguments[2 + extraArgs];
2729 ++extraArgs;
2730 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002731
2732 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002733 if (bias) {
2734 params.bias = arguments[2 + extraArgs];
2735 ++extraArgs;
2736 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002737
2738 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002739 if (cracked.gather && ! sampler.shadow) {
2740 // default component is 0, if missing, otherwise an argument
2741 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002742 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002743 ++extraArgs;
2744 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002745 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002746 }
2747 }
John Kessenichfc51d282015-08-19 13:34:18 -06002748
John Kessenich65336482016-06-16 14:06:26 -06002749 // projective component (might not to move)
2750 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2751 // are divided by the last component of P."
2752 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2753 // unused components will appear after all used components."
2754 if (cracked.proj) {
2755 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2756 int projTargetComp;
2757 switch (sampler.dim) {
2758 case glslang::Esd1D: projTargetComp = 1; break;
2759 case glslang::Esd2D: projTargetComp = 2; break;
2760 case glslang::EsdRect: projTargetComp = 2; break;
2761 default: projTargetComp = projSourceComp; break;
2762 }
2763 // copy the projective coordinate if we have to
2764 if (projTargetComp != projSourceComp) {
2765 spv::Id projComp = builder.createCompositeExtract(params.coords,
2766 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2767 projSourceComp);
2768 params.coords = builder.createCompositeInsert(projComp, params.coords,
2769 builder.getTypeId(params.coords), projTargetComp);
2770 }
2771 }
2772
John Kessenich019f08f2016-02-15 15:40:42 -07002773 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002774}
2775
2776spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2777{
2778 // Grab the function's pointer from the previously created function
2779 spv::Function* function = functionMap[node->getName().c_str()];
2780 if (! function)
2781 return 0;
2782
2783 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2784 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2785
2786 // See comments in makeFunctions() for details about the semantics for parameter passing.
2787 //
2788 // These imply we need a four step process:
2789 // 1. Evaluate the arguments
2790 // 2. Allocate and make copies of in, out, and inout arguments
2791 // 3. Make the call
2792 // 4. Copy back the results
2793
2794 // 1. Evaluate the arguments
2795 std::vector<spv::Builder::AccessChain> lValues;
2796 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002797 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002798 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002799 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002800 // build l-value
2801 builder.clearAccessChain();
2802 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002803 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002804 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2805 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002806 // save l-value
2807 lValues.push_back(builder.getAccessChain());
2808 } else {
2809 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002810 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002811 }
2812 }
2813
2814 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2815 // copy the original into that space.
2816 //
2817 // Also, build up the list of actual arguments to pass in for the call
2818 int lValueCount = 0;
2819 int rValueCount = 0;
2820 std::vector<spv::Id> spvArgs;
2821 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002822 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002823 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002824 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002825 builder.setAccessChain(lValues[lValueCount]);
2826 arg = builder.accessChainGetLValue();
2827 ++lValueCount;
2828 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002829 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002830 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2831 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2832 // need to copy the input into output space
2833 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002834 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002835 builder.createStore(copy, arg);
2836 }
2837 ++lValueCount;
2838 } else {
2839 arg = rValues[rValueCount];
2840 ++rValueCount;
2841 }
2842 spvArgs.push_back(arg);
2843 }
2844
2845 // 3. Make the call.
2846 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002847 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002848
2849 // 4. Copy back out an "out" arguments.
2850 lValueCount = 0;
2851 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2852 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2853 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2854 spv::Id copy = builder.createLoad(spvArgs[a]);
2855 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002856 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002857 }
2858 ++lValueCount;
2859 }
2860 }
2861
2862 return result;
2863}
2864
2865// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002866spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2867 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002868 spv::Id typeId, spv::Id left, spv::Id right,
2869 glslang::TBasicType typeProxy, bool reduceComparison)
2870{
Rex Xu8ff43de2016-04-22 16:51:45 +08002871 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002872 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002873 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002874
2875 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002876 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002877 bool comparison = false;
2878
2879 switch (op) {
2880 case glslang::EOpAdd:
2881 case glslang::EOpAddAssign:
2882 if (isFloat)
2883 binOp = spv::OpFAdd;
2884 else
2885 binOp = spv::OpIAdd;
2886 break;
2887 case glslang::EOpSub:
2888 case glslang::EOpSubAssign:
2889 if (isFloat)
2890 binOp = spv::OpFSub;
2891 else
2892 binOp = spv::OpISub;
2893 break;
2894 case glslang::EOpMul:
2895 case glslang::EOpMulAssign:
2896 if (isFloat)
2897 binOp = spv::OpFMul;
2898 else
2899 binOp = spv::OpIMul;
2900 break;
2901 case glslang::EOpVectorTimesScalar:
2902 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002903 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002904 if (builder.isVector(right))
2905 std::swap(left, right);
2906 assert(builder.isScalar(right));
2907 needMatchingVectors = false;
2908 binOp = spv::OpVectorTimesScalar;
2909 } else
2910 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002911 break;
2912 case glslang::EOpVectorTimesMatrix:
2913 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002914 binOp = spv::OpVectorTimesMatrix;
2915 break;
2916 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002917 binOp = spv::OpMatrixTimesVector;
2918 break;
2919 case glslang::EOpMatrixTimesScalar:
2920 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002921 binOp = spv::OpMatrixTimesScalar;
2922 break;
2923 case glslang::EOpMatrixTimesMatrix:
2924 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002925 binOp = spv::OpMatrixTimesMatrix;
2926 break;
2927 case glslang::EOpOuterProduct:
2928 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002929 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002930 break;
2931
2932 case glslang::EOpDiv:
2933 case glslang::EOpDivAssign:
2934 if (isFloat)
2935 binOp = spv::OpFDiv;
2936 else if (isUnsigned)
2937 binOp = spv::OpUDiv;
2938 else
2939 binOp = spv::OpSDiv;
2940 break;
2941 case glslang::EOpMod:
2942 case glslang::EOpModAssign:
2943 if (isFloat)
2944 binOp = spv::OpFMod;
2945 else if (isUnsigned)
2946 binOp = spv::OpUMod;
2947 else
2948 binOp = spv::OpSMod;
2949 break;
2950 case glslang::EOpRightShift:
2951 case glslang::EOpRightShiftAssign:
2952 if (isUnsigned)
2953 binOp = spv::OpShiftRightLogical;
2954 else
2955 binOp = spv::OpShiftRightArithmetic;
2956 break;
2957 case glslang::EOpLeftShift:
2958 case glslang::EOpLeftShiftAssign:
2959 binOp = spv::OpShiftLeftLogical;
2960 break;
2961 case glslang::EOpAnd:
2962 case glslang::EOpAndAssign:
2963 binOp = spv::OpBitwiseAnd;
2964 break;
2965 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002966 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002967 binOp = spv::OpLogicalAnd;
2968 break;
2969 case glslang::EOpInclusiveOr:
2970 case glslang::EOpInclusiveOrAssign:
2971 binOp = spv::OpBitwiseOr;
2972 break;
2973 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002974 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002975 binOp = spv::OpLogicalOr;
2976 break;
2977 case glslang::EOpExclusiveOr:
2978 case glslang::EOpExclusiveOrAssign:
2979 binOp = spv::OpBitwiseXor;
2980 break;
2981 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002982 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002983 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002984 break;
2985
2986 case glslang::EOpLessThan:
2987 case glslang::EOpGreaterThan:
2988 case glslang::EOpLessThanEqual:
2989 case glslang::EOpGreaterThanEqual:
2990 case glslang::EOpEqual:
2991 case glslang::EOpNotEqual:
2992 case glslang::EOpVectorEqual:
2993 case glslang::EOpVectorNotEqual:
2994 comparison = true;
2995 break;
2996 default:
2997 break;
2998 }
2999
John Kessenich7c1aa102015-10-15 13:29:11 -06003000 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003001 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003002 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003003 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003004 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003005
3006 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003007 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003008 builder.promoteScalar(precision, left, right);
3009
qining25262b32016-05-06 17:25:16 -04003010 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3011 addDecoration(result, noContraction);
3012 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003013 }
3014
3015 if (! comparison)
3016 return 0;
3017
John Kessenich7c1aa102015-10-15 13:29:11 -06003018 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003019
3020 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
3021 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
3022
John Kessenich22118352015-12-21 20:54:09 -07003023 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003024 }
3025
3026 switch (op) {
3027 case glslang::EOpLessThan:
3028 if (isFloat)
3029 binOp = spv::OpFOrdLessThan;
3030 else if (isUnsigned)
3031 binOp = spv::OpULessThan;
3032 else
3033 binOp = spv::OpSLessThan;
3034 break;
3035 case glslang::EOpGreaterThan:
3036 if (isFloat)
3037 binOp = spv::OpFOrdGreaterThan;
3038 else if (isUnsigned)
3039 binOp = spv::OpUGreaterThan;
3040 else
3041 binOp = spv::OpSGreaterThan;
3042 break;
3043 case glslang::EOpLessThanEqual:
3044 if (isFloat)
3045 binOp = spv::OpFOrdLessThanEqual;
3046 else if (isUnsigned)
3047 binOp = spv::OpULessThanEqual;
3048 else
3049 binOp = spv::OpSLessThanEqual;
3050 break;
3051 case glslang::EOpGreaterThanEqual:
3052 if (isFloat)
3053 binOp = spv::OpFOrdGreaterThanEqual;
3054 else if (isUnsigned)
3055 binOp = spv::OpUGreaterThanEqual;
3056 else
3057 binOp = spv::OpSGreaterThanEqual;
3058 break;
3059 case glslang::EOpEqual:
3060 case glslang::EOpVectorEqual:
3061 if (isFloat)
3062 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003063 else if (isBool)
3064 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003065 else
3066 binOp = spv::OpIEqual;
3067 break;
3068 case glslang::EOpNotEqual:
3069 case glslang::EOpVectorNotEqual:
3070 if (isFloat)
3071 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003072 else if (isBool)
3073 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003074 else
3075 binOp = spv::OpINotEqual;
3076 break;
3077 default:
3078 break;
3079 }
3080
qining25262b32016-05-06 17:25:16 -04003081 if (binOp != spv::OpNop) {
3082 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3083 addDecoration(result, noContraction);
3084 return builder.setPrecision(result, precision);
3085 }
John Kessenich140f3df2015-06-26 16:58:36 -06003086
3087 return 0;
3088}
3089
John Kessenich04bb8a02015-12-12 12:28:14 -07003090//
3091// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3092// These can be any of:
3093//
3094// matrix * scalar
3095// scalar * matrix
3096// matrix * matrix linear algebraic
3097// matrix * vector
3098// vector * matrix
3099// matrix * matrix componentwise
3100// matrix op matrix op in {+, -, /}
3101// matrix op scalar op in {+, -, /}
3102// scalar op matrix op in {+, -, /}
3103//
qining25262b32016-05-06 17:25:16 -04003104spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003105{
3106 bool firstClass = true;
3107
3108 // First, handle first-class matrix operations (* and matrix/scalar)
3109 switch (op) {
3110 case spv::OpFDiv:
3111 if (builder.isMatrix(left) && builder.isScalar(right)) {
3112 // turn matrix / scalar into a multiply...
3113 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3114 op = spv::OpMatrixTimesScalar;
3115 } else
3116 firstClass = false;
3117 break;
3118 case spv::OpMatrixTimesScalar:
3119 if (builder.isMatrix(right))
3120 std::swap(left, right);
3121 assert(builder.isScalar(right));
3122 break;
3123 case spv::OpVectorTimesMatrix:
3124 assert(builder.isVector(left));
3125 assert(builder.isMatrix(right));
3126 break;
3127 case spv::OpMatrixTimesVector:
3128 assert(builder.isMatrix(left));
3129 assert(builder.isVector(right));
3130 break;
3131 case spv::OpMatrixTimesMatrix:
3132 assert(builder.isMatrix(left));
3133 assert(builder.isMatrix(right));
3134 break;
3135 default:
3136 firstClass = false;
3137 break;
3138 }
3139
qining25262b32016-05-06 17:25:16 -04003140 if (firstClass) {
3141 spv::Id result = builder.createBinOp(op, typeId, left, right);
3142 addDecoration(result, noContraction);
3143 return builder.setPrecision(result, precision);
3144 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003145
LoopDawg592860c2016-06-09 08:57:35 -06003146 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003147 // The result type of all of them is the same type as the (a) matrix operand.
3148 // The algorithm is to:
3149 // - break the matrix(es) into vectors
3150 // - smear any scalar to a vector
3151 // - do vector operations
3152 // - make a matrix out the vector results
3153 switch (op) {
3154 case spv::OpFAdd:
3155 case spv::OpFSub:
3156 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003157 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003158 case spv::OpFMul:
3159 {
3160 // one time set up...
3161 bool leftMat = builder.isMatrix(left);
3162 bool rightMat = builder.isMatrix(right);
3163 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3164 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3165 spv::Id scalarType = builder.getScalarTypeId(typeId);
3166 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3167 std::vector<spv::Id> results;
3168 spv::Id smearVec = spv::NoResult;
3169 if (builder.isScalar(left))
3170 smearVec = builder.smearScalar(precision, left, vecType);
3171 else if (builder.isScalar(right))
3172 smearVec = builder.smearScalar(precision, right, vecType);
3173
3174 // do each vector op
3175 for (unsigned int c = 0; c < numCols; ++c) {
3176 std::vector<unsigned int> indexes;
3177 indexes.push_back(c);
3178 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3179 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003180 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3181 addDecoration(result, noContraction);
3182 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003183 }
3184
3185 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003186 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003187 }
3188 default:
3189 assert(0);
3190 return spv::NoResult;
3191 }
3192}
3193
qining25262b32016-05-06 17:25:16 -04003194spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003195{
3196 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003197 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003198 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003199 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003200 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003201
3202 switch (op) {
3203 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003204 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003205 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003206 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003207 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003208 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003209 unaryOp = spv::OpSNegate;
3210 break;
3211
3212 case glslang::EOpLogicalNot:
3213 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003214 unaryOp = spv::OpLogicalNot;
3215 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003216 case glslang::EOpBitwiseNot:
3217 unaryOp = spv::OpNot;
3218 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003219
John Kessenich140f3df2015-06-26 16:58:36 -06003220 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003221 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 break;
3223 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003224 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003225 break;
3226 case glslang::EOpTranspose:
3227 unaryOp = spv::OpTranspose;
3228 break;
3229
3230 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003231 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 break;
3233 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003234 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003235 break;
3236 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003237 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003238 break;
3239 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003240 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003241 break;
3242 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003243 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003244 break;
3245 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003246 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003247 break;
3248 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003249 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003250 break;
3251 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003252 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003253 break;
3254
3255 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003256 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003257 break;
3258 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003259 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003260 break;
3261 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003262 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003263 break;
3264 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003265 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003266 break;
3267 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003268 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003269 break;
3270 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003271 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003272 break;
3273
3274 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003275 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003276 break;
3277 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003278 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003279 break;
3280
3281 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003282 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003283 break;
3284 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003285 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003286 break;
3287 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003288 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003289 break;
3290 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003291 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003292 break;
3293 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003294 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003295 break;
3296 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003297 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003298 break;
3299
3300 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003301 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003302 break;
3303 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003304 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003305 break;
3306 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003307 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003308 break;
3309 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003310 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003311 break;
3312 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
3318
3319 case glslang::EOpIsNan:
3320 unaryOp = spv::OpIsNan;
3321 break;
3322 case glslang::EOpIsInf:
3323 unaryOp = spv::OpIsInf;
3324 break;
LoopDawg592860c2016-06-09 08:57:35 -06003325 case glslang::EOpIsFinite:
3326 unaryOp = spv::OpIsFinite;
3327 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003328
Rex Xucbc426e2015-12-15 16:03:10 +08003329 case glslang::EOpFloatBitsToInt:
3330 case glslang::EOpFloatBitsToUint:
3331 case glslang::EOpIntBitsToFloat:
3332 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003333 case glslang::EOpDoubleBitsToInt64:
3334 case glslang::EOpDoubleBitsToUint64:
3335 case glslang::EOpInt64BitsToDouble:
3336 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003337 unaryOp = spv::OpBitcast;
3338 break;
3339
John Kessenich140f3df2015-06-26 16:58:36 -06003340 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003341 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003342 break;
3343 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003344 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003345 break;
3346 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003347 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003348 break;
3349 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003350 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003351 break;
3352 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003353 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003354 break;
3355 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003356 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003357 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003358 case glslang::EOpPackSnorm4x8:
3359 libCall = spv::GLSLstd450PackSnorm4x8;
3360 break;
3361 case glslang::EOpUnpackSnorm4x8:
3362 libCall = spv::GLSLstd450UnpackSnorm4x8;
3363 break;
3364 case glslang::EOpPackUnorm4x8:
3365 libCall = spv::GLSLstd450PackUnorm4x8;
3366 break;
3367 case glslang::EOpUnpackUnorm4x8:
3368 libCall = spv::GLSLstd450UnpackUnorm4x8;
3369 break;
3370 case glslang::EOpPackDouble2x32:
3371 libCall = spv::GLSLstd450PackDouble2x32;
3372 break;
3373 case glslang::EOpUnpackDouble2x32:
3374 libCall = spv::GLSLstd450UnpackDouble2x32;
3375 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003376
Rex Xu8ff43de2016-04-22 16:51:45 +08003377 case glslang::EOpPackInt2x32:
3378 case glslang::EOpUnpackInt2x32:
3379 case glslang::EOpPackUint2x32:
3380 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003381 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003382 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3383 break;
3384
John Kessenich140f3df2015-06-26 16:58:36 -06003385 case glslang::EOpDPdx:
3386 unaryOp = spv::OpDPdx;
3387 break;
3388 case glslang::EOpDPdy:
3389 unaryOp = spv::OpDPdy;
3390 break;
3391 case glslang::EOpFwidth:
3392 unaryOp = spv::OpFwidth;
3393 break;
3394 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003395 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003396 unaryOp = spv::OpDPdxFine;
3397 break;
3398 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003399 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003400 unaryOp = spv::OpDPdyFine;
3401 break;
3402 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003403 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003404 unaryOp = spv::OpFwidthFine;
3405 break;
3406 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003407 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003408 unaryOp = spv::OpDPdxCoarse;
3409 break;
3410 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003411 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003412 unaryOp = spv::OpDPdyCoarse;
3413 break;
3414 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003415 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003416 unaryOp = spv::OpFwidthCoarse;
3417 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003418 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003419 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003420 libCall = spv::GLSLstd450InterpolateAtCentroid;
3421 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003422 case glslang::EOpAny:
3423 unaryOp = spv::OpAny;
3424 break;
3425 case glslang::EOpAll:
3426 unaryOp = spv::OpAll;
3427 break;
3428
3429 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003430 if (isFloat)
3431 libCall = spv::GLSLstd450FAbs;
3432 else
3433 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003434 break;
3435 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003436 if (isFloat)
3437 libCall = spv::GLSLstd450FSign;
3438 else
3439 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003440 break;
3441
John Kessenichfc51d282015-08-19 13:34:18 -06003442 case glslang::EOpAtomicCounterIncrement:
3443 case glslang::EOpAtomicCounterDecrement:
3444 case glslang::EOpAtomicCounter:
3445 {
3446 // Handle all of the atomics in one place, in createAtomicOperation()
3447 std::vector<spv::Id> operands;
3448 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003449 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003450 }
3451
John Kessenichfc51d282015-08-19 13:34:18 -06003452 case glslang::EOpBitFieldReverse:
3453 unaryOp = spv::OpBitReverse;
3454 break;
3455 case glslang::EOpBitCount:
3456 unaryOp = spv::OpBitCount;
3457 break;
3458 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003459 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003460 break;
3461 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003462 if (isUnsigned)
3463 libCall = spv::GLSLstd450FindUMsb;
3464 else
3465 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003466 break;
3467
Rex Xu574ab042016-04-14 16:53:07 +08003468 case glslang::EOpBallot:
3469 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003470 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003471 libCall = spv::GLSLstd450Bad;
3472 break;
3473
Rex Xu338b1852016-05-05 20:38:33 +08003474 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003475 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003476 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003477#ifdef AMD_EXTENSIONS
3478 case glslang::EOpMinInvocations:
3479 case glslang::EOpMaxInvocations:
3480 case glslang::EOpAddInvocations:
3481 case glslang::EOpMinInvocationsNonUniform:
3482 case glslang::EOpMaxInvocationsNonUniform:
3483 case glslang::EOpAddInvocationsNonUniform:
3484#endif
3485 return createInvocationsOperation(op, typeId, operand, typeProxy);
3486
3487#ifdef AMD_EXTENSIONS
3488 case glslang::EOpMbcnt:
3489 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3490 libCall = spv::MbcntAMD;
3491 break;
3492
3493 case glslang::EOpCubeFaceIndex:
3494 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3495 libCall = spv::CubeFaceIndexAMD;
3496 break;
3497
3498 case glslang::EOpCubeFaceCoord:
3499 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3500 libCall = spv::CubeFaceCoordAMD;
3501 break;
3502#endif
Rex Xu338b1852016-05-05 20:38:33 +08003503
John Kessenich140f3df2015-06-26 16:58:36 -06003504 default:
3505 return 0;
3506 }
3507
3508 spv::Id id;
3509 if (libCall >= 0) {
3510 std::vector<spv::Id> args;
3511 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003512 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003513 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003514 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003515 }
John Kessenich140f3df2015-06-26 16:58:36 -06003516
qining25262b32016-05-06 17:25:16 -04003517 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003518 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003519}
3520
John Kessenich7a53f762016-01-20 11:19:27 -07003521// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003522spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07003523{
3524 // Handle unary operations vector by vector.
3525 // The result type is the same type as the original type.
3526 // The algorithm is to:
3527 // - break the matrix into vectors
3528 // - apply the operation to each vector
3529 // - make a matrix out the vector results
3530
3531 // get the types sorted out
3532 int numCols = builder.getNumColumns(operand);
3533 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003534 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3535 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003536 std::vector<spv::Id> results;
3537
3538 // do each vector op
3539 for (int c = 0; c < numCols; ++c) {
3540 std::vector<unsigned int> indexes;
3541 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003542 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3543 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3544 addDecoration(destVec, noContraction);
3545 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003546 }
3547
3548 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003549 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003550}
3551
Rex Xu73e3ce72016-04-27 18:48:17 +08003552spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003553{
3554 spv::Op convOp = spv::OpNop;
3555 spv::Id zero = 0;
3556 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003557 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003558
3559 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3560
3561 switch (op) {
3562 case glslang::EOpConvIntToBool:
3563 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003564 case glslang::EOpConvInt64ToBool:
3565 case glslang::EOpConvUint64ToBool:
3566 zero = (op == glslang::EOpConvInt64ToBool ||
3567 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003568 zero = makeSmearedConstant(zero, vectorSize);
3569 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3570
3571 case glslang::EOpConvFloatToBool:
3572 zero = builder.makeFloatConstant(0.0F);
3573 zero = makeSmearedConstant(zero, vectorSize);
3574 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3575
3576 case glslang::EOpConvDoubleToBool:
3577 zero = builder.makeDoubleConstant(0.0);
3578 zero = makeSmearedConstant(zero, vectorSize);
3579 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3580
3581 case glslang::EOpConvBoolToFloat:
3582 convOp = spv::OpSelect;
3583 zero = builder.makeFloatConstant(0.0);
3584 one = builder.makeFloatConstant(1.0);
3585 break;
3586 case glslang::EOpConvBoolToDouble:
3587 convOp = spv::OpSelect;
3588 zero = builder.makeDoubleConstant(0.0);
3589 one = builder.makeDoubleConstant(1.0);
3590 break;
3591 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003592 case glslang::EOpConvBoolToInt64:
3593 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3594 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003595 convOp = spv::OpSelect;
3596 break;
3597 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003598 case glslang::EOpConvBoolToUint64:
3599 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3600 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003601 convOp = spv::OpSelect;
3602 break;
3603
3604 case glslang::EOpConvIntToFloat:
3605 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003606 case glslang::EOpConvInt64ToFloat:
3607 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003608 convOp = spv::OpConvertSToF;
3609 break;
3610
3611 case glslang::EOpConvUintToFloat:
3612 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003613 case glslang::EOpConvUint64ToFloat:
3614 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003615 convOp = spv::OpConvertUToF;
3616 break;
3617
3618 case glslang::EOpConvDoubleToFloat:
3619 case glslang::EOpConvFloatToDouble:
3620 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003621 if (builder.isMatrixType(destType))
3622 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003623 break;
3624
3625 case glslang::EOpConvFloatToInt:
3626 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003627 case glslang::EOpConvFloatToInt64:
3628 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003629 convOp = spv::OpConvertFToS;
3630 break;
3631
3632 case glslang::EOpConvUintToInt:
3633 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003634 case glslang::EOpConvUint64ToInt64:
3635 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003636 if (builder.isInSpecConstCodeGenMode()) {
3637 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003638 zero = (op == glslang::EOpConvUintToInt64 ||
3639 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003640 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003641 // Use OpIAdd, instead of OpBitcast to do the conversion when
3642 // generating for OpSpecConstantOp instruction.
3643 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3644 }
3645 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003646 convOp = spv::OpBitcast;
3647 break;
3648
3649 case glslang::EOpConvFloatToUint:
3650 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003651 case glslang::EOpConvFloatToUint64:
3652 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003653 convOp = spv::OpConvertFToU;
3654 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003655
3656 case glslang::EOpConvIntToInt64:
3657 case glslang::EOpConvInt64ToInt:
3658 convOp = spv::OpSConvert;
3659 break;
3660
3661 case glslang::EOpConvUintToUint64:
3662 case glslang::EOpConvUint64ToUint:
3663 convOp = spv::OpUConvert;
3664 break;
3665
3666 case glslang::EOpConvIntToUint64:
3667 case glslang::EOpConvInt64ToUint:
3668 case glslang::EOpConvUint64ToInt:
3669 case glslang::EOpConvUintToInt64:
3670 // OpSConvert/OpUConvert + OpBitCast
3671 switch (op) {
3672 case glslang::EOpConvIntToUint64:
3673 convOp = spv::OpSConvert;
3674 type = builder.makeIntType(64);
3675 break;
3676 case glslang::EOpConvInt64ToUint:
3677 convOp = spv::OpSConvert;
3678 type = builder.makeIntType(32);
3679 break;
3680 case glslang::EOpConvUint64ToInt:
3681 convOp = spv::OpUConvert;
3682 type = builder.makeUintType(32);
3683 break;
3684 case glslang::EOpConvUintToInt64:
3685 convOp = spv::OpUConvert;
3686 type = builder.makeUintType(64);
3687 break;
3688 default:
3689 assert(0);
3690 break;
3691 }
3692
3693 if (vectorSize > 0)
3694 type = builder.makeVectorType(type, vectorSize);
3695
3696 operand = builder.createUnaryOp(convOp, type, operand);
3697
3698 if (builder.isInSpecConstCodeGenMode()) {
3699 // Build zero scalar or vector for OpIAdd.
3700 zero = (op == glslang::EOpConvIntToUint64 ||
3701 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3702 zero = makeSmearedConstant(zero, vectorSize);
3703 // Use OpIAdd, instead of OpBitcast to do the conversion when
3704 // generating for OpSpecConstantOp instruction.
3705 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3706 }
3707 // For normal run-time conversion instruction, use OpBitcast.
3708 convOp = spv::OpBitcast;
3709 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 default:
3711 break;
3712 }
3713
3714 spv::Id result = 0;
3715 if (convOp == spv::OpNop)
3716 return result;
3717
3718 if (convOp == spv::OpSelect) {
3719 zero = makeSmearedConstant(zero, vectorSize);
3720 one = makeSmearedConstant(one, vectorSize);
3721 result = builder.createTriOp(convOp, destType, operand, one, zero);
3722 } else
3723 result = builder.createUnaryOp(convOp, destType, operand);
3724
John Kessenich32cfd492016-02-02 12:37:46 -07003725 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003726}
3727
3728spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3729{
3730 if (vectorSize == 0)
3731 return constant;
3732
3733 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3734 std::vector<spv::Id> components;
3735 for (int c = 0; c < vectorSize; ++c)
3736 components.push_back(constant);
3737 return builder.makeCompositeConstant(vectorTypeId, components);
3738}
3739
John Kessenich426394d2015-07-23 10:22:48 -06003740// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003741spv::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 -06003742{
3743 spv::Op opCode = spv::OpNop;
3744
3745 switch (op) {
3746 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003747 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003748 opCode = spv::OpAtomicIAdd;
3749 break;
3750 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003751 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003752 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003753 break;
3754 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003755 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003756 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003757 break;
3758 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003759 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003760 opCode = spv::OpAtomicAnd;
3761 break;
3762 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003763 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003764 opCode = spv::OpAtomicOr;
3765 break;
3766 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003767 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003768 opCode = spv::OpAtomicXor;
3769 break;
3770 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003771 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003772 opCode = spv::OpAtomicExchange;
3773 break;
3774 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003775 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003776 opCode = spv::OpAtomicCompareExchange;
3777 break;
3778 case glslang::EOpAtomicCounterIncrement:
3779 opCode = spv::OpAtomicIIncrement;
3780 break;
3781 case glslang::EOpAtomicCounterDecrement:
3782 opCode = spv::OpAtomicIDecrement;
3783 break;
3784 case glslang::EOpAtomicCounter:
3785 opCode = spv::OpAtomicLoad;
3786 break;
3787 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003788 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003789 break;
3790 }
3791
3792 // Sort out the operands
3793 // - mapping from glslang -> SPV
3794 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003795 // - compare-exchange swaps the value and comparator
3796 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003797 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3798 auto opIt = operands.begin(); // walk the glslang operands
3799 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003800 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3801 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3802 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003803 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3804 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003805 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003806 spvAtomicOperands.push_back(*(opIt + 1));
3807 spvAtomicOperands.push_back(*opIt);
3808 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003809 }
John Kessenich426394d2015-07-23 10:22:48 -06003810
John Kessenich3e60a6f2015-09-14 22:45:16 -06003811 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003812 for (; opIt != operands.end(); ++opIt)
3813 spvAtomicOperands.push_back(*opIt);
3814
3815 return builder.createOp(opCode, typeId, spvAtomicOperands);
3816}
3817
John Kessenich91cef522016-05-05 16:45:40 -06003818// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003819spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003820{
Rex Xu9d93a232016-05-05 12:30:44 +08003821 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3822 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3823
John Kessenich91cef522016-05-05 16:45:40 -06003824 builder.addCapability(spv::CapabilityGroups);
3825
3826 std::vector<spv::Id> operands;
3827 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003828#ifdef AMD_EXTENSIONS
3829 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3830 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3831 operands.push_back(spv::GroupOperationReduce);
3832#endif
John Kessenich91cef522016-05-05 16:45:40 -06003833 operands.push_back(operand);
3834
3835 switch (op) {
3836 case glslang::EOpAnyInvocation:
3837 case glslang::EOpAllInvocations:
3838 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3839
3840 case glslang::EOpAllInvocationsEqual:
3841 {
3842 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3843 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3844
3845 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3846 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3847 }
Rex Xu9d93a232016-05-05 12:30:44 +08003848#ifdef AMD_EXTENSIONS
3849 case glslang::EOpMinInvocations:
3850 case glslang::EOpMaxInvocations:
3851 case glslang::EOpAddInvocations:
3852 {
3853 spv::Op spvOp = spv::OpNop;
3854 if (op == glslang::EOpMinInvocations) {
3855 if (isFloat)
3856 spvOp = spv::OpGroupFMin;
3857 else {
3858 if (isUnsigned)
3859 spvOp = spv::OpGroupUMin;
3860 else
3861 spvOp = spv::OpGroupSMin;
3862 }
3863 } else if (op == glslang::EOpMaxInvocations) {
3864 if (isFloat)
3865 spvOp = spv::OpGroupFMax;
3866 else {
3867 if (isUnsigned)
3868 spvOp = spv::OpGroupUMax;
3869 else
3870 spvOp = spv::OpGroupSMax;
3871 }
3872 } else {
3873 if (isFloat)
3874 spvOp = spv::OpGroupFAdd;
3875 else
3876 spvOp = spv::OpGroupIAdd;
3877 }
3878
3879 return builder.createOp(spvOp, typeId, operands);
3880 }
3881 case glslang::EOpMinInvocationsNonUniform:
3882 case glslang::EOpMaxInvocationsNonUniform:
3883 case glslang::EOpAddInvocationsNonUniform:
3884 {
3885 spv::Op spvOp = spv::OpNop;
3886 if (op == glslang::EOpMinInvocationsNonUniform) {
3887 if (isFloat)
3888 spvOp = spv::OpGroupFMinNonUniformAMD;
3889 else {
3890 if (isUnsigned)
3891 spvOp = spv::OpGroupUMinNonUniformAMD;
3892 else
3893 spvOp = spv::OpGroupSMinNonUniformAMD;
3894 }
3895 }
3896 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3897 if (isFloat)
3898 spvOp = spv::OpGroupFMaxNonUniformAMD;
3899 else {
3900 if (isUnsigned)
3901 spvOp = spv::OpGroupUMaxNonUniformAMD;
3902 else
3903 spvOp = spv::OpGroupSMaxNonUniformAMD;
3904 }
3905 }
3906 else {
3907 if (isFloat)
3908 spvOp = spv::OpGroupFAddNonUniformAMD;
3909 else
3910 spvOp = spv::OpGroupIAddNonUniformAMD;
3911 }
3912
3913 return builder.createOp(spvOp, typeId, operands);
3914 }
3915#endif
John Kessenich91cef522016-05-05 16:45:40 -06003916 default:
3917 logger->missingFunctionality("invocation operation");
3918 return spv::NoResult;
3919 }
3920}
3921
John Kessenich5e4b1242015-08-06 22:53:06 -06003922spv::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 -06003923{
Rex Xu8ff43de2016-04-22 16:51:45 +08003924 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003925 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3926
John Kessenich140f3df2015-06-26 16:58:36 -06003927 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003928 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003929 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003930 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003931 spv::Id typeId0 = 0;
3932 if (consumedOperands > 0)
3933 typeId0 = builder.getTypeId(operands[0]);
3934 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003935
3936 switch (op) {
3937 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003938 if (isFloat)
3939 libCall = spv::GLSLstd450FMin;
3940 else if (isUnsigned)
3941 libCall = spv::GLSLstd450UMin;
3942 else
3943 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003944 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003945 break;
3946 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003947 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003948 break;
3949 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003950 if (isFloat)
3951 libCall = spv::GLSLstd450FMax;
3952 else if (isUnsigned)
3953 libCall = spv::GLSLstd450UMax;
3954 else
3955 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003956 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003957 break;
3958 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003959 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003960 break;
3961 case glslang::EOpDot:
3962 opCode = spv::OpDot;
3963 break;
3964 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003965 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003966 break;
3967
3968 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003969 if (isFloat)
3970 libCall = spv::GLSLstd450FClamp;
3971 else if (isUnsigned)
3972 libCall = spv::GLSLstd450UClamp;
3973 else
3974 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003975 builder.promoteScalar(precision, operands.front(), operands[1]);
3976 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003977 break;
3978 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003979 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3980 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003981 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003982 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003983 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003984 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003985 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003986 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003987 break;
3988 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003989 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003990 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003991 break;
3992 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003993 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003994 builder.promoteScalar(precision, operands[0], operands[2]);
3995 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003996 break;
3997
3998 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003999 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004000 break;
4001 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004002 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004003 break;
4004 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004005 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004006 break;
4007 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004009 break;
4010 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004013 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004014 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004015 libCall = spv::GLSLstd450InterpolateAtSample;
4016 break;
4017 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004018 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004019 libCall = spv::GLSLstd450InterpolateAtOffset;
4020 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004021 case glslang::EOpAddCarry:
4022 opCode = spv::OpIAddCarry;
4023 typeId = builder.makeStructResultType(typeId0, typeId0);
4024 consumedOperands = 2;
4025 break;
4026 case glslang::EOpSubBorrow:
4027 opCode = spv::OpISubBorrow;
4028 typeId = builder.makeStructResultType(typeId0, typeId0);
4029 consumedOperands = 2;
4030 break;
4031 case glslang::EOpUMulExtended:
4032 opCode = spv::OpUMulExtended;
4033 typeId = builder.makeStructResultType(typeId0, typeId0);
4034 consumedOperands = 2;
4035 break;
4036 case glslang::EOpIMulExtended:
4037 opCode = spv::OpSMulExtended;
4038 typeId = builder.makeStructResultType(typeId0, typeId0);
4039 consumedOperands = 2;
4040 break;
4041 case glslang::EOpBitfieldExtract:
4042 if (isUnsigned)
4043 opCode = spv::OpBitFieldUExtract;
4044 else
4045 opCode = spv::OpBitFieldSExtract;
4046 break;
4047 case glslang::EOpBitfieldInsert:
4048 opCode = spv::OpBitFieldInsert;
4049 break;
4050
4051 case glslang::EOpFma:
4052 libCall = spv::GLSLstd450Fma;
4053 break;
4054 case glslang::EOpFrexp:
4055 libCall = spv::GLSLstd450FrexpStruct;
4056 if (builder.getNumComponents(operands[0]) == 1)
4057 frexpIntType = builder.makeIntegerType(32, true);
4058 else
4059 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4060 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4061 consumedOperands = 1;
4062 break;
4063 case glslang::EOpLdexp:
4064 libCall = spv::GLSLstd450Ldexp;
4065 break;
4066
Rex Xu574ab042016-04-14 16:53:07 +08004067 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004068 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004069 libCall = spv::GLSLstd450Bad;
4070 break;
4071
Rex Xu9d93a232016-05-05 12:30:44 +08004072#ifdef AMD_EXTENSIONS
4073 case glslang::EOpSwizzleInvocations:
4074 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4075 libCall = spv::SwizzleInvocationsAMD;
4076 break;
4077 case glslang::EOpSwizzleInvocationsMasked:
4078 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4079 libCall = spv::SwizzleInvocationsMaskedAMD;
4080 break;
4081 case glslang::EOpWriteInvocation:
4082 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4083 libCall = spv::WriteInvocationAMD;
4084 break;
4085
4086 case glslang::EOpMin3:
4087 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4088 if (isFloat)
4089 libCall = spv::FMin3AMD;
4090 else {
4091 if (isUnsigned)
4092 libCall = spv::UMin3AMD;
4093 else
4094 libCall = spv::SMin3AMD;
4095 }
4096 break;
4097 case glslang::EOpMax3:
4098 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4099 if (isFloat)
4100 libCall = spv::FMax3AMD;
4101 else {
4102 if (isUnsigned)
4103 libCall = spv::UMax3AMD;
4104 else
4105 libCall = spv::SMax3AMD;
4106 }
4107 break;
4108 case glslang::EOpMid3:
4109 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4110 if (isFloat)
4111 libCall = spv::FMid3AMD;
4112 else {
4113 if (isUnsigned)
4114 libCall = spv::UMid3AMD;
4115 else
4116 libCall = spv::SMid3AMD;
4117 }
4118 break;
4119
4120 case glslang::EOpInterpolateAtVertex:
4121 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4122 libCall = spv::InterpolateAtVertexAMD;
4123 break;
4124#endif
4125
John Kessenich140f3df2015-06-26 16:58:36 -06004126 default:
4127 return 0;
4128 }
4129
4130 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004131 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004132 // Use an extended instruction from the standard library.
4133 // Construct the call arguments, without modifying the original operands vector.
4134 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4135 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004136 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004137 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004138 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004139 case 0:
4140 // should all be handled by visitAggregate and createNoArgOperation
4141 assert(0);
4142 return 0;
4143 case 1:
4144 // should all be handled by createUnaryOperation
4145 assert(0);
4146 return 0;
4147 case 2:
4148 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4149 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004150 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004151 // anything 3 or over doesn't have l-value operands, so all should be consumed
4152 assert(consumedOperands == operands.size());
4153 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004154 break;
4155 }
4156 }
4157
John Kessenich55e7d112015-11-15 21:33:39 -07004158 // Decode the return types that were structures
4159 switch (op) {
4160 case glslang::EOpAddCarry:
4161 case glslang::EOpSubBorrow:
4162 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4163 id = builder.createCompositeExtract(id, typeId0, 0);
4164 break;
4165 case glslang::EOpUMulExtended:
4166 case glslang::EOpIMulExtended:
4167 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4168 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4169 break;
4170 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004171 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004172 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4173 id = builder.createCompositeExtract(id, typeId0, 0);
4174 break;
4175 default:
4176 break;
4177 }
4178
John Kessenich32cfd492016-02-02 12:37:46 -07004179 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004180}
4181
Rex Xu9d93a232016-05-05 12:30:44 +08004182// Intrinsics with no arguments (or no return value, and no precision).
4183spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004184{
4185 // TODO: get the barrier operands correct
4186
4187 switch (op) {
4188 case glslang::EOpEmitVertex:
4189 builder.createNoResultOp(spv::OpEmitVertex);
4190 return 0;
4191 case glslang::EOpEndPrimitive:
4192 builder.createNoResultOp(spv::OpEndPrimitive);
4193 return 0;
4194 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004195 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004196 return 0;
4197 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004198 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004199 return 0;
4200 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004201 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004202 return 0;
4203 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004204 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004205 return 0;
4206 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004207 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004208 return 0;
4209 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004210 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004211 return 0;
4212 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004213 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004214 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004215 case glslang::EOpAllMemoryBarrierWithGroupSync:
4216 // Control barrier with non-"None" semantic is also a memory barrier.
4217 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4218 return 0;
4219 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4220 // Control barrier with non-"None" semantic is also a memory barrier.
4221 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4222 return 0;
4223 case glslang::EOpWorkgroupMemoryBarrier:
4224 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4225 return 0;
4226 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4227 // Control barrier with non-"None" semantic is also a memory barrier.
4228 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4229 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004230#ifdef AMD_EXTENSIONS
4231 case glslang::EOpTime:
4232 {
4233 std::vector<spv::Id> args; // Dummy arguments
4234 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4235 return builder.setPrecision(id, precision);
4236 }
4237#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004238 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004239 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004240 return 0;
4241 }
4242}
4243
4244spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4245{
John Kessenich2f273362015-07-18 22:34:27 -06004246 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004247 spv::Id id;
4248 if (symbolValues.end() != iter) {
4249 id = iter->second;
4250 return id;
4251 }
4252
4253 // it was not found, create it
4254 id = createSpvVariable(symbol);
4255 symbolValues[symbol->getId()] = id;
4256
Rex Xuc884b4a2016-06-29 15:03:44 +08004257 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004258 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004259 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004260 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004261 if (symbol->getType().getQualifier().hasSpecConstantId())
4262 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004263 if (symbol->getQualifier().hasIndex())
4264 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4265 if (symbol->getQualifier().hasComponent())
4266 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4267 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004268 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004269 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004270 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004271 if (symbol->getQualifier().hasXfbBuffer())
4272 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4273 if (symbol->getQualifier().hasXfbOffset())
4274 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4275 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004276 // atomic counters use this:
4277 if (symbol->getQualifier().hasOffset())
4278 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004279 }
4280
scygan2c864272016-05-18 18:09:17 +02004281 if (symbol->getQualifier().hasLocation())
4282 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004283 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004284 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004285 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004286 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004287 }
John Kessenich140f3df2015-06-26 16:58:36 -06004288 if (symbol->getQualifier().hasSet())
4289 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004290 else if (IsDescriptorResource(symbol->getType())) {
4291 // default to 0
4292 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4293 }
John Kessenich140f3df2015-06-26 16:58:36 -06004294 if (symbol->getQualifier().hasBinding())
4295 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004296 if (symbol->getQualifier().hasAttachment())
4297 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004298 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004299 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004300 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004301 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004302 if (symbol->getQualifier().hasXfbBuffer())
4303 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4304 }
4305
Rex Xu1da878f2016-02-21 20:59:01 +08004306 if (symbol->getType().isImage()) {
4307 std::vector<spv::Decoration> memory;
4308 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4309 for (unsigned int i = 0; i < memory.size(); ++i)
4310 addDecoration(id, memory[i]);
4311 }
4312
John Kessenich140f3df2015-06-26 16:58:36 -06004313 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004314 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004315 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004316 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004317
John Kessenich140f3df2015-06-26 16:58:36 -06004318 return id;
4319}
4320
John Kessenich55e7d112015-11-15 21:33:39 -07004321// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004322void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4323{
John Kessenich4016e382016-07-15 11:53:56 -06004324 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004325 builder.addDecoration(id, dec);
4326}
4327
John Kessenich55e7d112015-11-15 21:33:39 -07004328// If 'dec' is valid, add a one-operand decoration to an object
4329void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4330{
John Kessenich4016e382016-07-15 11:53:56 -06004331 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004332 builder.addDecoration(id, dec, value);
4333}
4334
4335// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004336void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4337{
John Kessenich4016e382016-07-15 11:53:56 -06004338 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004339 builder.addMemberDecoration(id, (unsigned)member, dec);
4340}
4341
John Kessenich92187592016-02-01 13:45:25 -07004342// If 'dec' is valid, add a one-operand decoration to a struct member
4343void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4344{
John Kessenich4016e382016-07-15 11:53:56 -06004345 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004346 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4347}
4348
John Kessenich55e7d112015-11-15 21:33:39 -07004349// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004350// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004351//
4352// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4353//
4354// Recursively walk the nodes. The nodes form a tree whose leaves are
4355// regular constants, which themselves are trees that createSpvConstant()
4356// recursively walks. So, this function walks the "top" of the tree:
4357// - emit specialization constant-building instructions for specConstant
4358// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004359spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004360{
John Kessenich7cc0e282016-03-20 00:46:02 -06004361 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004362
qining4f4bb812016-04-03 23:55:17 -04004363 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004364 if (! node.getQualifier().specConstant) {
4365 // hand off to the non-spec-constant path
4366 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4367 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004368 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004369 nextConst, false);
4370 }
4371
4372 // We now know we have a specialization constant to build
4373
John Kessenichd94c0032016-05-30 19:29:40 -06004374 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004375 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4376 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4377 std::vector<spv::Id> dimConstId;
4378 for (int dim = 0; dim < 3; ++dim) {
4379 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4380 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4381 if (specConst)
4382 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4383 }
4384 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4385 }
4386
4387 // An AST node labelled as specialization constant should be a symbol node.
4388 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4389 if (auto* sn = node.getAsSymbolNode()) {
4390 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004391 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4392 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4393 // will set the builder into spec constant op instruction generating mode.
4394 sub_tree->traverse(this);
4395 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004396 } else if (auto* const_union_array = &sn->getConstArray()){
4397 int nextConst = 0;
4398 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004399 }
4400 }
qining4f4bb812016-04-03 23:55:17 -04004401
4402 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4403 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004404 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004405 exit(1);
4406 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004407}
4408
John Kessenich140f3df2015-06-26 16:58:36 -06004409// Use 'consts' as the flattened glslang source of scalar constants to recursively
4410// build the aggregate SPIR-V constant.
4411//
4412// If there are not enough elements present in 'consts', 0 will be substituted;
4413// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4414//
qining08408382016-03-21 09:51:37 -04004415spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004416{
4417 // vector of constants for SPIR-V
4418 std::vector<spv::Id> spvConsts;
4419
4420 // Type is used for struct and array constants
4421 spv::Id typeId = convertGlslangToSpvType(glslangType);
4422
4423 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004424 glslang::TType elementType(glslangType, 0);
4425 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004426 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004427 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004428 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004429 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004430 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004431 } else if (glslangType.getStruct()) {
4432 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4433 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004434 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004435 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004436 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4437 bool zero = nextConst >= consts.size();
4438 switch (glslangType.getBasicType()) {
4439 case glslang::EbtInt:
4440 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4441 break;
4442 case glslang::EbtUint:
4443 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4444 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004445 case glslang::EbtInt64:
4446 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4447 break;
4448 case glslang::EbtUint64:
4449 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4450 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004451 case glslang::EbtFloat:
4452 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4453 break;
4454 case glslang::EbtDouble:
4455 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4456 break;
4457 case glslang::EbtBool:
4458 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4459 break;
4460 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004461 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004462 break;
4463 }
4464 ++nextConst;
4465 }
4466 } else {
4467 // we have a non-aggregate (scalar) constant
4468 bool zero = nextConst >= consts.size();
4469 spv::Id scalar = 0;
4470 switch (glslangType.getBasicType()) {
4471 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004472 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004473 break;
4474 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004475 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004476 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004477 case glslang::EbtInt64:
4478 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4479 break;
4480 case glslang::EbtUint64:
4481 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4482 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004483 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004484 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004485 break;
4486 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004487 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004488 break;
4489 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004490 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004491 break;
4492 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004493 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004494 break;
4495 }
4496 ++nextConst;
4497 return scalar;
4498 }
4499
4500 return builder.makeCompositeConstant(typeId, spvConsts);
4501}
4502
John Kessenich7c1aa102015-10-15 13:29:11 -06004503// Return true if the node is a constant or symbol whose reading has no
4504// non-trivial observable cost or effect.
4505bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4506{
4507 // don't know what this is
4508 if (node == nullptr)
4509 return false;
4510
4511 // a constant is safe
4512 if (node->getAsConstantUnion() != nullptr)
4513 return true;
4514
4515 // not a symbol means non-trivial
4516 if (node->getAsSymbolNode() == nullptr)
4517 return false;
4518
4519 // a symbol, depends on what's being read
4520 switch (node->getType().getQualifier().storage) {
4521 case glslang::EvqTemporary:
4522 case glslang::EvqGlobal:
4523 case glslang::EvqIn:
4524 case glslang::EvqInOut:
4525 case glslang::EvqConst:
4526 case glslang::EvqConstReadOnly:
4527 case glslang::EvqUniform:
4528 return true;
4529 default:
4530 return false;
4531 }
qining25262b32016-05-06 17:25:16 -04004532}
John Kessenich7c1aa102015-10-15 13:29:11 -06004533
4534// A node is trivial if it is a single operation with no side effects.
4535// Error on the side of saying non-trivial.
4536// Return true if trivial.
4537bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4538{
4539 if (node == nullptr)
4540 return false;
4541
4542 // symbols and constants are trivial
4543 if (isTrivialLeaf(node))
4544 return true;
4545
4546 // otherwise, it needs to be a simple operation or one or two leaf nodes
4547
4548 // not a simple operation
4549 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4550 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4551 if (binaryNode == nullptr && unaryNode == nullptr)
4552 return false;
4553
4554 // not on leaf nodes
4555 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4556 return false;
4557
4558 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4559 return false;
4560 }
4561
4562 switch (node->getAsOperator()->getOp()) {
4563 case glslang::EOpLogicalNot:
4564 case glslang::EOpConvIntToBool:
4565 case glslang::EOpConvUintToBool:
4566 case glslang::EOpConvFloatToBool:
4567 case glslang::EOpConvDoubleToBool:
4568 case glslang::EOpEqual:
4569 case glslang::EOpNotEqual:
4570 case glslang::EOpLessThan:
4571 case glslang::EOpGreaterThan:
4572 case glslang::EOpLessThanEqual:
4573 case glslang::EOpGreaterThanEqual:
4574 case glslang::EOpIndexDirect:
4575 case glslang::EOpIndexDirectStruct:
4576 case glslang::EOpLogicalXor:
4577 case glslang::EOpAny:
4578 case glslang::EOpAll:
4579 return true;
4580 default:
4581 return false;
4582 }
4583}
4584
4585// Emit short-circuiting code, where 'right' is never evaluated unless
4586// the left side is true (for &&) or false (for ||).
4587spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4588{
4589 spv::Id boolTypeId = builder.makeBoolType();
4590
4591 // emit left operand
4592 builder.clearAccessChain();
4593 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004594 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004595
4596 // Operands to accumulate OpPhi operands
4597 std::vector<spv::Id> phiOperands;
4598 // accumulate left operand's phi information
4599 phiOperands.push_back(leftId);
4600 phiOperands.push_back(builder.getBuildPoint()->getId());
4601
4602 // Make the two kinds of operation symmetric with a "!"
4603 // || => emit "if (! left) result = right"
4604 // && => emit "if ( left) result = right"
4605 //
4606 // TODO: this runtime "not" for || could be avoided by adding functionality
4607 // to 'builder' to have an "else" without an "then"
4608 if (op == glslang::EOpLogicalOr)
4609 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4610
4611 // make an "if" based on the left value
4612 spv::Builder::If ifBuilder(leftId, builder);
4613
4614 // emit right operand as the "then" part of the "if"
4615 builder.clearAccessChain();
4616 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004617 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004618
4619 // accumulate left operand's phi information
4620 phiOperands.push_back(rightId);
4621 phiOperands.push_back(builder.getBuildPoint()->getId());
4622
4623 // finish the "if"
4624 ifBuilder.makeEndIf();
4625
4626 // phi together the two results
4627 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4628}
4629
Rex Xu9d93a232016-05-05 12:30:44 +08004630// Return type Id of the imported set of extended instructions corresponds to the name.
4631// Import this set if it has not been imported yet.
4632spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4633{
4634 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4635 return extBuiltinMap[name];
4636 else {
4637 builder.addExtensions(name);
4638 spv::Id extBuiltins = builder.import(name);
4639 extBuiltinMap[name] = extBuiltins;
4640 return extBuiltins;
4641 }
4642}
4643
John Kessenich140f3df2015-06-26 16:58:36 -06004644}; // end anonymous namespace
4645
4646namespace glslang {
4647
John Kessenich68d78fd2015-07-12 19:28:10 -06004648void GetSpirvVersion(std::string& version)
4649{
John Kessenich9e55f632015-07-15 10:03:39 -06004650 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004651 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004652 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004653 version = buf;
4654}
4655
John Kessenich140f3df2015-06-26 16:58:36 -06004656// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004657void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004658{
4659 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004660 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004661 for (int i = 0; i < (int)spirv.size(); ++i) {
4662 unsigned int word = spirv[i];
4663 out.write((const char*)&word, 4);
4664 }
4665 out.close();
4666}
4667
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004668// Write SPIR-V out to a text file with 32-bit hexadecimal words
4669void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4670{
4671 std::ofstream out;
4672 out.open(baseName, std::ios::binary | std::ios::out);
4673 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4674 const int WORDS_PER_LINE = 8;
4675 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4676 out << "\t";
4677 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4678 const unsigned int word = spirv[i + j];
4679 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4680 if (i + j + 1 < (int)spirv.size()) {
4681 out << ",";
4682 }
4683 }
4684 out << std::endl;
4685 }
4686 out.close();
4687}
4688
John Kessenich140f3df2015-06-26 16:58:36 -06004689//
4690// Set up the glslang traversal
4691//
4692void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4693{
Lei Zhang17535f72016-05-04 15:55:59 -04004694 spv::SpvBuildLogger logger;
4695 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004696}
4697
Lei Zhang17535f72016-05-04 15:55:59 -04004698void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004699{
John Kessenich140f3df2015-06-26 16:58:36 -06004700 TIntermNode* root = intermediate.getTreeRoot();
4701
4702 if (root == 0)
4703 return;
4704
4705 glslang::GetThreadPoolAllocator().push();
4706
Lei Zhang17535f72016-05-04 15:55:59 -04004707 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004708
4709 root->traverse(&it);
4710
4711 it.dumpSpv(spirv);
4712
4713 glslang::GetThreadPoolAllocator().pop();
4714}
4715
4716}; // end namespace glslang