blob: 146666527643f66f262ab27ee750c95701f40ed2 [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&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600121 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
122 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
123 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600124 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700125 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600126 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
127 glslang::TLayoutPacking, const glslang::TQualifier&);
128 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
129 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700130 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700131 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800132 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700133 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700134 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
135 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
136 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 +0100137 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600138
139 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
140 void makeFunctions(const glslang::TIntermSequence&);
141 void makeGlobalInitializers(const glslang::TIntermSequence&);
142 void visitFunctions(const glslang::TIntermSequence&);
143 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800144 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600145 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
146 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
148
qining25262b32016-05-06 17:25:16 -0400149 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);
150 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
151 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800152 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800153 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 -0600154 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800156 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy);
157#ifdef AMD_EXTENSIONS
158 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand);
159#endif
John Kessenich5e4b1242015-08-06 22:53:06 -0600160 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 +0800161 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
163 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700164 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700166 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400167 spv::Id createSpvConstant(const glslang::TIntermTyped&);
168 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600169 bool isTrivialLeaf(const glslang::TIntermTyped* node);
170 bool isTrivial(const glslang::TIntermTyped* node);
171 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800172 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600173
174 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700175 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600176 int sequenceDepth;
177
Lei Zhang17535f72016-05-04 15:55:59 -0400178 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400179
John Kessenich140f3df2015-06-26 16:58:36 -0600180 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
181 spv::Builder builder;
182 bool inMain;
183 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700184 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 -0700185 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600186 const glslang::TIntermediate* glslangIntermediate;
187 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800188 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600189
John Kessenich2f273362015-07-18 22:34:27 -0600190 std::unordered_map<int, spv::Id> symbolValues;
191 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
192 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700193 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600194 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 -0600195 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600196};
197
198//
199// Helper functions for translating glslang representations to SPIR-V enumerants.
200//
201
202// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700203spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600204{
John Kessenich66e2faf2016-03-12 18:34:36 -0700205 switch (source) {
206 case glslang::EShSourceGlsl:
207 switch (profile) {
208 case ENoProfile:
209 case ECoreProfile:
210 case ECompatibilityProfile:
211 return spv::SourceLanguageGLSL;
212 case EEsProfile:
213 return spv::SourceLanguageESSL;
214 default:
215 return spv::SourceLanguageUnknown;
216 }
217 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400218 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
219 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 default:
221 return spv::SourceLanguageUnknown;
222 }
223}
224
225// Translate glslang language (stage) to SPIR-V execution model.
226spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
227{
228 switch (stage) {
229 case EShLangVertex: return spv::ExecutionModelVertex;
230 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
231 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
232 case EShLangGeometry: return spv::ExecutionModelGeometry;
233 case EShLangFragment: return spv::ExecutionModelFragment;
234 case EShLangCompute: return spv::ExecutionModelGLCompute;
235 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700236 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600237 return spv::ExecutionModelFragment;
238 }
239}
240
241// Translate glslang type to SPIR-V storage class.
242spv::StorageClass TranslateStorageClass(const glslang::TType& type)
243{
244 if (type.getQualifier().isPipeInput())
245 return spv::StorageClassInput;
246 else if (type.getQualifier().isPipeOutput())
247 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700248 else if (type.getBasicType() == glslang::EbtSampler)
249 return spv::StorageClassUniformConstant;
250 else if (type.getBasicType() == glslang::EbtAtomicUint)
251 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600252 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700253 if (type.getQualifier().layoutPushConstant)
254 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600255 if (type.getBasicType() == glslang::EbtBlock)
256 return spv::StorageClassUniform;
257 else
258 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600259 // 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 -0600260 } else {
261 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700262 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
263 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
265 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400266 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600268 return spv::StorageClassFunction;
269 }
270 }
271}
272
273// Translate glslang sampler type to SPIR-V dimensionality.
274spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
275{
276 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700277 case glslang::Esd1D: return spv::Dim1D;
278 case glslang::Esd2D: return spv::Dim2D;
279 case glslang::Esd3D: return spv::Dim3D;
280 case glslang::EsdCube: return spv::DimCube;
281 case glslang::EsdRect: return spv::DimRect;
282 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700283 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700285 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600286 return spv::Dim2D;
287 }
288}
289
John Kessenichf6640762016-08-01 19:44:00 -0600290// Translate glslang precision to SPIR-V precision decorations.
291spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600292{
John Kessenichf6640762016-08-01 19:44:00 -0600293 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700294 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600295 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 default:
297 return spv::NoPrecision;
298 }
299}
300
John Kessenichf6640762016-08-01 19:44:00 -0600301// Translate glslang type to SPIR-V precision decorations.
302spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
303{
304 return TranslatePrecisionDecoration(type.getQualifier().precision);
305}
306
John Kessenich140f3df2015-06-26 16:58:36 -0600307// Translate glslang type to SPIR-V block decorations.
308spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
309{
310 if (type.getBasicType() == glslang::EbtBlock) {
311 switch (type.getQualifier().storage) {
312 case glslang::EvqUniform: return spv::DecorationBlock;
313 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
314 case glslang::EvqVaryingIn: return spv::DecorationBlock;
315 case glslang::EvqVaryingOut: return spv::DecorationBlock;
316 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600318 break;
319 }
320 }
321
John Kessenich4016e382016-07-15 11:53:56 -0600322 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600323}
324
Rex Xu1da878f2016-02-21 20:59:01 +0800325// Translate glslang type to SPIR-V memory decorations.
326void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
327{
328 if (qualifier.coherent)
329 memory.push_back(spv::DecorationCoherent);
330 if (qualifier.volatil)
331 memory.push_back(spv::DecorationVolatile);
332 if (qualifier.restrict)
333 memory.push_back(spv::DecorationRestrict);
334 if (qualifier.readonly)
335 memory.push_back(spv::DecorationNonWritable);
336 if (qualifier.writeonly)
337 memory.push_back(spv::DecorationNonReadable);
338}
339
John Kessenich140f3df2015-06-26 16:58:36 -0600340// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700341spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600342{
343 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700344 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600345 case glslang::ElmRowMajor:
346 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700347 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 default:
350 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 }
353 } else {
354 switch (type.getBasicType()) {
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 break;
358 case glslang::EbtBlock:
359 switch (type.getQualifier().storage) {
360 case glslang::EvqUniform:
361 case glslang::EvqBuffer:
362 switch (type.getQualifier().layoutPacking) {
363 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
365 default:
John Kessenich4016e382016-07-15 11:53:56 -0600366 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 }
368 case glslang::EvqVaryingIn:
369 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700370 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700373 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600374 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600375 }
376 }
377 }
378}
379
380// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700382// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800383spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600384{
Rex Xubbceed72016-05-21 09:40:44 +0800385 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700386 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700389 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700390 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800392#ifdef AMD_EXTENSIONS
393 else if (qualifier.explicitInterp)
394 return spv::DecorationExplicitInterpAMD;
395#endif
Rex Xubbceed72016-05-21 09:40:44 +0800396 else
John Kessenich4016e382016-07-15 11:53:56 -0600397 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800398}
399
400// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600401// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800402// should be applied.
403spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
404{
405 if (qualifier.patch)
406 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600408 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700409 else if (qualifier.sample) {
410 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600411 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700412 } else
John Kessenich4016e382016-07-15 11:53:56 -0600413 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600414}
415
John Kessenich92187592016-02-01 13:45:25 -0700416// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700417spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600418{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700419 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600420 return spv::DecorationInvariant;
421 else
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423}
424
qining9220dbb2016-05-04 17:34:38 -0400425// If glslang type is noContraction, return SPIR-V NoContraction decoration.
426spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
427{
428 if (qualifier.noContraction)
429 return spv::DecorationNoContraction;
430 else
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400432}
433
David Netoa901ffe2016-06-08 14:11:40 +0100434// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
435// associated capabilities when required. For some built-in variables, a capability
436// is generated only when using the variable in an executable instruction, but not when
437// just declaring a struct member variable with it. This is true for PointSize,
438// ClipDistance, and CullDistance.
439spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600440{
441 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700442 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600443 // Defer adding the capability until the built-in is actually used.
444 if (! memberDeclaration) {
445 switch (glslangIntermediate->getStage()) {
446 case EShLangGeometry:
447 builder.addCapability(spv::CapabilityGeometryPointSize);
448 break;
449 case EShLangTessControl:
450 case EShLangTessEvaluation:
451 builder.addCapability(spv::CapabilityTessellationPointSize);
452 break;
453 default:
454 break;
455 }
John Kessenich92187592016-02-01 13:45:25 -0700456 }
457 return spv::BuiltInPointSize;
458
John Kessenichebb50532016-05-16 19:22:05 -0600459 // These *Distance capabilities logically belong here, but if the member is declared and
460 // then never used, consumers of SPIR-V prefer the capability not be declared.
461 // They are now generated when used, rather than here when declared.
462 // Potentially, the specification should be more clear what the minimum
463 // use needed is to trigger the capability.
464 //
John Kessenich92187592016-02-01 13:45:25 -0700465 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100466 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600467 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInClipDistance;
469
470 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100471 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600472 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700473 return spv::BuiltInCullDistance;
474
475 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500476 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700477 return spv::BuiltInViewportIndex;
478
John Kessenich5e801132016-02-15 11:09:46 -0700479 case glslang::EbvSampleId:
480 builder.addCapability(spv::CapabilitySampleRateShading);
481 return spv::BuiltInSampleId;
482
483 case glslang::EbvSamplePosition:
484 builder.addCapability(spv::CapabilitySampleRateShading);
485 return spv::BuiltInSamplePosition;
486
487 case glslang::EbvSampleMask:
488 builder.addCapability(spv::CapabilitySampleRateShading);
489 return spv::BuiltInSampleMask;
490
John Kessenich78a45572016-07-08 14:05:15 -0600491 case glslang::EbvLayer:
492 builder.addCapability(spv::CapabilityGeometry);
493 return spv::BuiltInLayer;
494
John Kessenich140f3df2015-06-26 16:58:36 -0600495 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvVertexId: return spv::BuiltInVertexId;
497 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700498 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
499 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600500 case glslang::EbvBaseVertex:
501 case glslang::EbvBaseInstance:
502 case glslang::EbvDrawId:
503 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600504 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600505 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600506 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
507 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600508 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
509 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
510 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
511 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
512 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
513 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
514 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600515 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
516 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
517 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
518 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
519 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
520 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
521 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
522 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800523 case glslang::EbvSubGroupSize:
524 case glslang::EbvSubGroupInvocation:
525 case glslang::EbvSubGroupEqMask:
526 case glslang::EbvSubGroupGeMask:
527 case glslang::EbvSubGroupGtMask:
528 case glslang::EbvSubGroupLeMask:
529 case glslang::EbvSubGroupLtMask:
530 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600531 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600532 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800533#ifdef AMD_EXTENSIONS
534 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
535 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
536 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
537 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
538 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
539 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
540 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
541#endif
John Kessenich4016e382016-07-15 11:53:56 -0600542 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600543 }
544}
545
Rex Xufc618912015-09-09 16:42:49 +0800546// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700547spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800548{
549 assert(type.getBasicType() == glslang::EbtSampler);
550
John Kessenich5d0fa972016-02-15 11:57:00 -0700551 // Check for capabilities
552 switch (type.getQualifier().layoutFormat) {
553 case glslang::ElfRg32f:
554 case glslang::ElfRg16f:
555 case glslang::ElfR11fG11fB10f:
556 case glslang::ElfR16f:
557 case glslang::ElfRgba16:
558 case glslang::ElfRgb10A2:
559 case glslang::ElfRg16:
560 case glslang::ElfRg8:
561 case glslang::ElfR16:
562 case glslang::ElfR8:
563 case glslang::ElfRgba16Snorm:
564 case glslang::ElfRg16Snorm:
565 case glslang::ElfRg8Snorm:
566 case glslang::ElfR16Snorm:
567 case glslang::ElfR8Snorm:
568
569 case glslang::ElfRg32i:
570 case glslang::ElfRg16i:
571 case glslang::ElfRg8i:
572 case glslang::ElfR16i:
573 case glslang::ElfR8i:
574
575 case glslang::ElfRgb10a2ui:
576 case glslang::ElfRg32ui:
577 case glslang::ElfRg16ui:
578 case glslang::ElfRg8ui:
579 case glslang::ElfR16ui:
580 case glslang::ElfR8ui:
581 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
582 break;
583
584 default:
585 break;
586 }
587
588 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800589 switch (type.getQualifier().layoutFormat) {
590 case glslang::ElfNone: return spv::ImageFormatUnknown;
591 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
592 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
593 case glslang::ElfR32f: return spv::ImageFormatR32f;
594 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
595 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
596 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
597 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
598 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
599 case glslang::ElfR16f: return spv::ImageFormatR16f;
600 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
601 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
602 case glslang::ElfRg16: return spv::ImageFormatRg16;
603 case glslang::ElfRg8: return spv::ImageFormatRg8;
604 case glslang::ElfR16: return spv::ImageFormatR16;
605 case glslang::ElfR8: return spv::ImageFormatR8;
606 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
607 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
608 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
609 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
610 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
611 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
612 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
613 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
614 case glslang::ElfR32i: return spv::ImageFormatR32i;
615 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
616 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
617 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
618 case glslang::ElfR16i: return spv::ImageFormatR16i;
619 case glslang::ElfR8i: return spv::ImageFormatR8i;
620 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
621 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
622 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
623 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
624 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
625 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
626 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
627 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
628 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
629 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600630 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800631 }
632}
633
qining25262b32016-05-06 17:25:16 -0400634// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700635// descriptor set.
636bool IsDescriptorResource(const glslang::TType& type)
637{
John Kessenichf7497e22016-03-08 21:36:22 -0700638 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700639 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700640 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700641
642 // non block...
643 // basically samplerXXX/subpass/sampler/texture are all included
644 // if they are the global-scope-class, not the function parameter
645 // (or local, if they ever exist) class.
646 if (type.getBasicType() == glslang::EbtSampler)
647 return type.getQualifier().isUniformOrBuffer();
648
649 // None of the above.
650 return false;
651}
652
John Kesseniche0b6cad2015-12-24 10:30:13 -0700653void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
654{
655 if (child.layoutMatrix == glslang::ElmNone)
656 child.layoutMatrix = parent.layoutMatrix;
657
658 if (parent.invariant)
659 child.invariant = true;
660 if (parent.nopersp)
661 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800662#ifdef AMD_EXTENSIONS
663 if (parent.explicitInterp)
664 child.explicitInterp = true;
665#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700666 if (parent.flat)
667 child.flat = true;
668 if (parent.centroid)
669 child.centroid = true;
670 if (parent.patch)
671 child.patch = true;
672 if (parent.sample)
673 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800674 if (parent.coherent)
675 child.coherent = true;
676 if (parent.volatil)
677 child.volatil = true;
678 if (parent.restrict)
679 child.restrict = true;
680 if (parent.readonly)
681 child.readonly = true;
682 if (parent.writeonly)
683 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700684}
685
686bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
687{
John Kessenich7b9fa252016-01-21 18:56:57 -0700688 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700689 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600690 // - 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 -0700691 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600692 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700693}
694
John Kessenich140f3df2015-06-26 16:58:36 -0600695//
696// Implement the TGlslangToSpvTraverser class.
697//
698
Lei Zhang17535f72016-05-04 15:55:59 -0400699TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
700 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
701 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600702 inMain(false), mainTerminated(false), linkageOnly(false),
703 glslangIntermediate(glslangIntermediate)
704{
705 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
706
707 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700708 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600709 stdBuiltins = builder.import("GLSL.std.450");
710 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700711 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
712 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600713
714 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600715 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
716 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600717 builder.addSourceExtension(it->c_str());
718
719 // Add the top-level modes for this shader.
720
John Kessenich92187592016-02-01 13:45:25 -0700721 if (glslangIntermediate->getXfbMode()) {
722 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600723 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700724 }
John Kessenich140f3df2015-06-26 16:58:36 -0600725
726 unsigned int mode;
727 switch (glslangIntermediate->getStage()) {
728 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600729 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600730 break;
731
732 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600733 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600734 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
735 break;
736
737 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600738 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600739 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700740 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
741 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
742 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600743 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600744 }
John Kessenich4016e382016-07-15 11:53:56 -0600745 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600746 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
747
John Kesseniche6903322015-10-13 16:29:02 -0600748 switch (glslangIntermediate->getVertexSpacing()) {
749 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
750 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
751 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600752 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600753 }
John Kessenich4016e382016-07-15 11:53:56 -0600754 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600755 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
756
757 switch (glslangIntermediate->getVertexOrder()) {
758 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
759 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600760 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600761 }
John Kessenich4016e382016-07-15 11:53:56 -0600762 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600763 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
764
765 if (glslangIntermediate->getPointMode())
766 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600767 break;
768
769 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600770 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600771 switch (glslangIntermediate->getInputPrimitive()) {
772 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
773 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
774 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700775 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600776 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600777 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600778 }
John Kessenich4016e382016-07-15 11:53:56 -0600779 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600780 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600781
John Kessenich140f3df2015-06-26 16:58:36 -0600782 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
783
784 switch (glslangIntermediate->getOutputPrimitive()) {
785 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
786 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
787 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600788 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600789 }
John Kessenich4016e382016-07-15 11:53:56 -0600790 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600791 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
792 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
793 break;
794
795 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600796 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600797 if (glslangIntermediate->getPixelCenterInteger())
798 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600799
John Kessenich140f3df2015-06-26 16:58:36 -0600800 if (glslangIntermediate->getOriginUpperLeft())
801 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600802 else
803 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600804
805 if (glslangIntermediate->getEarlyFragmentTests())
806 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
807
808 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600809 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
810 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600811 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600812 }
John Kessenich4016e382016-07-15 11:53:56 -0600813 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600814 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
815
816 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
817 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600818 break;
819
820 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600821 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600822 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
823 glslangIntermediate->getLocalSize(1),
824 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600825 break;
826
827 default:
828 break;
829 }
830
831}
832
John Kessenich7ba63412015-12-20 17:37:07 -0700833// Finish everything and dump
834void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
835{
836 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100837 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
838 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700839
qiningda397332016-03-09 19:54:03 -0500840 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700841 builder.dump(out);
842}
843
John Kessenich140f3df2015-06-26 16:58:36 -0600844TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
845{
846 if (! mainTerminated) {
847 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
848 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600849 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600850 }
851}
852
853//
854// Implement the traversal functions.
855//
856// Return true from interior nodes to have the external traversal
857// continue on to children. Return false if children were
858// already processed.
859//
860
861//
qining25262b32016-05-06 17:25:16 -0400862// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600863// - uniform/input reads
864// - output writes
865// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
866// - something simple that degenerates into the last bullet
867//
868void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
869{
qining75d1d802016-04-06 14:42:01 -0400870 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
871 if (symbol->getType().getQualifier().isSpecConstant())
872 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
873
John Kessenich140f3df2015-06-26 16:58:36 -0600874 // getSymbolId() will set up all the IO decorations on the first call.
875 // Formal function parameters were mapped during makeFunctions().
876 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700877
878 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
879 if (builder.isPointer(id)) {
880 spv::StorageClass sc = builder.getStorageClass(id);
881 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
882 iOSet.insert(id);
883 }
884
885 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700886 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600887 // Prepare to generate code for the access
888
889 // L-value chains will be computed left to right. We're on the symbol now,
890 // which is the left-most part of the access chain, so now is "clear" time,
891 // followed by setting the base.
892 builder.clearAccessChain();
893
894 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700895 // except for
896 // A) "const in" arguments to a function, which are an intermediate object.
897 // See comments in handleUserFunctionCall().
898 // B) Specialization constants (normal constant don't even come in as a variable),
899 // These are also pure R-values.
900 glslang::TQualifier qualifier = symbol->getQualifier();
901 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
902 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600903 builder.setAccessChainRValue(id);
904 else
905 builder.setAccessChainLValue(id);
906 }
907}
908
909bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
910{
qining40887662016-04-03 22:20:42 -0400911 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
912 if (node->getType().getQualifier().isSpecConstant())
913 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
914
John Kessenich140f3df2015-06-26 16:58:36 -0600915 // First, handle special cases
916 switch (node->getOp()) {
917 case glslang::EOpAssign:
918 case glslang::EOpAddAssign:
919 case glslang::EOpSubAssign:
920 case glslang::EOpMulAssign:
921 case glslang::EOpVectorTimesMatrixAssign:
922 case glslang::EOpVectorTimesScalarAssign:
923 case glslang::EOpMatrixTimesScalarAssign:
924 case glslang::EOpMatrixTimesMatrixAssign:
925 case glslang::EOpDivAssign:
926 case glslang::EOpModAssign:
927 case glslang::EOpAndAssign:
928 case glslang::EOpInclusiveOrAssign:
929 case glslang::EOpExclusiveOrAssign:
930 case glslang::EOpLeftShiftAssign:
931 case glslang::EOpRightShiftAssign:
932 // A bin-op assign "a += b" means the same thing as "a = a + b"
933 // where a is evaluated before b. For a simple assignment, GLSL
934 // says to evaluate the left before the right. So, always, left
935 // node then right node.
936 {
937 // get the left l-value, save it away
938 builder.clearAccessChain();
939 node->getLeft()->traverse(this);
940 spv::Builder::AccessChain lValue = builder.getAccessChain();
941
942 // evaluate the right
943 builder.clearAccessChain();
944 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700945 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600946
947 if (node->getOp() != glslang::EOpAssign) {
948 // the left is also an r-value
949 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700950 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600951
952 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600953 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400954 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600955 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
956 node->getType().getBasicType());
957
958 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700959 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600960 }
961
962 // store the result
963 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800964 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600965
966 // assignments are expressions having an rValue after they are evaluated...
967 builder.clearAccessChain();
968 builder.setAccessChainRValue(rValue);
969 }
970 return false;
971 case glslang::EOpIndexDirect:
972 case glslang::EOpIndexDirectStruct:
973 {
974 // Get the left part of the access chain.
975 node->getLeft()->traverse(this);
976
977 // Add the next element in the chain
978
David Netoa901ffe2016-06-08 14:11:40 +0100979 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600980 if (! node->getLeft()->getType().isArray() &&
981 node->getLeft()->getType().isVector() &&
982 node->getOp() == glslang::EOpIndexDirect) {
983 // This is essentially a hard-coded vector swizzle of size 1,
984 // so short circuit the access-chain stuff with a swizzle.
985 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100986 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600987 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600988 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100989 int spvIndex = glslangIndex;
990 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
991 node->getOp() == glslang::EOpIndexDirectStruct)
992 {
993 // This may be, e.g., an anonymous block-member selection, which generally need
994 // index remapping due to hidden members in anonymous blocks.
995 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
996 assert(remapper.size() > 0);
997 spvIndex = remapper[glslangIndex];
998 }
John Kessenichebb50532016-05-16 19:22:05 -0600999
David Netoa901ffe2016-06-08 14:11:40 +01001000 // normal case for indexing array or structure or block
1001 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1002
1003 // Add capabilities here for accessing PointSize and clip/cull distance.
1004 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001005 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001006 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001007 }
1008 }
1009 return false;
1010 case glslang::EOpIndexIndirect:
1011 {
1012 // Structure or array or vector indirection.
1013 // Will use native SPIR-V access-chain for struct and array indirection;
1014 // matrices are arrays of vectors, so will also work for a matrix.
1015 // Will use the access chain's 'component' for variable index into a vector.
1016
1017 // This adapter is building access chains left to right.
1018 // Set up the access chain to the left.
1019 node->getLeft()->traverse(this);
1020
1021 // save it so that computing the right side doesn't trash it
1022 spv::Builder::AccessChain partial = builder.getAccessChain();
1023
1024 // compute the next index in the chain
1025 builder.clearAccessChain();
1026 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001027 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001028
1029 // restore the saved access chain
1030 builder.setAccessChain(partial);
1031
1032 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001033 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001034 else
John Kessenichfa668da2015-09-13 14:46:30 -06001035 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001036 }
1037 return false;
1038 case glslang::EOpVectorSwizzle:
1039 {
1040 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001041 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001042 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001043 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001044 }
1045 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001046 case glslang::EOpLogicalOr:
1047 case glslang::EOpLogicalAnd:
1048 {
1049
1050 // These may require short circuiting, but can sometimes be done as straight
1051 // binary operations. The right operand must be short circuited if it has
1052 // side effects, and should probably be if it is complex.
1053 if (isTrivial(node->getRight()->getAsTyped()))
1054 break; // handle below as a normal binary operation
1055 // otherwise, we need to do dynamic short circuiting on the right operand
1056 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1057 builder.clearAccessChain();
1058 builder.setAccessChainRValue(result);
1059 }
1060 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001061 default:
1062 break;
1063 }
1064
1065 // Assume generic binary op...
1066
John Kessenich32cfd492016-02-02 12:37:46 -07001067 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001068 builder.clearAccessChain();
1069 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001070 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001071
John Kessenich32cfd492016-02-02 12:37:46 -07001072 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001073 builder.clearAccessChain();
1074 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001075 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001076
John Kessenich32cfd492016-02-02 12:37:46 -07001077 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001078 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001079 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001080 convertGlslangToSpvType(node->getType()), left, right,
1081 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001082
John Kessenich50e57562015-12-21 21:21:11 -07001083 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001084 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001085 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001086 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001087 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001088 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001089 return false;
1090 }
John Kessenich140f3df2015-06-26 16:58:36 -06001091}
1092
1093bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1094{
qining40887662016-04-03 22:20:42 -04001095 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1096 if (node->getType().getQualifier().isSpecConstant())
1097 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1098
John Kessenichfc51d282015-08-19 13:34:18 -06001099 spv::Id result = spv::NoResult;
1100
1101 // try texturing first
1102 result = createImageTextureFunctionCall(node);
1103 if (result != spv::NoResult) {
1104 builder.clearAccessChain();
1105 builder.setAccessChainRValue(result);
1106
1107 return false; // done with this node
1108 }
1109
1110 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001111
1112 if (node->getOp() == glslang::EOpArrayLength) {
1113 // Quite special; won't want to evaluate the operand.
1114
1115 // Normal .length() would have been constant folded by the front-end.
1116 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001117 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001118 assert(node->getOperand()->getType().isRuntimeSizedArray());
1119 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1120 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001121 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1122 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001123
1124 builder.clearAccessChain();
1125 builder.setAccessChainRValue(length);
1126
1127 return false;
1128 }
1129
John Kessenichfc51d282015-08-19 13:34:18 -06001130 // Start by evaluating the operand
1131
John Kessenich8c8505c2016-07-26 12:50:38 -06001132 // Does it need a swizzle inversion? If so, evaluation is inverted;
1133 // operate first on the swizzle base, then apply the swizzle.
1134 spv::Id invertedType = spv::NoType;
1135 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1136 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1137 invertedType = getInvertedSwizzleType(*node->getOperand());
1138
John Kessenich140f3df2015-06-26 16:58:36 -06001139 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001140 if (invertedType != spv::NoType)
1141 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1142 else
1143 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001144
Rex Xufc618912015-09-09 16:42:49 +08001145 spv::Id operand = spv::NoResult;
1146
1147 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1148 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001149 node->getOp() == glslang::EOpAtomicCounter ||
1150 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001151 operand = builder.accessChainGetLValue(); // Special case l-value operands
1152 else
John Kessenich32cfd492016-02-02 12:37:46 -07001153 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001154
John Kessenichf6640762016-08-01 19:44:00 -06001155 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001156 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001157
1158 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001159 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001160 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001161
1162 // if not, then possibly an operation
1163 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001164 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001165
1166 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001167 if (invertedType)
1168 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1169
John Kessenich140f3df2015-06-26 16:58:36 -06001170 builder.clearAccessChain();
1171 builder.setAccessChainRValue(result);
1172
1173 return false; // done with this node
1174 }
1175
1176 // it must be a special case, check...
1177 switch (node->getOp()) {
1178 case glslang::EOpPostIncrement:
1179 case glslang::EOpPostDecrement:
1180 case glslang::EOpPreIncrement:
1181 case glslang::EOpPreDecrement:
1182 {
1183 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001184 spv::Id one = 0;
1185 if (node->getBasicType() == glslang::EbtFloat)
1186 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001187 else if (node->getBasicType() == glslang::EbtDouble)
1188 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001189 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1190 one = builder.makeInt64Constant(1);
1191 else
1192 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001193 glslang::TOperator op;
1194 if (node->getOp() == glslang::EOpPreIncrement ||
1195 node->getOp() == glslang::EOpPostIncrement)
1196 op = glslang::EOpAdd;
1197 else
1198 op = glslang::EOpSub;
1199
John Kessenichf6640762016-08-01 19:44:00 -06001200 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001201 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001202 convertGlslangToSpvType(node->getType()), operand, one,
1203 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001204 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001205
1206 // The result of operation is always stored, but conditionally the
1207 // consumed result. The consumed result is always an r-value.
1208 builder.accessChainStore(result);
1209 builder.clearAccessChain();
1210 if (node->getOp() == glslang::EOpPreIncrement ||
1211 node->getOp() == glslang::EOpPreDecrement)
1212 builder.setAccessChainRValue(result);
1213 else
1214 builder.setAccessChainRValue(operand);
1215 }
1216
1217 return false;
1218
1219 case glslang::EOpEmitStreamVertex:
1220 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1221 return false;
1222 case glslang::EOpEndStreamPrimitive:
1223 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1224 return false;
1225
1226 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001227 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001228 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001229 }
John Kessenich140f3df2015-06-26 16:58:36 -06001230}
1231
1232bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1233{
qining27e04a02016-04-14 16:40:20 -04001234 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1235 if (node->getType().getQualifier().isSpecConstant())
1236 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1237
John Kessenichfc51d282015-08-19 13:34:18 -06001238 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001239 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1240 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001241
1242 // try texturing
1243 result = createImageTextureFunctionCall(node);
1244 if (result != spv::NoResult) {
1245 builder.clearAccessChain();
1246 builder.setAccessChainRValue(result);
1247
1248 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001249 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001250 // "imageStore" is a special case, which has no result
1251 return false;
1252 }
John Kessenichfc51d282015-08-19 13:34:18 -06001253
John Kessenich140f3df2015-06-26 16:58:36 -06001254 glslang::TOperator binOp = glslang::EOpNull;
1255 bool reduceComparison = true;
1256 bool isMatrix = false;
1257 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001258 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001259
1260 assert(node->getOp());
1261
John Kessenichf6640762016-08-01 19:44:00 -06001262 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001263
1264 switch (node->getOp()) {
1265 case glslang::EOpSequence:
1266 {
1267 if (preVisit)
1268 ++sequenceDepth;
1269 else
1270 --sequenceDepth;
1271
1272 if (sequenceDepth == 1) {
1273 // If this is the parent node of all the functions, we want to see them
1274 // early, so all call points have actual SPIR-V functions to reference.
1275 // In all cases, still let the traverser visit the children for us.
1276 makeFunctions(node->getAsAggregate()->getSequence());
1277
1278 // Also, we want all globals initializers to go into the entry of main(), before
1279 // anything else gets there, so visit out of order, doing them all now.
1280 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1281
1282 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1283 // so do them manually.
1284 visitFunctions(node->getAsAggregate()->getSequence());
1285
1286 return false;
1287 }
1288
1289 return true;
1290 }
1291 case glslang::EOpLinkerObjects:
1292 {
1293 if (visit == glslang::EvPreVisit)
1294 linkageOnly = true;
1295 else
1296 linkageOnly = false;
1297
1298 return true;
1299 }
1300 case glslang::EOpComma:
1301 {
1302 // processing from left to right naturally leaves the right-most
1303 // lying around in the access chain
1304 glslang::TIntermSequence& glslangOperands = node->getSequence();
1305 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1306 glslangOperands[i]->traverse(this);
1307
1308 return false;
1309 }
1310 case glslang::EOpFunction:
1311 if (visit == glslang::EvPreVisit) {
1312 if (isShaderEntrypoint(node)) {
1313 inMain = true;
1314 builder.setBuildPoint(shaderEntry->getLastBlock());
1315 } else {
1316 handleFunctionEntry(node);
1317 }
1318 } else {
1319 if (inMain)
1320 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001321 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001322 inMain = false;
1323 }
1324
1325 return true;
1326 case glslang::EOpParameters:
1327 // Parameters will have been consumed by EOpFunction processing, but not
1328 // the body, so we still visited the function node's children, making this
1329 // child redundant.
1330 return false;
1331 case glslang::EOpFunctionCall:
1332 {
1333 if (node->isUserDefined())
1334 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001335 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1336 if (result) {
1337 builder.clearAccessChain();
1338 builder.setAccessChainRValue(result);
1339 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001340 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001341
1342 return false;
1343 }
1344 case glslang::EOpConstructMat2x2:
1345 case glslang::EOpConstructMat2x3:
1346 case glslang::EOpConstructMat2x4:
1347 case glslang::EOpConstructMat3x2:
1348 case glslang::EOpConstructMat3x3:
1349 case glslang::EOpConstructMat3x4:
1350 case glslang::EOpConstructMat4x2:
1351 case glslang::EOpConstructMat4x3:
1352 case glslang::EOpConstructMat4x4:
1353 case glslang::EOpConstructDMat2x2:
1354 case glslang::EOpConstructDMat2x3:
1355 case glslang::EOpConstructDMat2x4:
1356 case glslang::EOpConstructDMat3x2:
1357 case glslang::EOpConstructDMat3x3:
1358 case glslang::EOpConstructDMat3x4:
1359 case glslang::EOpConstructDMat4x2:
1360 case glslang::EOpConstructDMat4x3:
1361 case glslang::EOpConstructDMat4x4:
1362 isMatrix = true;
1363 // fall through
1364 case glslang::EOpConstructFloat:
1365 case glslang::EOpConstructVec2:
1366 case glslang::EOpConstructVec3:
1367 case glslang::EOpConstructVec4:
1368 case glslang::EOpConstructDouble:
1369 case glslang::EOpConstructDVec2:
1370 case glslang::EOpConstructDVec3:
1371 case glslang::EOpConstructDVec4:
1372 case glslang::EOpConstructBool:
1373 case glslang::EOpConstructBVec2:
1374 case glslang::EOpConstructBVec3:
1375 case glslang::EOpConstructBVec4:
1376 case glslang::EOpConstructInt:
1377 case glslang::EOpConstructIVec2:
1378 case glslang::EOpConstructIVec3:
1379 case glslang::EOpConstructIVec4:
1380 case glslang::EOpConstructUint:
1381 case glslang::EOpConstructUVec2:
1382 case glslang::EOpConstructUVec3:
1383 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001384 case glslang::EOpConstructInt64:
1385 case glslang::EOpConstructI64Vec2:
1386 case glslang::EOpConstructI64Vec3:
1387 case glslang::EOpConstructI64Vec4:
1388 case glslang::EOpConstructUint64:
1389 case glslang::EOpConstructU64Vec2:
1390 case glslang::EOpConstructU64Vec3:
1391 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001392 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001393 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001394 {
1395 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001396 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001397 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001398 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001399 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001400 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001401 std::vector<spv::Id> constituents;
1402 for (int c = 0; c < (int)arguments.size(); ++c)
1403 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001404 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001405 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001406 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001407 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001408 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001409
1410 builder.clearAccessChain();
1411 builder.setAccessChainRValue(constructed);
1412
1413 return false;
1414 }
1415
1416 // These six are component-wise compares with component-wise results.
1417 // Forward on to createBinaryOperation(), requesting a vector result.
1418 case glslang::EOpLessThan:
1419 case glslang::EOpGreaterThan:
1420 case glslang::EOpLessThanEqual:
1421 case glslang::EOpGreaterThanEqual:
1422 case glslang::EOpVectorEqual:
1423 case glslang::EOpVectorNotEqual:
1424 {
1425 // Map the operation to a binary
1426 binOp = node->getOp();
1427 reduceComparison = false;
1428 switch (node->getOp()) {
1429 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1430 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1431 default: binOp = node->getOp(); break;
1432 }
1433
1434 break;
1435 }
1436 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001437 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001438 binOp = glslang::EOpMul;
1439 break;
1440 case glslang::EOpOuterProduct:
1441 // two vectors multiplied to make a matrix
1442 binOp = glslang::EOpOuterProduct;
1443 break;
1444 case glslang::EOpDot:
1445 {
qining25262b32016-05-06 17:25:16 -04001446 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001447 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001448 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001449 binOp = glslang::EOpMul;
1450 break;
1451 }
1452 case glslang::EOpMod:
1453 // when an aggregate, this is the floating-point mod built-in function,
1454 // which can be emitted by the one in createBinaryOperation()
1455 binOp = glslang::EOpMod;
1456 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001457 case glslang::EOpEmitVertex:
1458 case glslang::EOpEndPrimitive:
1459 case glslang::EOpBarrier:
1460 case glslang::EOpMemoryBarrier:
1461 case glslang::EOpMemoryBarrierAtomicCounter:
1462 case glslang::EOpMemoryBarrierBuffer:
1463 case glslang::EOpMemoryBarrierImage:
1464 case glslang::EOpMemoryBarrierShared:
1465 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001466 case glslang::EOpAllMemoryBarrierWithGroupSync:
1467 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1468 case glslang::EOpWorkgroupMemoryBarrier:
1469 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001470 noReturnValue = true;
1471 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1472 break;
1473
John Kessenich426394d2015-07-23 10:22:48 -06001474 case glslang::EOpAtomicAdd:
1475 case glslang::EOpAtomicMin:
1476 case glslang::EOpAtomicMax:
1477 case glslang::EOpAtomicAnd:
1478 case glslang::EOpAtomicOr:
1479 case glslang::EOpAtomicXor:
1480 case glslang::EOpAtomicExchange:
1481 case glslang::EOpAtomicCompSwap:
1482 atomic = true;
1483 break;
1484
John Kessenich140f3df2015-06-26 16:58:36 -06001485 default:
1486 break;
1487 }
1488
1489 //
1490 // See if it maps to a regular operation.
1491 //
John Kessenich140f3df2015-06-26 16:58:36 -06001492 if (binOp != glslang::EOpNull) {
1493 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1494 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1495 assert(left && right);
1496
1497 builder.clearAccessChain();
1498 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001499 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001500
1501 builder.clearAccessChain();
1502 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001503 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001504
qining25262b32016-05-06 17:25:16 -04001505 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001506 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001507 left->getType().getBasicType(), reduceComparison);
1508
1509 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001510 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001511 builder.clearAccessChain();
1512 builder.setAccessChainRValue(result);
1513
1514 return false;
1515 }
1516
John Kessenich426394d2015-07-23 10:22:48 -06001517 //
1518 // Create the list of operands.
1519 //
John Kessenich140f3df2015-06-26 16:58:36 -06001520 glslang::TIntermSequence& glslangOperands = node->getSequence();
1521 std::vector<spv::Id> operands;
1522 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001523 // special case l-value operands; there are just a few
1524 bool lvalue = false;
1525 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001526 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001527 case glslang::EOpModf:
1528 if (arg == 1)
1529 lvalue = true;
1530 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001531 case glslang::EOpInterpolateAtSample:
1532 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001533#ifdef AMD_EXTENSIONS
1534 case glslang::EOpInterpolateAtVertex:
1535#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001536 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001537 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001538
1539 // Does it need a swizzle inversion? If so, evaluation is inverted;
1540 // operate first on the swizzle base, then apply the swizzle.
1541 if (glslangOperands[0]->getAsOperator() &&
1542 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1543 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1544 }
Rex Xu7a26c172015-12-08 17:12:09 +08001545 break;
Rex Xud4782c12015-09-06 16:30:11 +08001546 case glslang::EOpAtomicAdd:
1547 case glslang::EOpAtomicMin:
1548 case glslang::EOpAtomicMax:
1549 case glslang::EOpAtomicAnd:
1550 case glslang::EOpAtomicOr:
1551 case glslang::EOpAtomicXor:
1552 case glslang::EOpAtomicExchange:
1553 case glslang::EOpAtomicCompSwap:
1554 if (arg == 0)
1555 lvalue = true;
1556 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001557 case glslang::EOpAddCarry:
1558 case glslang::EOpSubBorrow:
1559 if (arg == 2)
1560 lvalue = true;
1561 break;
1562 case glslang::EOpUMulExtended:
1563 case glslang::EOpIMulExtended:
1564 if (arg >= 2)
1565 lvalue = true;
1566 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001567 default:
1568 break;
1569 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001570 builder.clearAccessChain();
1571 if (invertedType != spv::NoType && arg == 0)
1572 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1573 else
1574 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001575 if (lvalue)
1576 operands.push_back(builder.accessChainGetLValue());
1577 else
John Kessenich32cfd492016-02-02 12:37:46 -07001578 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001579 }
John Kessenich426394d2015-07-23 10:22:48 -06001580
1581 if (atomic) {
1582 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001583 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001584 } else {
1585 // Pass through to generic operations.
1586 switch (glslangOperands.size()) {
1587 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001588 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001589 break;
1590 case 1:
qining25262b32016-05-06 17:25:16 -04001591 result = createUnaryOperation(
1592 node->getOp(), precision,
1593 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001594 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001595 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001596 break;
1597 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001598 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001599 break;
1600 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001601 if (invertedType)
1602 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001603 }
1604
1605 if (noReturnValue)
1606 return false;
1607
1608 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001609 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001610 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001611 } else {
1612 builder.clearAccessChain();
1613 builder.setAccessChainRValue(result);
1614 return false;
1615 }
1616}
1617
1618bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1619{
1620 // This path handles both if-then-else and ?:
1621 // The if-then-else has a node type of void, while
1622 // ?: has a non-void node type
1623 spv::Id result = 0;
1624 if (node->getBasicType() != glslang::EbtVoid) {
1625 // don't handle this as just on-the-fly temporaries, because there will be two names
1626 // and better to leave SSA to later passes
1627 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1628 }
1629
1630 // emit the condition before doing anything with selection
1631 node->getCondition()->traverse(this);
1632
1633 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001634 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001635
1636 if (node->getTrueBlock()) {
1637 // emit the "then" statement
1638 node->getTrueBlock()->traverse(this);
1639 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001640 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001641 }
1642
1643 if (node->getFalseBlock()) {
1644 ifBuilder.makeBeginElse();
1645 // emit the "else" statement
1646 node->getFalseBlock()->traverse(this);
1647 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001648 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001649 }
1650
1651 ifBuilder.makeEndIf();
1652
1653 if (result) {
1654 // GLSL only has r-values as the result of a :?, but
1655 // if we have an l-value, that can be more efficient if it will
1656 // become the base of a complex r-value expression, because the
1657 // next layer copies r-values into memory to use the access-chain mechanism
1658 builder.clearAccessChain();
1659 builder.setAccessChainLValue(result);
1660 }
1661
1662 return false;
1663}
1664
1665bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1666{
1667 // emit and get the condition before doing anything with switch
1668 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001669 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001670
1671 // browse the children to sort out code segments
1672 int defaultSegment = -1;
1673 std::vector<TIntermNode*> codeSegments;
1674 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1675 std::vector<int> caseValues;
1676 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1677 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1678 TIntermNode* child = *c;
1679 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001680 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001681 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001682 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001683 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1684 } else
1685 codeSegments.push_back(child);
1686 }
1687
qining25262b32016-05-06 17:25:16 -04001688 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001689 // statements between the last case and the end of the switch statement
1690 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1691 (int)codeSegments.size() == defaultSegment)
1692 codeSegments.push_back(nullptr);
1693
1694 // make the switch statement
1695 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001696 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001697
1698 // emit all the code in the segments
1699 breakForLoop.push(false);
1700 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1701 builder.nextSwitchSegment(segmentBlocks, s);
1702 if (codeSegments[s])
1703 codeSegments[s]->traverse(this);
1704 else
1705 builder.addSwitchBreak();
1706 }
1707 breakForLoop.pop();
1708
1709 builder.endSwitch(segmentBlocks);
1710
1711 return false;
1712}
1713
1714void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1715{
1716 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001717 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001718
1719 builder.clearAccessChain();
1720 builder.setAccessChainRValue(constant);
1721}
1722
1723bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1724{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001725 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001726 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001727 // Spec requires back edges to target header blocks, and every header block
1728 // must dominate its merge block. Make a header block first to ensure these
1729 // conditions are met. By definition, it will contain OpLoopMerge, followed
1730 // by a block-ending branch. But we don't want to put any other body/test
1731 // instructions in it, since the body/test may have arbitrary instructions,
1732 // including merges of its own.
1733 builder.setBuildPoint(&blocks.head);
1734 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001735 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001736 spv::Block& test = builder.makeNewBlock();
1737 builder.createBranch(&test);
1738
1739 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001740 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001741 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001742 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001743 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1744
1745 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001746 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001747 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001748 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001749 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001750 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001751
1752 builder.setBuildPoint(&blocks.continue_target);
1753 if (node->getTerminal())
1754 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001755 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001756 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001757 builder.createBranch(&blocks.body);
1758
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001759 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001760 builder.setBuildPoint(&blocks.body);
1761 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001762 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001763 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001764 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001765
1766 builder.setBuildPoint(&blocks.continue_target);
1767 if (node->getTerminal())
1768 node->getTerminal()->traverse(this);
1769 if (node->getTest()) {
1770 node->getTest()->traverse(this);
1771 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001772 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001773 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001774 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001775 // TODO: unless there was a break/return/discard instruction
1776 // somewhere in the body, this is an infinite loop, so we should
1777 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001778 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001779 }
John Kessenich140f3df2015-06-26 16:58:36 -06001780 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001781 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001782 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001783 return false;
1784}
1785
1786bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1787{
1788 if (node->getExpression())
1789 node->getExpression()->traverse(this);
1790
1791 switch (node->getFlowOp()) {
1792 case glslang::EOpKill:
1793 builder.makeDiscard();
1794 break;
1795 case glslang::EOpBreak:
1796 if (breakForLoop.top())
1797 builder.createLoopExit();
1798 else
1799 builder.addSwitchBreak();
1800 break;
1801 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001802 builder.createLoopContinue();
1803 break;
1804 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001805 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001806 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001807 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001808 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001809
1810 builder.clearAccessChain();
1811 break;
1812
1813 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001814 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001815 break;
1816 }
1817
1818 return false;
1819}
1820
1821spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1822{
qining25262b32016-05-06 17:25:16 -04001823 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001824 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001825 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001826 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001827 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001828 }
1829
1830 // Now, handle actual variables
1831 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1832 spv::Id spvType = convertGlslangToSpvType(node->getType());
1833
1834 const char* name = node->getName().c_str();
1835 if (glslang::IsAnonymous(name))
1836 name = "";
1837
1838 return builder.createVariable(storageClass, spvType, name);
1839}
1840
1841// Return type Id of the sampled type.
1842spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1843{
1844 switch (sampler.type) {
1845 case glslang::EbtFloat: return builder.makeFloatType(32);
1846 case glslang::EbtInt: return builder.makeIntType(32);
1847 case glslang::EbtUint: return builder.makeUintType(32);
1848 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001849 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001850 return builder.makeFloatType(32);
1851 }
1852}
1853
John Kessenich8c8505c2016-07-26 12:50:38 -06001854// If node is a swizzle operation, return the type that should be used if
1855// the swizzle base is first consumed by another operation, before the swizzle
1856// is applied.
1857spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1858{
1859 if (node.getAsOperator() &&
1860 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1861 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1862 else
1863 return spv::NoType;
1864}
1865
1866// When inverting a swizzle with a parent op, this function
1867// will apply the swizzle operation to a completed parent operation.
1868spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1869{
1870 std::vector<unsigned> swizzle;
1871 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1872 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1873}
1874
1875
1876// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1877void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1878{
1879 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1880 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1881 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1882}
1883
John Kessenich3ac051e2015-12-20 11:29:16 -07001884// Convert from a glslang type to an SPV type, by calling into a
1885// recursive version of this function. This establishes the inherited
1886// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001887spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1888{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001889 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001890}
1891
1892// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001893// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001894// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001895spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001896{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001897 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001898
1899 switch (type.getBasicType()) {
1900 case glslang::EbtVoid:
1901 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001902 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001903 break;
1904 case glslang::EbtFloat:
1905 spvType = builder.makeFloatType(32);
1906 break;
1907 case glslang::EbtDouble:
1908 spvType = builder.makeFloatType(64);
1909 break;
1910 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001911 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1912 // a 32-bit int where non-0 means true.
1913 if (explicitLayout != glslang::ElpNone)
1914 spvType = builder.makeUintType(32);
1915 else
1916 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001917 break;
1918 case glslang::EbtInt:
1919 spvType = builder.makeIntType(32);
1920 break;
1921 case glslang::EbtUint:
1922 spvType = builder.makeUintType(32);
1923 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001924 case glslang::EbtInt64:
1925 builder.addCapability(spv::CapabilityInt64);
1926 spvType = builder.makeIntType(64);
1927 break;
1928 case glslang::EbtUint64:
1929 builder.addCapability(spv::CapabilityInt64);
1930 spvType = builder.makeUintType(64);
1931 break;
John Kessenich426394d2015-07-23 10:22:48 -06001932 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001933 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001934 spvType = builder.makeUintType(32);
1935 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001936 case glslang::EbtSampler:
1937 {
1938 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001939 if (sampler.sampler) {
1940 // pure sampler
1941 spvType = builder.makeSamplerType();
1942 } else {
1943 // an image is present, make its type
1944 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1945 sampler.image ? 2 : 1, TranslateImageFormat(type));
1946 if (sampler.combined) {
1947 // already has both image and sampler, make the combined type
1948 spvType = builder.makeSampledImageType(spvType);
1949 }
John Kessenich55e7d112015-11-15 21:33:39 -07001950 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001951 }
John Kessenich140f3df2015-06-26 16:58:36 -06001952 break;
1953 case glslang::EbtStruct:
1954 case glslang::EbtBlock:
1955 {
1956 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001957 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001958
1959 // Try to share structs for different layouts, but not yet for other
1960 // kinds of qualification (primarily not yet including interpolant qualification).
1961 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001962 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001963 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001964 break;
1965
1966 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001967 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001968 memberRemapper[glslangMembers].resize(glslangMembers->size());
1969 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001970 }
1971 break;
1972 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001973 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001974 break;
1975 }
1976
1977 if (type.isMatrix())
1978 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1979 else {
1980 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1981 if (type.getVectorSize() > 1)
1982 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1983 }
1984
1985 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001986 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1987
John Kessenichc9a80832015-09-12 12:17:44 -06001988 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001989 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001990 // We need to decorate array strides for types needing explicit layout, except blocks.
1991 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001992 // Use a dummy glslang type for querying internal strides of
1993 // arrays of arrays, but using just a one-dimensional array.
1994 glslang::TType simpleArrayType(type, 0); // deference type of the array
1995 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1996 simpleArrayType.getArraySizes().dereference();
1997
1998 // Will compute the higher-order strides here, rather than making a whole
1999 // pile of types and doing repetitive recursion on their contents.
2000 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2001 }
John Kessenichf8842e52016-01-04 19:22:56 -07002002
2003 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002004 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002005 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002006 if (stride > 0)
2007 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002008 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002009 }
2010 } else {
2011 // single-dimensional array, and don't yet have stride
2012
John Kessenichf8842e52016-01-04 19:22:56 -07002013 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002014 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2015 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002016 }
John Kessenich31ed4832015-09-09 17:51:38 -06002017
John Kessenichc9a80832015-09-12 12:17:44 -06002018 // Do the outer dimension, which might not be known for a runtime-sized array
2019 if (type.isRuntimeSizedArray()) {
2020 spvType = builder.makeRuntimeArray(spvType);
2021 } else {
2022 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002023 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002024 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002025 if (stride > 0)
2026 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002027 }
2028
2029 return spvType;
2030}
2031
John Kessenich6090df02016-06-30 21:18:02 -06002032
2033// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2034// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2035// Mutually recursive with convertGlslangToSpvType().
2036spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2037 const glslang::TTypeList* glslangMembers,
2038 glslang::TLayoutPacking explicitLayout,
2039 const glslang::TQualifier& qualifier)
2040{
2041 // Create a vector of struct types for SPIR-V to consume
2042 std::vector<spv::Id> spvMembers;
2043 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2044 int locationOffset = 0; // for use across struct members, when they are called recursively
2045 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2046 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2047 if (glslangMember.hiddenMember()) {
2048 ++memberDelta;
2049 if (type.getBasicType() == glslang::EbtBlock)
2050 memberRemapper[glslangMembers][i] = -1;
2051 } else {
2052 if (type.getBasicType() == glslang::EbtBlock)
2053 memberRemapper[glslangMembers][i] = i - memberDelta;
2054 // modify just this child's view of the qualifier
2055 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2056 InheritQualifiers(memberQualifier, qualifier);
2057
2058 // manually inherit location; it's more complex
2059 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2060 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2061 if (qualifier.hasLocation())
2062 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2063
2064 // recurse
2065 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2066 }
2067 }
2068
2069 // Make the SPIR-V type
2070 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
2071 if (! HasNonLayoutQualifiers(qualifier))
2072 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2073
2074 // Decorate it
2075 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2076
2077 return spvType;
2078}
2079
2080void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2081 const glslang::TTypeList* glslangMembers,
2082 glslang::TLayoutPacking explicitLayout,
2083 const glslang::TQualifier& qualifier,
2084 spv::Id spvType)
2085{
2086 // Name and decorate the non-hidden members
2087 int offset = -1;
2088 int locationOffset = 0; // for use within the members of this struct
2089 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2090 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2091 int member = i;
2092 if (type.getBasicType() == glslang::EbtBlock)
2093 member = memberRemapper[glslangMembers][i];
2094
2095 // modify just this child's view of the qualifier
2096 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2097 InheritQualifiers(memberQualifier, qualifier);
2098
2099 // using -1 above to indicate a hidden member
2100 if (member >= 0) {
2101 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2102 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2103 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2104 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2105 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2106 if (type.getBasicType() == glslang::EbtBlock) {
2107 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2108 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2109 }
2110 }
2111 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2112
2113 if (qualifier.storage == glslang::EvqBuffer) {
2114 std::vector<spv::Decoration> memory;
2115 TranslateMemoryDecoration(memberQualifier, memory);
2116 for (unsigned int i = 0; i < memory.size(); ++i)
2117 addMemberDecoration(spvType, member, memory[i]);
2118 }
2119
John Kessenich2f47bc92016-06-30 21:47:35 -06002120 // Compute location decoration; tricky based on whether inheritance is at play and
2121 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002122 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2123 // probably move to the linker stage of the front end proper, and just have the
2124 // answer sitting already distributed throughout the individual member locations.
2125 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002126 // Ignore member locations if the container is an array, as that's
2127 // ill-specified and decisions have been made to not allow this anyway.
2128 // The object itself must have a location, and that comes out from decorating the object,
2129 // not the type (this code decorates types).
2130 if (! type.isArray()) {
2131 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2132 // struct members should not have explicit locations
2133 assert(type.getBasicType() != glslang::EbtStruct);
2134 location = memberQualifier.layoutLocation;
2135 } else if (type.getBasicType() != glslang::EbtBlock) {
2136 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2137 // The members, and their nested types, must not themselves have Location decorations.
2138 } else if (qualifier.hasLocation()) // inheritance
2139 location = qualifier.layoutLocation + locationOffset;
2140 }
John Kessenich6090df02016-06-30 21:18:02 -06002141 if (location >= 0)
2142 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2143
John Kessenich2f47bc92016-06-30 21:47:35 -06002144 if (qualifier.hasLocation()) // track for upcoming inheritance
2145 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2146
John Kessenich6090df02016-06-30 21:18:02 -06002147 // component, XFB, others
2148 if (glslangMember.getQualifier().hasComponent())
2149 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2150 if (glslangMember.getQualifier().hasXfbOffset())
2151 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2152 else if (explicitLayout != glslang::ElpNone) {
2153 // figure out what to do with offset, which is accumulating
2154 int nextOffset;
2155 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2156 if (offset >= 0)
2157 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2158 offset = nextOffset;
2159 }
2160
2161 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2162 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2163
2164 // built-in variable decorations
2165 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002166 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002167 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2168 }
2169 }
2170
2171 // Decorate the structure
2172 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2173 addDecoration(spvType, TranslateBlockDecoration(type));
2174 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2175 builder.addCapability(spv::CapabilityGeometryStreams);
2176 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2177 }
2178 if (glslangIntermediate->getXfbMode()) {
2179 builder.addCapability(spv::CapabilityTransformFeedback);
2180 if (type.getQualifier().hasXfbStride())
2181 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2182 if (type.getQualifier().hasXfbBuffer())
2183 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2184 }
2185}
2186
John Kessenich6c292d32016-02-15 20:58:50 -07002187// Turn the expression forming the array size into an id.
2188// This is not quite trivial, because of specialization constants.
2189// Sometimes, a raw constant is turned into an Id, and sometimes
2190// a specialization constant expression is.
2191spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2192{
2193 // First, see if this is sized with a node, meaning a specialization constant:
2194 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2195 if (specNode != nullptr) {
2196 builder.clearAccessChain();
2197 specNode->traverse(this);
2198 return accessChainLoad(specNode->getAsTyped()->getType());
2199 }
qining25262b32016-05-06 17:25:16 -04002200
John Kessenich6c292d32016-02-15 20:58:50 -07002201 // Otherwise, need a compile-time (front end) size, get it:
2202 int size = arraySizes.getDimSize(dim);
2203 assert(size > 0);
2204 return builder.makeUintConstant(size);
2205}
2206
John Kessenich103bef92016-02-08 21:38:15 -07002207// Wrap the builder's accessChainLoad to:
2208// - localize handling of RelaxedPrecision
2209// - use the SPIR-V inferred type instead of another conversion of the glslang type
2210// (avoids unnecessary work and possible type punning for structures)
2211// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002212spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2213{
John Kessenich103bef92016-02-08 21:38:15 -07002214 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2215 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2216
2217 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002218 if (type.getBasicType() == glslang::EbtBool) {
2219 if (builder.isScalarType(nominalTypeId)) {
2220 // Conversion for bool
2221 spv::Id boolType = builder.makeBoolType();
2222 if (nominalTypeId != boolType)
2223 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2224 } else if (builder.isVectorType(nominalTypeId)) {
2225 // Conversion for bvec
2226 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2227 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2228 if (nominalTypeId != bvecType)
2229 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2230 }
2231 }
John Kessenich103bef92016-02-08 21:38:15 -07002232
2233 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002234}
2235
Rex Xu27253232016-02-23 17:51:09 +08002236// Wrap the builder's accessChainStore to:
2237// - do conversion of concrete to abstract type
2238void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2239{
2240 // Need to convert to abstract types when necessary
2241 if (type.getBasicType() == glslang::EbtBool) {
2242 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2243
2244 if (builder.isScalarType(nominalTypeId)) {
2245 // Conversion for bool
2246 spv::Id boolType = builder.makeBoolType();
2247 if (nominalTypeId != boolType) {
2248 spv::Id zero = builder.makeUintConstant(0);
2249 spv::Id one = builder.makeUintConstant(1);
2250 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2251 }
2252 } else if (builder.isVectorType(nominalTypeId)) {
2253 // Conversion for bvec
2254 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2255 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2256 if (nominalTypeId != bvecType) {
2257 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2258 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2259 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2260 }
2261 }
2262 }
2263
2264 builder.accessChainStore(rvalue);
2265}
2266
John Kessenichf85e8062015-12-19 13:57:10 -07002267// Decide whether or not this type should be
2268// decorated with offsets and strides, and if so
2269// whether std140 or std430 rules should be applied.
2270glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002271{
John Kessenichf85e8062015-12-19 13:57:10 -07002272 // has to be a block
2273 if (type.getBasicType() != glslang::EbtBlock)
2274 return glslang::ElpNone;
2275
2276 // has to be a uniform or buffer block
2277 if (type.getQualifier().storage != glslang::EvqUniform &&
2278 type.getQualifier().storage != glslang::EvqBuffer)
2279 return glslang::ElpNone;
2280
2281 // return the layout to use
2282 switch (type.getQualifier().layoutPacking) {
2283 case glslang::ElpStd140:
2284 case glslang::ElpStd430:
2285 return type.getQualifier().layoutPacking;
2286 default:
2287 return glslang::ElpNone;
2288 }
John Kessenich31ed4832015-09-09 17:51:38 -06002289}
2290
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002291// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002292int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002293{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002294 int size;
John Kessenich49987892015-12-29 17:11:44 -07002295 int stride;
2296 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002297
2298 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002299}
2300
John Kessenich49987892015-12-29 17:11:44 -07002301// 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 -07002302// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002303int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002304{
John Kessenich49987892015-12-29 17:11:44 -07002305 glslang::TType elementType;
2306 elementType.shallowCopy(matrixType);
2307 elementType.clearArraySizes();
2308
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002309 int size;
John Kessenich49987892015-12-29 17:11:44 -07002310 int stride;
2311 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2312
2313 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002314}
2315
John Kessenich5e4b1242015-08-06 22:53:06 -06002316// Given a member type of a struct, realign the current offset for it, and compute
2317// the next (not yet aligned) offset for the next member, which will get aligned
2318// on the next call.
2319// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2320// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2321// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002322void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002323 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002324{
2325 // this will get a positive value when deemed necessary
2326 nextOffset = -1;
2327
John Kessenich5e4b1242015-08-06 22:53:06 -06002328 // override anything in currentOffset with user-set offset
2329 if (memberType.getQualifier().hasOffset())
2330 currentOffset = memberType.getQualifier().layoutOffset;
2331
2332 // It could be that current linker usage in glslang updated all the layoutOffset,
2333 // in which case the following code does not matter. But, that's not quite right
2334 // once cross-compilation unit GLSL validation is done, as the original user
2335 // settings are needed in layoutOffset, and then the following will come into play.
2336
John Kessenichf85e8062015-12-19 13:57:10 -07002337 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002338 if (! memberType.getQualifier().hasOffset())
2339 currentOffset = -1;
2340
2341 return;
2342 }
2343
John Kessenichf85e8062015-12-19 13:57:10 -07002344 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002345 if (currentOffset < 0)
2346 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002347
John Kessenich5e4b1242015-08-06 22:53:06 -06002348 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2349 // but possibly not yet correctly aligned.
2350
2351 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002352 int dummyStride;
2353 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002354 glslang::RoundToPow2(currentOffset, memberAlignment);
2355 nextOffset = currentOffset + memberSize;
2356}
2357
David Netoa901ffe2016-06-08 14:11:40 +01002358void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002359{
David Netoa901ffe2016-06-08 14:11:40 +01002360 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2361 switch (glslangBuiltIn)
2362 {
2363 case glslang::EbvClipDistance:
2364 case glslang::EbvCullDistance:
2365 case glslang::EbvPointSize:
2366 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2367 // Alternately, we could just call this for any glslang built-in, since the
2368 // capability already guards against duplicates.
2369 TranslateBuiltInDecoration(glslangBuiltIn, false);
2370 break;
2371 default:
2372 // Capabilities were already generated when the struct was declared.
2373 break;
2374 }
John Kessenichebb50532016-05-16 19:22:05 -06002375}
2376
John Kessenich140f3df2015-06-26 16:58:36 -06002377bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2378{
John Kessenich4d65ee32016-03-12 18:17:47 -07002379 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002380 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002381 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002382}
2383
2384// Make all the functions, skeletally, without actually visiting their bodies.
2385void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2386{
2387 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2388 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2389 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2390 continue;
2391
2392 // We're on a user function. Set up the basic interface for the function now,
2393 // so that it's available to call.
2394 // Translating the body will happen later.
2395 //
qining25262b32016-05-06 17:25:16 -04002396 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002397 // function. What it is an address of varies:
2398 //
2399 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2400 // so that write needs to be to a copy, hence the address of a copy works.
2401 //
2402 // - "const in" parameters can just be the r-value, as no writes need occur.
2403 //
2404 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2405 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2406
2407 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002408 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002409 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2410
2411 for (int p = 0; p < (int)parameters.size(); ++p) {
2412 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2413 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002414 if (paramType.isOpaque())
2415 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2416 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002417 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2418 else
2419 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002420 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002421 paramTypes.push_back(typeId);
2422 }
2423
2424 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002425 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2426 convertGlslangToSpvType(glslFunction->getType()),
2427 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002428
2429 // Track function to emit/call later
2430 functionMap[glslFunction->getName().c_str()] = function;
2431
2432 // Set the parameter id's
2433 for (int p = 0; p < (int)parameters.size(); ++p) {
2434 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2435 // give a name too
2436 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2437 }
2438 }
2439}
2440
2441// Process all the initializers, while skipping the functions and link objects
2442void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2443{
2444 builder.setBuildPoint(shaderEntry->getLastBlock());
2445 for (int i = 0; i < (int)initializers.size(); ++i) {
2446 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2447 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2448
2449 // We're on a top-level node that's not a function. Treat as an initializer, whose
2450 // code goes into the beginning of main.
2451 initializer->traverse(this);
2452 }
2453 }
2454}
2455
2456// Process all the functions, while skipping initializers.
2457void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2458{
2459 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2460 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2461 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2462 node->traverse(this);
2463 }
2464}
2465
2466void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2467{
qining25262b32016-05-06 17:25:16 -04002468 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002469 // that called makeFunctions().
2470 spv::Function* function = functionMap[node->getName().c_str()];
2471 spv::Block* functionBlock = function->getEntryBlock();
2472 builder.setBuildPoint(functionBlock);
2473}
2474
Rex Xu04db3f52015-09-16 11:44:02 +08002475void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002476{
Rex Xufc618912015-09-09 16:42:49 +08002477 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002478
2479 glslang::TSampler sampler = {};
2480 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002481 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002482 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2483 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2484 }
2485
John Kessenich140f3df2015-06-26 16:58:36 -06002486 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2487 builder.clearAccessChain();
2488 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002489
2490 // Special case l-value operands
2491 bool lvalue = false;
2492 switch (node.getOp()) {
2493 case glslang::EOpImageAtomicAdd:
2494 case glslang::EOpImageAtomicMin:
2495 case glslang::EOpImageAtomicMax:
2496 case glslang::EOpImageAtomicAnd:
2497 case glslang::EOpImageAtomicOr:
2498 case glslang::EOpImageAtomicXor:
2499 case glslang::EOpImageAtomicExchange:
2500 case glslang::EOpImageAtomicCompSwap:
2501 if (i == 0)
2502 lvalue = true;
2503 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002504 case glslang::EOpSparseImageLoad:
2505 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2506 lvalue = true;
2507 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002508 case glslang::EOpSparseTexture:
2509 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2510 lvalue = true;
2511 break;
2512 case glslang::EOpSparseTextureClamp:
2513 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2514 lvalue = true;
2515 break;
2516 case glslang::EOpSparseTextureLod:
2517 case glslang::EOpSparseTextureOffset:
2518 if (i == 3)
2519 lvalue = true;
2520 break;
2521 case glslang::EOpSparseTextureFetch:
2522 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2523 lvalue = true;
2524 break;
2525 case glslang::EOpSparseTextureFetchOffset:
2526 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2527 lvalue = true;
2528 break;
2529 case glslang::EOpSparseTextureLodOffset:
2530 case glslang::EOpSparseTextureGrad:
2531 case glslang::EOpSparseTextureOffsetClamp:
2532 if (i == 4)
2533 lvalue = true;
2534 break;
2535 case glslang::EOpSparseTextureGradOffset:
2536 case glslang::EOpSparseTextureGradClamp:
2537 if (i == 5)
2538 lvalue = true;
2539 break;
2540 case glslang::EOpSparseTextureGradOffsetClamp:
2541 if (i == 6)
2542 lvalue = true;
2543 break;
2544 case glslang::EOpSparseTextureGather:
2545 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2546 lvalue = true;
2547 break;
2548 case glslang::EOpSparseTextureGatherOffset:
2549 case glslang::EOpSparseTextureGatherOffsets:
2550 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2551 lvalue = true;
2552 break;
Rex Xufc618912015-09-09 16:42:49 +08002553 default:
2554 break;
2555 }
2556
Rex Xu6b86d492015-09-16 17:48:22 +08002557 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002558 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002559 else
John Kessenich32cfd492016-02-02 12:37:46 -07002560 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002561 }
2562}
2563
John Kessenichfc51d282015-08-19 13:34:18 -06002564void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002565{
John Kessenichfc51d282015-08-19 13:34:18 -06002566 builder.clearAccessChain();
2567 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002568 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002569}
John Kessenich140f3df2015-06-26 16:58:36 -06002570
John Kessenichfc51d282015-08-19 13:34:18 -06002571spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2572{
Rex Xufc618912015-09-09 16:42:49 +08002573 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002574 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002575 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002576 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002577
John Kessenichfc51d282015-08-19 13:34:18 -06002578 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002579 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2580 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2581 std::vector<spv::Id> arguments;
2582 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002583 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002584 else
2585 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002586 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002587
2588 spv::Builder::TextureParameters params = { };
2589 params.sampler = arguments[0];
2590
Rex Xu04db3f52015-09-16 11:44:02 +08002591 glslang::TCrackedTextureOp cracked;
2592 node->crackTexture(sampler, cracked);
2593
John Kessenichfc51d282015-08-19 13:34:18 -06002594 // Check for queries
2595 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002596 // a sampled image needs to have the image extracted first
2597 if (builder.isSampledImage(params.sampler))
2598 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002599 switch (node->getOp()) {
2600 case glslang::EOpImageQuerySize:
2601 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002602 if (arguments.size() > 1) {
2603 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002604 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002605 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002606 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002607 case glslang::EOpImageQuerySamples:
2608 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002609 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002610 case glslang::EOpTextureQueryLod:
2611 params.coords = arguments[1];
2612 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2613 case glslang::EOpTextureQueryLevels:
2614 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002615 case glslang::EOpSparseTexelsResident:
2616 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002617 default:
2618 assert(0);
2619 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002620 }
John Kessenich140f3df2015-06-26 16:58:36 -06002621 }
2622
Rex Xufc618912015-09-09 16:42:49 +08002623 // Check for image functions other than queries
2624 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002625 std::vector<spv::Id> operands;
2626 auto opIt = arguments.begin();
2627 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002628
2629 // Handle subpass operations
2630 // TODO: GLSL should change to have the "MS" only on the type rather than the
2631 // built-in function.
2632 if (cracked.subpass) {
2633 // add on the (0,0) coordinate
2634 spv::Id zero = builder.makeIntConstant(0);
2635 std::vector<spv::Id> comps;
2636 comps.push_back(zero);
2637 comps.push_back(zero);
2638 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2639 if (sampler.ms) {
2640 operands.push_back(spv::ImageOperandsSampleMask);
2641 operands.push_back(*(opIt++));
2642 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002643 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002644 }
2645
John Kessenich56bab042015-09-16 10:54:31 -06002646 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002647 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002648 if (sampler.ms) {
2649 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002650 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002651 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002652 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2653 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002654 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002655 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002656 if (sampler.ms) {
2657 operands.push_back(*(opIt + 1));
2658 operands.push_back(spv::ImageOperandsSampleMask);
2659 operands.push_back(*opIt);
2660 } else
2661 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002662 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002663 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2664 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002665 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002666 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2667 builder.addCapability(spv::CapabilitySparseResidency);
2668 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2669 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2670
2671 if (sampler.ms) {
2672 operands.push_back(spv::ImageOperandsSampleMask);
2673 operands.push_back(*opIt++);
2674 }
2675
2676 // Create the return type that was a special structure
2677 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002678 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002679 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2680 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2681
2682 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2683
2684 // Decode the return type
2685 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2686 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002687 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002688 // Process image atomic operations
2689
2690 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2691 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002692 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002693
John Kessenich8c8505c2016-07-26 12:50:38 -06002694 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002695 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002696
2697 std::vector<spv::Id> operands;
2698 operands.push_back(pointer);
2699 for (; opIt != arguments.end(); ++opIt)
2700 operands.push_back(*opIt);
2701
John Kessenich8c8505c2016-07-26 12:50:38 -06002702 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002703 }
2704 }
2705
2706 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002707 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002708 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2709
John Kessenichfc51d282015-08-19 13:34:18 -06002710 // check for bias argument
2711 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002712 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002713 int nonBiasArgCount = 2;
2714 if (cracked.offset)
2715 ++nonBiasArgCount;
2716 if (cracked.grad)
2717 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002718 if (cracked.lodClamp)
2719 ++nonBiasArgCount;
2720 if (sparse)
2721 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002722
2723 if ((int)arguments.size() > nonBiasArgCount)
2724 bias = true;
2725 }
2726
John Kessenicha5c33d62016-06-02 23:45:21 -06002727 // See if the sampler param should really be just the SPV image part
2728 if (cracked.fetch) {
2729 // a fetch needs to have the image extracted first
2730 if (builder.isSampledImage(params.sampler))
2731 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2732 }
2733
John Kessenichfc51d282015-08-19 13:34:18 -06002734 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002735
John Kessenichfc51d282015-08-19 13:34:18 -06002736 params.coords = arguments[1];
2737 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002738 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002739
2740 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002741 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002742 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002743 ++extraArgs;
2744 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002745 params.Dref = arguments[2];
2746 ++extraArgs;
2747 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002748 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002749 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002750 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002751 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002752 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002753 dRefComp = builder.getNumComponents(params.coords) - 1;
2754 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002755 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2756 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002757
2758 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002759 if (cracked.lod) {
2760 params.lod = arguments[2];
2761 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002762 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2763 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2764 noImplicitLod = true;
2765 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002766
2767 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002768 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002769 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002770 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002771 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002772
2773 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002774 if (cracked.grad) {
2775 params.gradX = arguments[2 + extraArgs];
2776 params.gradY = arguments[3 + extraArgs];
2777 extraArgs += 2;
2778 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002779
2780 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002781 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002782 params.offset = arguments[2 + extraArgs];
2783 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002784 } else if (cracked.offsets) {
2785 params.offsets = arguments[2 + extraArgs];
2786 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002787 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002788
2789 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002790 if (cracked.lodClamp) {
2791 params.lodClamp = arguments[2 + extraArgs];
2792 ++extraArgs;
2793 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002794
2795 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002796 if (sparse) {
2797 params.texelOut = arguments[2 + extraArgs];
2798 ++extraArgs;
2799 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002800
2801 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002802 if (bias) {
2803 params.bias = arguments[2 + extraArgs];
2804 ++extraArgs;
2805 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002806
2807 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002808 if (cracked.gather && ! sampler.shadow) {
2809 // default component is 0, if missing, otherwise an argument
2810 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002811 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002812 ++extraArgs;
2813 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002814 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002815 }
2816 }
John Kessenichfc51d282015-08-19 13:34:18 -06002817
John Kessenich65336482016-06-16 14:06:26 -06002818 // projective component (might not to move)
2819 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2820 // are divided by the last component of P."
2821 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2822 // unused components will appear after all used components."
2823 if (cracked.proj) {
2824 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2825 int projTargetComp;
2826 switch (sampler.dim) {
2827 case glslang::Esd1D: projTargetComp = 1; break;
2828 case glslang::Esd2D: projTargetComp = 2; break;
2829 case glslang::EsdRect: projTargetComp = 2; break;
2830 default: projTargetComp = projSourceComp; break;
2831 }
2832 // copy the projective coordinate if we have to
2833 if (projTargetComp != projSourceComp) {
2834 spv::Id projComp = builder.createCompositeExtract(params.coords,
2835 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2836 projSourceComp);
2837 params.coords = builder.createCompositeInsert(projComp, params.coords,
2838 builder.getTypeId(params.coords), projTargetComp);
2839 }
2840 }
2841
John Kessenich8c8505c2016-07-26 12:50:38 -06002842 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002843}
2844
2845spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2846{
2847 // Grab the function's pointer from the previously created function
2848 spv::Function* function = functionMap[node->getName().c_str()];
2849 if (! function)
2850 return 0;
2851
2852 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2853 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2854
2855 // See comments in makeFunctions() for details about the semantics for parameter passing.
2856 //
2857 // These imply we need a four step process:
2858 // 1. Evaluate the arguments
2859 // 2. Allocate and make copies of in, out, and inout arguments
2860 // 3. Make the call
2861 // 4. Copy back the results
2862
2863 // 1. Evaluate the arguments
2864 std::vector<spv::Builder::AccessChain> lValues;
2865 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002866 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002867 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002868 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002869 // build l-value
2870 builder.clearAccessChain();
2871 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002872 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002873 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002874 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002875 // save l-value
2876 lValues.push_back(builder.getAccessChain());
2877 } else {
2878 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002879 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002880 }
2881 }
2882
2883 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2884 // copy the original into that space.
2885 //
2886 // Also, build up the list of actual arguments to pass in for the call
2887 int lValueCount = 0;
2888 int rValueCount = 0;
2889 std::vector<spv::Id> spvArgs;
2890 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002891 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002892 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002893 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002894 builder.setAccessChain(lValues[lValueCount]);
2895 arg = builder.accessChainGetLValue();
2896 ++lValueCount;
2897 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002898 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002899 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2900 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2901 // need to copy the input into output space
2902 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002903 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002904 builder.createStore(copy, arg);
2905 }
2906 ++lValueCount;
2907 } else {
2908 arg = rValues[rValueCount];
2909 ++rValueCount;
2910 }
2911 spvArgs.push_back(arg);
2912 }
2913
2914 // 3. Make the call.
2915 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002916 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002917
2918 // 4. Copy back out an "out" arguments.
2919 lValueCount = 0;
2920 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2921 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2922 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2923 spv::Id copy = builder.createLoad(spvArgs[a]);
2924 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002925 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002926 }
2927 ++lValueCount;
2928 }
2929 }
2930
2931 return result;
2932}
2933
2934// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002935spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2936 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002937 spv::Id typeId, spv::Id left, spv::Id right,
2938 glslang::TBasicType typeProxy, bool reduceComparison)
2939{
Rex Xu8ff43de2016-04-22 16:51:45 +08002940 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002941 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002942 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002943
2944 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002945 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002946 bool comparison = false;
2947
2948 switch (op) {
2949 case glslang::EOpAdd:
2950 case glslang::EOpAddAssign:
2951 if (isFloat)
2952 binOp = spv::OpFAdd;
2953 else
2954 binOp = spv::OpIAdd;
2955 break;
2956 case glslang::EOpSub:
2957 case glslang::EOpSubAssign:
2958 if (isFloat)
2959 binOp = spv::OpFSub;
2960 else
2961 binOp = spv::OpISub;
2962 break;
2963 case glslang::EOpMul:
2964 case glslang::EOpMulAssign:
2965 if (isFloat)
2966 binOp = spv::OpFMul;
2967 else
2968 binOp = spv::OpIMul;
2969 break;
2970 case glslang::EOpVectorTimesScalar:
2971 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002972 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002973 if (builder.isVector(right))
2974 std::swap(left, right);
2975 assert(builder.isScalar(right));
2976 needMatchingVectors = false;
2977 binOp = spv::OpVectorTimesScalar;
2978 } else
2979 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002980 break;
2981 case glslang::EOpVectorTimesMatrix:
2982 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002983 binOp = spv::OpVectorTimesMatrix;
2984 break;
2985 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002986 binOp = spv::OpMatrixTimesVector;
2987 break;
2988 case glslang::EOpMatrixTimesScalar:
2989 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002990 binOp = spv::OpMatrixTimesScalar;
2991 break;
2992 case glslang::EOpMatrixTimesMatrix:
2993 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002994 binOp = spv::OpMatrixTimesMatrix;
2995 break;
2996 case glslang::EOpOuterProduct:
2997 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002998 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002999 break;
3000
3001 case glslang::EOpDiv:
3002 case glslang::EOpDivAssign:
3003 if (isFloat)
3004 binOp = spv::OpFDiv;
3005 else if (isUnsigned)
3006 binOp = spv::OpUDiv;
3007 else
3008 binOp = spv::OpSDiv;
3009 break;
3010 case glslang::EOpMod:
3011 case glslang::EOpModAssign:
3012 if (isFloat)
3013 binOp = spv::OpFMod;
3014 else if (isUnsigned)
3015 binOp = spv::OpUMod;
3016 else
3017 binOp = spv::OpSMod;
3018 break;
3019 case glslang::EOpRightShift:
3020 case glslang::EOpRightShiftAssign:
3021 if (isUnsigned)
3022 binOp = spv::OpShiftRightLogical;
3023 else
3024 binOp = spv::OpShiftRightArithmetic;
3025 break;
3026 case glslang::EOpLeftShift:
3027 case glslang::EOpLeftShiftAssign:
3028 binOp = spv::OpShiftLeftLogical;
3029 break;
3030 case glslang::EOpAnd:
3031 case glslang::EOpAndAssign:
3032 binOp = spv::OpBitwiseAnd;
3033 break;
3034 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003035 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 binOp = spv::OpLogicalAnd;
3037 break;
3038 case glslang::EOpInclusiveOr:
3039 case glslang::EOpInclusiveOrAssign:
3040 binOp = spv::OpBitwiseOr;
3041 break;
3042 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003043 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003044 binOp = spv::OpLogicalOr;
3045 break;
3046 case glslang::EOpExclusiveOr:
3047 case glslang::EOpExclusiveOrAssign:
3048 binOp = spv::OpBitwiseXor;
3049 break;
3050 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003051 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003052 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003053 break;
3054
3055 case glslang::EOpLessThan:
3056 case glslang::EOpGreaterThan:
3057 case glslang::EOpLessThanEqual:
3058 case glslang::EOpGreaterThanEqual:
3059 case glslang::EOpEqual:
3060 case glslang::EOpNotEqual:
3061 case glslang::EOpVectorEqual:
3062 case glslang::EOpVectorNotEqual:
3063 comparison = true;
3064 break;
3065 default:
3066 break;
3067 }
3068
John Kessenich7c1aa102015-10-15 13:29:11 -06003069 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003070 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003071 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003072 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003073 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003074
3075 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003076 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003077 builder.promoteScalar(precision, left, right);
3078
qining25262b32016-05-06 17:25:16 -04003079 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3080 addDecoration(result, noContraction);
3081 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003082 }
3083
3084 if (! comparison)
3085 return 0;
3086
John Kessenich7c1aa102015-10-15 13:29:11 -06003087 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003088
John Kessenich4583b612016-08-07 19:14:22 -06003089 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3090 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003091 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003092
3093 switch (op) {
3094 case glslang::EOpLessThan:
3095 if (isFloat)
3096 binOp = spv::OpFOrdLessThan;
3097 else if (isUnsigned)
3098 binOp = spv::OpULessThan;
3099 else
3100 binOp = spv::OpSLessThan;
3101 break;
3102 case glslang::EOpGreaterThan:
3103 if (isFloat)
3104 binOp = spv::OpFOrdGreaterThan;
3105 else if (isUnsigned)
3106 binOp = spv::OpUGreaterThan;
3107 else
3108 binOp = spv::OpSGreaterThan;
3109 break;
3110 case glslang::EOpLessThanEqual:
3111 if (isFloat)
3112 binOp = spv::OpFOrdLessThanEqual;
3113 else if (isUnsigned)
3114 binOp = spv::OpULessThanEqual;
3115 else
3116 binOp = spv::OpSLessThanEqual;
3117 break;
3118 case glslang::EOpGreaterThanEqual:
3119 if (isFloat)
3120 binOp = spv::OpFOrdGreaterThanEqual;
3121 else if (isUnsigned)
3122 binOp = spv::OpUGreaterThanEqual;
3123 else
3124 binOp = spv::OpSGreaterThanEqual;
3125 break;
3126 case glslang::EOpEqual:
3127 case glslang::EOpVectorEqual:
3128 if (isFloat)
3129 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003130 else if (isBool)
3131 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003132 else
3133 binOp = spv::OpIEqual;
3134 break;
3135 case glslang::EOpNotEqual:
3136 case glslang::EOpVectorNotEqual:
3137 if (isFloat)
3138 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003139 else if (isBool)
3140 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003141 else
3142 binOp = spv::OpINotEqual;
3143 break;
3144 default:
3145 break;
3146 }
3147
qining25262b32016-05-06 17:25:16 -04003148 if (binOp != spv::OpNop) {
3149 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3150 addDecoration(result, noContraction);
3151 return builder.setPrecision(result, precision);
3152 }
John Kessenich140f3df2015-06-26 16:58:36 -06003153
3154 return 0;
3155}
3156
John Kessenich04bb8a02015-12-12 12:28:14 -07003157//
3158// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3159// These can be any of:
3160//
3161// matrix * scalar
3162// scalar * matrix
3163// matrix * matrix linear algebraic
3164// matrix * vector
3165// vector * matrix
3166// matrix * matrix componentwise
3167// matrix op matrix op in {+, -, /}
3168// matrix op scalar op in {+, -, /}
3169// scalar op matrix op in {+, -, /}
3170//
qining25262b32016-05-06 17:25:16 -04003171spv::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 -07003172{
3173 bool firstClass = true;
3174
3175 // First, handle first-class matrix operations (* and matrix/scalar)
3176 switch (op) {
3177 case spv::OpFDiv:
3178 if (builder.isMatrix(left) && builder.isScalar(right)) {
3179 // turn matrix / scalar into a multiply...
3180 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3181 op = spv::OpMatrixTimesScalar;
3182 } else
3183 firstClass = false;
3184 break;
3185 case spv::OpMatrixTimesScalar:
3186 if (builder.isMatrix(right))
3187 std::swap(left, right);
3188 assert(builder.isScalar(right));
3189 break;
3190 case spv::OpVectorTimesMatrix:
3191 assert(builder.isVector(left));
3192 assert(builder.isMatrix(right));
3193 break;
3194 case spv::OpMatrixTimesVector:
3195 assert(builder.isMatrix(left));
3196 assert(builder.isVector(right));
3197 break;
3198 case spv::OpMatrixTimesMatrix:
3199 assert(builder.isMatrix(left));
3200 assert(builder.isMatrix(right));
3201 break;
3202 default:
3203 firstClass = false;
3204 break;
3205 }
3206
qining25262b32016-05-06 17:25:16 -04003207 if (firstClass) {
3208 spv::Id result = builder.createBinOp(op, typeId, left, right);
3209 addDecoration(result, noContraction);
3210 return builder.setPrecision(result, precision);
3211 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003212
LoopDawg592860c2016-06-09 08:57:35 -06003213 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003214 // The result type of all of them is the same type as the (a) matrix operand.
3215 // The algorithm is to:
3216 // - break the matrix(es) into vectors
3217 // - smear any scalar to a vector
3218 // - do vector operations
3219 // - make a matrix out the vector results
3220 switch (op) {
3221 case spv::OpFAdd:
3222 case spv::OpFSub:
3223 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003224 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003225 case spv::OpFMul:
3226 {
3227 // one time set up...
3228 bool leftMat = builder.isMatrix(left);
3229 bool rightMat = builder.isMatrix(right);
3230 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3231 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3232 spv::Id scalarType = builder.getScalarTypeId(typeId);
3233 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3234 std::vector<spv::Id> results;
3235 spv::Id smearVec = spv::NoResult;
3236 if (builder.isScalar(left))
3237 smearVec = builder.smearScalar(precision, left, vecType);
3238 else if (builder.isScalar(right))
3239 smearVec = builder.smearScalar(precision, right, vecType);
3240
3241 // do each vector op
3242 for (unsigned int c = 0; c < numCols; ++c) {
3243 std::vector<unsigned int> indexes;
3244 indexes.push_back(c);
3245 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3246 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003247 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3248 addDecoration(result, noContraction);
3249 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003250 }
3251
3252 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003253 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003254 }
3255 default:
3256 assert(0);
3257 return spv::NoResult;
3258 }
3259}
3260
qining25262b32016-05-06 17:25:16 -04003261spv::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 -06003262{
3263 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003264 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003265 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003266 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003267 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003268
3269 switch (op) {
3270 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003271 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003272 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003273 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003274 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003275 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003276 unaryOp = spv::OpSNegate;
3277 break;
3278
3279 case glslang::EOpLogicalNot:
3280 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003281 unaryOp = spv::OpLogicalNot;
3282 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003283 case glslang::EOpBitwiseNot:
3284 unaryOp = spv::OpNot;
3285 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003286
John Kessenich140f3df2015-06-26 16:58:36 -06003287 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003288 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003289 break;
3290 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003291 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003292 break;
3293 case glslang::EOpTranspose:
3294 unaryOp = spv::OpTranspose;
3295 break;
3296
3297 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003298 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003299 break;
3300 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003301 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003302 break;
3303 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003304 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003305 break;
3306 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003307 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003308 break;
3309 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003310 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003311 break;
3312 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
3318 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003319 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321
3322 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003323 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 break;
3325 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003326 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003327 break;
3328 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003329 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003330 break;
3331 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003332 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003333 break;
3334 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003335 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003336 break;
3337 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003338 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003339 break;
3340
3341 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003342 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003343 break;
3344 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003345 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003346 break;
3347
3348 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003349 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003350 break;
3351 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003352 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003353 break;
3354 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003355 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003356 break;
3357 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003358 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003359 break;
3360 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003361 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003362 break;
3363 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003364 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003365 break;
3366
3367 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003369 break;
3370 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003371 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003372 break;
3373 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003374 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003375 break;
3376 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003377 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003378 break;
3379 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003380 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003381 break;
3382 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003383 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003384 break;
3385
3386 case glslang::EOpIsNan:
3387 unaryOp = spv::OpIsNan;
3388 break;
3389 case glslang::EOpIsInf:
3390 unaryOp = spv::OpIsInf;
3391 break;
LoopDawg592860c2016-06-09 08:57:35 -06003392 case glslang::EOpIsFinite:
3393 unaryOp = spv::OpIsFinite;
3394 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003395
Rex Xucbc426e2015-12-15 16:03:10 +08003396 case glslang::EOpFloatBitsToInt:
3397 case glslang::EOpFloatBitsToUint:
3398 case glslang::EOpIntBitsToFloat:
3399 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003400 case glslang::EOpDoubleBitsToInt64:
3401 case glslang::EOpDoubleBitsToUint64:
3402 case glslang::EOpInt64BitsToDouble:
3403 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003404 unaryOp = spv::OpBitcast;
3405 break;
3406
John Kessenich140f3df2015-06-26 16:58:36 -06003407 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003408 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003411 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003412 break;
3413 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003414 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003415 break;
3416 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003417 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 break;
3419 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003420 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003421 break;
3422 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003423 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003424 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003425 case glslang::EOpPackSnorm4x8:
3426 libCall = spv::GLSLstd450PackSnorm4x8;
3427 break;
3428 case glslang::EOpUnpackSnorm4x8:
3429 libCall = spv::GLSLstd450UnpackSnorm4x8;
3430 break;
3431 case glslang::EOpPackUnorm4x8:
3432 libCall = spv::GLSLstd450PackUnorm4x8;
3433 break;
3434 case glslang::EOpUnpackUnorm4x8:
3435 libCall = spv::GLSLstd450UnpackUnorm4x8;
3436 break;
3437 case glslang::EOpPackDouble2x32:
3438 libCall = spv::GLSLstd450PackDouble2x32;
3439 break;
3440 case glslang::EOpUnpackDouble2x32:
3441 libCall = spv::GLSLstd450UnpackDouble2x32;
3442 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003443
Rex Xu8ff43de2016-04-22 16:51:45 +08003444 case glslang::EOpPackInt2x32:
3445 case glslang::EOpUnpackInt2x32:
3446 case glslang::EOpPackUint2x32:
3447 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003448 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003449 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3450 break;
3451
John Kessenich140f3df2015-06-26 16:58:36 -06003452 case glslang::EOpDPdx:
3453 unaryOp = spv::OpDPdx;
3454 break;
3455 case glslang::EOpDPdy:
3456 unaryOp = spv::OpDPdy;
3457 break;
3458 case glslang::EOpFwidth:
3459 unaryOp = spv::OpFwidth;
3460 break;
3461 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003462 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003463 unaryOp = spv::OpDPdxFine;
3464 break;
3465 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003466 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003467 unaryOp = spv::OpDPdyFine;
3468 break;
3469 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003470 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003471 unaryOp = spv::OpFwidthFine;
3472 break;
3473 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003474 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003475 unaryOp = spv::OpDPdxCoarse;
3476 break;
3477 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003478 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003479 unaryOp = spv::OpDPdyCoarse;
3480 break;
3481 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003482 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003483 unaryOp = spv::OpFwidthCoarse;
3484 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003485 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003486 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003487 libCall = spv::GLSLstd450InterpolateAtCentroid;
3488 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 case glslang::EOpAny:
3490 unaryOp = spv::OpAny;
3491 break;
3492 case glslang::EOpAll:
3493 unaryOp = spv::OpAll;
3494 break;
3495
3496 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003497 if (isFloat)
3498 libCall = spv::GLSLstd450FAbs;
3499 else
3500 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
3502 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003503 if (isFloat)
3504 libCall = spv::GLSLstd450FSign;
3505 else
3506 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003507 break;
3508
John Kessenichfc51d282015-08-19 13:34:18 -06003509 case glslang::EOpAtomicCounterIncrement:
3510 case glslang::EOpAtomicCounterDecrement:
3511 case glslang::EOpAtomicCounter:
3512 {
3513 // Handle all of the atomics in one place, in createAtomicOperation()
3514 std::vector<spv::Id> operands;
3515 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003516 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003517 }
3518
John Kessenichfc51d282015-08-19 13:34:18 -06003519 case glslang::EOpBitFieldReverse:
3520 unaryOp = spv::OpBitReverse;
3521 break;
3522 case glslang::EOpBitCount:
3523 unaryOp = spv::OpBitCount;
3524 break;
3525 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003526 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003527 break;
3528 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003529 if (isUnsigned)
3530 libCall = spv::GLSLstd450FindUMsb;
3531 else
3532 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003533 break;
3534
Rex Xu574ab042016-04-14 16:53:07 +08003535 case glslang::EOpBallot:
3536 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003537 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003538 libCall = spv::GLSLstd450Bad;
3539 break;
3540
Rex Xu338b1852016-05-05 20:38:33 +08003541 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003542 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003543 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003544#ifdef AMD_EXTENSIONS
3545 case glslang::EOpMinInvocations:
3546 case glslang::EOpMaxInvocations:
3547 case glslang::EOpAddInvocations:
3548 case glslang::EOpMinInvocationsNonUniform:
3549 case glslang::EOpMaxInvocationsNonUniform:
3550 case glslang::EOpAddInvocationsNonUniform:
3551#endif
3552 return createInvocationsOperation(op, typeId, operand, typeProxy);
3553
3554#ifdef AMD_EXTENSIONS
3555 case glslang::EOpMbcnt:
3556 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3557 libCall = spv::MbcntAMD;
3558 break;
3559
3560 case glslang::EOpCubeFaceIndex:
3561 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3562 libCall = spv::CubeFaceIndexAMD;
3563 break;
3564
3565 case glslang::EOpCubeFaceCoord:
3566 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3567 libCall = spv::CubeFaceCoordAMD;
3568 break;
3569#endif
Rex Xu338b1852016-05-05 20:38:33 +08003570
John Kessenich140f3df2015-06-26 16:58:36 -06003571 default:
3572 return 0;
3573 }
3574
3575 spv::Id id;
3576 if (libCall >= 0) {
3577 std::vector<spv::Id> args;
3578 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003579 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003580 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003581 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003582 }
John Kessenich140f3df2015-06-26 16:58:36 -06003583
qining25262b32016-05-06 17:25:16 -04003584 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003585 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003586}
3587
John Kessenich7a53f762016-01-20 11:19:27 -07003588// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003589spv::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 -07003590{
3591 // Handle unary operations vector by vector.
3592 // The result type is the same type as the original type.
3593 // The algorithm is to:
3594 // - break the matrix into vectors
3595 // - apply the operation to each vector
3596 // - make a matrix out the vector results
3597
3598 // get the types sorted out
3599 int numCols = builder.getNumColumns(operand);
3600 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003601 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3602 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003603 std::vector<spv::Id> results;
3604
3605 // do each vector op
3606 for (int c = 0; c < numCols; ++c) {
3607 std::vector<unsigned int> indexes;
3608 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003609 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3610 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3611 addDecoration(destVec, noContraction);
3612 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003613 }
3614
3615 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003616 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003617}
3618
Rex Xu73e3ce72016-04-27 18:48:17 +08003619spv::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 -06003620{
3621 spv::Op convOp = spv::OpNop;
3622 spv::Id zero = 0;
3623 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003624 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003625
3626 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3627
3628 switch (op) {
3629 case glslang::EOpConvIntToBool:
3630 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003631 case glslang::EOpConvInt64ToBool:
3632 case glslang::EOpConvUint64ToBool:
3633 zero = (op == glslang::EOpConvInt64ToBool ||
3634 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003635 zero = makeSmearedConstant(zero, vectorSize);
3636 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3637
3638 case glslang::EOpConvFloatToBool:
3639 zero = builder.makeFloatConstant(0.0F);
3640 zero = makeSmearedConstant(zero, vectorSize);
3641 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3642
3643 case glslang::EOpConvDoubleToBool:
3644 zero = builder.makeDoubleConstant(0.0);
3645 zero = makeSmearedConstant(zero, vectorSize);
3646 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3647
3648 case glslang::EOpConvBoolToFloat:
3649 convOp = spv::OpSelect;
3650 zero = builder.makeFloatConstant(0.0);
3651 one = builder.makeFloatConstant(1.0);
3652 break;
3653 case glslang::EOpConvBoolToDouble:
3654 convOp = spv::OpSelect;
3655 zero = builder.makeDoubleConstant(0.0);
3656 one = builder.makeDoubleConstant(1.0);
3657 break;
3658 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003659 case glslang::EOpConvBoolToInt64:
3660 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3661 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003662 convOp = spv::OpSelect;
3663 break;
3664 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003665 case glslang::EOpConvBoolToUint64:
3666 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3667 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003668 convOp = spv::OpSelect;
3669 break;
3670
3671 case glslang::EOpConvIntToFloat:
3672 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003673 case glslang::EOpConvInt64ToFloat:
3674 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003675 convOp = spv::OpConvertSToF;
3676 break;
3677
3678 case glslang::EOpConvUintToFloat:
3679 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003680 case glslang::EOpConvUint64ToFloat:
3681 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003682 convOp = spv::OpConvertUToF;
3683 break;
3684
3685 case glslang::EOpConvDoubleToFloat:
3686 case glslang::EOpConvFloatToDouble:
3687 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003688 if (builder.isMatrixType(destType))
3689 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003690 break;
3691
3692 case glslang::EOpConvFloatToInt:
3693 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003694 case glslang::EOpConvFloatToInt64:
3695 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003696 convOp = spv::OpConvertFToS;
3697 break;
3698
3699 case glslang::EOpConvUintToInt:
3700 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003701 case glslang::EOpConvUint64ToInt64:
3702 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003703 if (builder.isInSpecConstCodeGenMode()) {
3704 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003705 zero = (op == glslang::EOpConvUintToInt64 ||
3706 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003707 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003708 // Use OpIAdd, instead of OpBitcast to do the conversion when
3709 // generating for OpSpecConstantOp instruction.
3710 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3711 }
3712 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003713 convOp = spv::OpBitcast;
3714 break;
3715
3716 case glslang::EOpConvFloatToUint:
3717 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003718 case glslang::EOpConvFloatToUint64:
3719 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003720 convOp = spv::OpConvertFToU;
3721 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003722
3723 case glslang::EOpConvIntToInt64:
3724 case glslang::EOpConvInt64ToInt:
3725 convOp = spv::OpSConvert;
3726 break;
3727
3728 case glslang::EOpConvUintToUint64:
3729 case glslang::EOpConvUint64ToUint:
3730 convOp = spv::OpUConvert;
3731 break;
3732
3733 case glslang::EOpConvIntToUint64:
3734 case glslang::EOpConvInt64ToUint:
3735 case glslang::EOpConvUint64ToInt:
3736 case glslang::EOpConvUintToInt64:
3737 // OpSConvert/OpUConvert + OpBitCast
3738 switch (op) {
3739 case glslang::EOpConvIntToUint64:
3740 convOp = spv::OpSConvert;
3741 type = builder.makeIntType(64);
3742 break;
3743 case glslang::EOpConvInt64ToUint:
3744 convOp = spv::OpSConvert;
3745 type = builder.makeIntType(32);
3746 break;
3747 case glslang::EOpConvUint64ToInt:
3748 convOp = spv::OpUConvert;
3749 type = builder.makeUintType(32);
3750 break;
3751 case glslang::EOpConvUintToInt64:
3752 convOp = spv::OpUConvert;
3753 type = builder.makeUintType(64);
3754 break;
3755 default:
3756 assert(0);
3757 break;
3758 }
3759
3760 if (vectorSize > 0)
3761 type = builder.makeVectorType(type, vectorSize);
3762
3763 operand = builder.createUnaryOp(convOp, type, operand);
3764
3765 if (builder.isInSpecConstCodeGenMode()) {
3766 // Build zero scalar or vector for OpIAdd.
3767 zero = (op == glslang::EOpConvIntToUint64 ||
3768 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3769 zero = makeSmearedConstant(zero, vectorSize);
3770 // Use OpIAdd, instead of OpBitcast to do the conversion when
3771 // generating for OpSpecConstantOp instruction.
3772 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3773 }
3774 // For normal run-time conversion instruction, use OpBitcast.
3775 convOp = spv::OpBitcast;
3776 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 default:
3778 break;
3779 }
3780
3781 spv::Id result = 0;
3782 if (convOp == spv::OpNop)
3783 return result;
3784
3785 if (convOp == spv::OpSelect) {
3786 zero = makeSmearedConstant(zero, vectorSize);
3787 one = makeSmearedConstant(one, vectorSize);
3788 result = builder.createTriOp(convOp, destType, operand, one, zero);
3789 } else
3790 result = builder.createUnaryOp(convOp, destType, operand);
3791
John Kessenich32cfd492016-02-02 12:37:46 -07003792 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003793}
3794
3795spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3796{
3797 if (vectorSize == 0)
3798 return constant;
3799
3800 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3801 std::vector<spv::Id> components;
3802 for (int c = 0; c < vectorSize; ++c)
3803 components.push_back(constant);
3804 return builder.makeCompositeConstant(vectorTypeId, components);
3805}
3806
John Kessenich426394d2015-07-23 10:22:48 -06003807// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003808spv::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 -06003809{
3810 spv::Op opCode = spv::OpNop;
3811
3812 switch (op) {
3813 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003814 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003815 opCode = spv::OpAtomicIAdd;
3816 break;
3817 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003818 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003819 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003820 break;
3821 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003822 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003823 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003824 break;
3825 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003826 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003827 opCode = spv::OpAtomicAnd;
3828 break;
3829 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003830 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003831 opCode = spv::OpAtomicOr;
3832 break;
3833 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003834 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003835 opCode = spv::OpAtomicXor;
3836 break;
3837 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003838 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003839 opCode = spv::OpAtomicExchange;
3840 break;
3841 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003842 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003843 opCode = spv::OpAtomicCompareExchange;
3844 break;
3845 case glslang::EOpAtomicCounterIncrement:
3846 opCode = spv::OpAtomicIIncrement;
3847 break;
3848 case glslang::EOpAtomicCounterDecrement:
3849 opCode = spv::OpAtomicIDecrement;
3850 break;
3851 case glslang::EOpAtomicCounter:
3852 opCode = spv::OpAtomicLoad;
3853 break;
3854 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003855 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003856 break;
3857 }
3858
3859 // Sort out the operands
3860 // - mapping from glslang -> SPV
3861 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003862 // - compare-exchange swaps the value and comparator
3863 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003864 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3865 auto opIt = operands.begin(); // walk the glslang operands
3866 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003867 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3868 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3869 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003870 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3871 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003872 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003873 spvAtomicOperands.push_back(*(opIt + 1));
3874 spvAtomicOperands.push_back(*opIt);
3875 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003876 }
John Kessenich426394d2015-07-23 10:22:48 -06003877
John Kessenich3e60a6f2015-09-14 22:45:16 -06003878 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003879 for (; opIt != operands.end(); ++opIt)
3880 spvAtomicOperands.push_back(*opIt);
3881
3882 return builder.createOp(opCode, typeId, spvAtomicOperands);
3883}
3884
John Kessenich91cef522016-05-05 16:45:40 -06003885// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003886spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003887{
Rex Xu9d93a232016-05-05 12:30:44 +08003888 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3889 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3890
John Kessenich91cef522016-05-05 16:45:40 -06003891 builder.addCapability(spv::CapabilityGroups);
3892
3893 std::vector<spv::Id> operands;
3894 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003895#ifdef AMD_EXTENSIONS
3896 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3897 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3898 operands.push_back(spv::GroupOperationReduce);
3899#endif
John Kessenich91cef522016-05-05 16:45:40 -06003900 operands.push_back(operand);
3901
3902 switch (op) {
3903 case glslang::EOpAnyInvocation:
3904 case glslang::EOpAllInvocations:
3905 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3906
3907 case glslang::EOpAllInvocationsEqual:
3908 {
3909 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3910 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3911
3912 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3913 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3914 }
Rex Xu9d93a232016-05-05 12:30:44 +08003915#ifdef AMD_EXTENSIONS
3916 case glslang::EOpMinInvocations:
3917 case glslang::EOpMaxInvocations:
3918 case glslang::EOpAddInvocations:
3919 {
3920 spv::Op spvOp = spv::OpNop;
3921 if (op == glslang::EOpMinInvocations) {
3922 if (isFloat)
3923 spvOp = spv::OpGroupFMin;
3924 else {
3925 if (isUnsigned)
3926 spvOp = spv::OpGroupUMin;
3927 else
3928 spvOp = spv::OpGroupSMin;
3929 }
3930 } else if (op == glslang::EOpMaxInvocations) {
3931 if (isFloat)
3932 spvOp = spv::OpGroupFMax;
3933 else {
3934 if (isUnsigned)
3935 spvOp = spv::OpGroupUMax;
3936 else
3937 spvOp = spv::OpGroupSMax;
3938 }
3939 } else {
3940 if (isFloat)
3941 spvOp = spv::OpGroupFAdd;
3942 else
3943 spvOp = spv::OpGroupIAdd;
3944 }
3945
Rex Xu2bbbe062016-08-23 15:41:05 +08003946 if (builder.isVectorType(typeId))
3947 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
3948 else
3949 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08003950 }
3951 case glslang::EOpMinInvocationsNonUniform:
3952 case glslang::EOpMaxInvocationsNonUniform:
3953 case glslang::EOpAddInvocationsNonUniform:
3954 {
3955 spv::Op spvOp = spv::OpNop;
3956 if (op == glslang::EOpMinInvocationsNonUniform) {
3957 if (isFloat)
3958 spvOp = spv::OpGroupFMinNonUniformAMD;
3959 else {
3960 if (isUnsigned)
3961 spvOp = spv::OpGroupUMinNonUniformAMD;
3962 else
3963 spvOp = spv::OpGroupSMinNonUniformAMD;
3964 }
3965 }
3966 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3967 if (isFloat)
3968 spvOp = spv::OpGroupFMaxNonUniformAMD;
3969 else {
3970 if (isUnsigned)
3971 spvOp = spv::OpGroupUMaxNonUniformAMD;
3972 else
3973 spvOp = spv::OpGroupSMaxNonUniformAMD;
3974 }
3975 }
3976 else {
3977 if (isFloat)
3978 spvOp = spv::OpGroupFAddNonUniformAMD;
3979 else
3980 spvOp = spv::OpGroupIAddNonUniformAMD;
3981 }
3982
Rex Xu2bbbe062016-08-23 15:41:05 +08003983 if (builder.isVectorType(typeId))
3984 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
3985 else
3986 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08003987 }
3988#endif
John Kessenich91cef522016-05-05 16:45:40 -06003989 default:
3990 logger->missingFunctionality("invocation operation");
3991 return spv::NoResult;
3992 }
3993}
3994
Rex Xu2bbbe062016-08-23 15:41:05 +08003995#ifdef AMD_EXTENSIONS
3996// Create group invocation operations on a vector
3997spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand)
3998{
3999 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4000 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4001 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd ||
4002 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4003 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4004 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
4005
4006 // Handle group invocation operations scalar by scalar.
4007 // The result type is the same type as the original type.
4008 // The algorithm is to:
4009 // - break the vector into scalars
4010 // - apply the operation to each scalar
4011 // - make a vector out the scalar results
4012
4013 // get the types sorted out
4014 int numComponents = builder.getNumComponents(operand);
4015 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operand));
4016 std::vector<spv::Id> results;
4017
4018 // do each scalar op
4019 for (int comp = 0; comp < numComponents; ++comp) {
4020 std::vector<unsigned int> indexes;
4021 indexes.push_back(comp);
4022 spv::Id scalar = builder.createCompositeExtract(operand, scalarType, indexes);
4023
4024 std::vector<spv::Id> operands;
4025 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4026 operands.push_back(spv::GroupOperationReduce);
4027 operands.push_back(scalar);
4028
4029 results.push_back(builder.createOp(op, scalarType, operands));
4030 }
4031
4032 // put the pieces together
4033 return builder.createCompositeConstruct(typeId, results);
4034}
4035#endif
4036
John Kessenich5e4b1242015-08-06 22:53:06 -06004037spv::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 -06004038{
Rex Xu8ff43de2016-04-22 16:51:45 +08004039 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004040 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
4041
John Kessenich140f3df2015-06-26 16:58:36 -06004042 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004043 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004044 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004045 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004046 spv::Id typeId0 = 0;
4047 if (consumedOperands > 0)
4048 typeId0 = builder.getTypeId(operands[0]);
4049 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004050
4051 switch (op) {
4052 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 if (isFloat)
4054 libCall = spv::GLSLstd450FMin;
4055 else if (isUnsigned)
4056 libCall = spv::GLSLstd450UMin;
4057 else
4058 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004059 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 if (isFloat)
4066 libCall = spv::GLSLstd450FMax;
4067 else if (isUnsigned)
4068 libCall = spv::GLSLstd450UMax;
4069 else
4070 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004071 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
4076 case glslang::EOpDot:
4077 opCode = spv::OpDot;
4078 break;
4079 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004080 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004081 break;
4082
4083 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 if (isFloat)
4085 libCall = spv::GLSLstd450FClamp;
4086 else if (isUnsigned)
4087 libCall = spv::GLSLstd450UClamp;
4088 else
4089 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004090 builder.promoteScalar(precision, operands.front(), operands[1]);
4091 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004092 break;
4093 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004094 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4095 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004096 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004097 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004098 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004099 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004100 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004101 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004102 break;
4103 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004104 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004105 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004106 break;
4107 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004108 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004109 builder.promoteScalar(precision, operands[0], operands[2]);
4110 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112
4113 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004114 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004115 break;
4116 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004118 break;
4119 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004120 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
4122 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004128 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004129 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004130 libCall = spv::GLSLstd450InterpolateAtSample;
4131 break;
4132 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004133 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004134 libCall = spv::GLSLstd450InterpolateAtOffset;
4135 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004136 case glslang::EOpAddCarry:
4137 opCode = spv::OpIAddCarry;
4138 typeId = builder.makeStructResultType(typeId0, typeId0);
4139 consumedOperands = 2;
4140 break;
4141 case glslang::EOpSubBorrow:
4142 opCode = spv::OpISubBorrow;
4143 typeId = builder.makeStructResultType(typeId0, typeId0);
4144 consumedOperands = 2;
4145 break;
4146 case glslang::EOpUMulExtended:
4147 opCode = spv::OpUMulExtended;
4148 typeId = builder.makeStructResultType(typeId0, typeId0);
4149 consumedOperands = 2;
4150 break;
4151 case glslang::EOpIMulExtended:
4152 opCode = spv::OpSMulExtended;
4153 typeId = builder.makeStructResultType(typeId0, typeId0);
4154 consumedOperands = 2;
4155 break;
4156 case glslang::EOpBitfieldExtract:
4157 if (isUnsigned)
4158 opCode = spv::OpBitFieldUExtract;
4159 else
4160 opCode = spv::OpBitFieldSExtract;
4161 break;
4162 case glslang::EOpBitfieldInsert:
4163 opCode = spv::OpBitFieldInsert;
4164 break;
4165
4166 case glslang::EOpFma:
4167 libCall = spv::GLSLstd450Fma;
4168 break;
4169 case glslang::EOpFrexp:
4170 libCall = spv::GLSLstd450FrexpStruct;
4171 if (builder.getNumComponents(operands[0]) == 1)
4172 frexpIntType = builder.makeIntegerType(32, true);
4173 else
4174 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4175 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4176 consumedOperands = 1;
4177 break;
4178 case glslang::EOpLdexp:
4179 libCall = spv::GLSLstd450Ldexp;
4180 break;
4181
Rex Xu574ab042016-04-14 16:53:07 +08004182 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004183 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004184 libCall = spv::GLSLstd450Bad;
4185 break;
4186
Rex Xu9d93a232016-05-05 12:30:44 +08004187#ifdef AMD_EXTENSIONS
4188 case glslang::EOpSwizzleInvocations:
4189 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4190 libCall = spv::SwizzleInvocationsAMD;
4191 break;
4192 case glslang::EOpSwizzleInvocationsMasked:
4193 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4194 libCall = spv::SwizzleInvocationsMaskedAMD;
4195 break;
4196 case glslang::EOpWriteInvocation:
4197 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4198 libCall = spv::WriteInvocationAMD;
4199 break;
4200
4201 case glslang::EOpMin3:
4202 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4203 if (isFloat)
4204 libCall = spv::FMin3AMD;
4205 else {
4206 if (isUnsigned)
4207 libCall = spv::UMin3AMD;
4208 else
4209 libCall = spv::SMin3AMD;
4210 }
4211 break;
4212 case glslang::EOpMax3:
4213 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4214 if (isFloat)
4215 libCall = spv::FMax3AMD;
4216 else {
4217 if (isUnsigned)
4218 libCall = spv::UMax3AMD;
4219 else
4220 libCall = spv::SMax3AMD;
4221 }
4222 break;
4223 case glslang::EOpMid3:
4224 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4225 if (isFloat)
4226 libCall = spv::FMid3AMD;
4227 else {
4228 if (isUnsigned)
4229 libCall = spv::UMid3AMD;
4230 else
4231 libCall = spv::SMid3AMD;
4232 }
4233 break;
4234
4235 case glslang::EOpInterpolateAtVertex:
4236 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4237 libCall = spv::InterpolateAtVertexAMD;
4238 break;
4239#endif
4240
John Kessenich140f3df2015-06-26 16:58:36 -06004241 default:
4242 return 0;
4243 }
4244
4245 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004246 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004247 // Use an extended instruction from the standard library.
4248 // Construct the call arguments, without modifying the original operands vector.
4249 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4250 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004251 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004252 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004253 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004254 case 0:
4255 // should all be handled by visitAggregate and createNoArgOperation
4256 assert(0);
4257 return 0;
4258 case 1:
4259 // should all be handled by createUnaryOperation
4260 assert(0);
4261 return 0;
4262 case 2:
4263 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4264 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004265 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004266 // anything 3 or over doesn't have l-value operands, so all should be consumed
4267 assert(consumedOperands == operands.size());
4268 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004269 break;
4270 }
4271 }
4272
John Kessenich55e7d112015-11-15 21:33:39 -07004273 // Decode the return types that were structures
4274 switch (op) {
4275 case glslang::EOpAddCarry:
4276 case glslang::EOpSubBorrow:
4277 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4278 id = builder.createCompositeExtract(id, typeId0, 0);
4279 break;
4280 case glslang::EOpUMulExtended:
4281 case glslang::EOpIMulExtended:
4282 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4283 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4284 break;
4285 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004286 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004287 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4288 id = builder.createCompositeExtract(id, typeId0, 0);
4289 break;
4290 default:
4291 break;
4292 }
4293
John Kessenich32cfd492016-02-02 12:37:46 -07004294 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004295}
4296
Rex Xu9d93a232016-05-05 12:30:44 +08004297// Intrinsics with no arguments (or no return value, and no precision).
4298spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004299{
4300 // TODO: get the barrier operands correct
4301
4302 switch (op) {
4303 case glslang::EOpEmitVertex:
4304 builder.createNoResultOp(spv::OpEmitVertex);
4305 return 0;
4306 case glslang::EOpEndPrimitive:
4307 builder.createNoResultOp(spv::OpEndPrimitive);
4308 return 0;
4309 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004310 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004311 return 0;
4312 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004313 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004314 return 0;
4315 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004316 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004317 return 0;
4318 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004319 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004320 return 0;
4321 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004322 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004323 return 0;
4324 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004325 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004326 return 0;
4327 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004328 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004329 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004330 case glslang::EOpAllMemoryBarrierWithGroupSync:
4331 // Control barrier with non-"None" semantic is also a memory barrier.
4332 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4333 return 0;
4334 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4335 // Control barrier with non-"None" semantic is also a memory barrier.
4336 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4337 return 0;
4338 case glslang::EOpWorkgroupMemoryBarrier:
4339 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4340 return 0;
4341 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4342 // Control barrier with non-"None" semantic is also a memory barrier.
4343 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4344 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004345#ifdef AMD_EXTENSIONS
4346 case glslang::EOpTime:
4347 {
4348 std::vector<spv::Id> args; // Dummy arguments
4349 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4350 return builder.setPrecision(id, precision);
4351 }
4352#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004353 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004354 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004355 return 0;
4356 }
4357}
4358
4359spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4360{
John Kessenich2f273362015-07-18 22:34:27 -06004361 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004362 spv::Id id;
4363 if (symbolValues.end() != iter) {
4364 id = iter->second;
4365 return id;
4366 }
4367
4368 // it was not found, create it
4369 id = createSpvVariable(symbol);
4370 symbolValues[symbol->getId()] = id;
4371
Rex Xuc884b4a2016-06-29 15:03:44 +08004372 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004373 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004374 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004375 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004376 if (symbol->getType().getQualifier().hasSpecConstantId())
4377 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004378 if (symbol->getQualifier().hasIndex())
4379 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4380 if (symbol->getQualifier().hasComponent())
4381 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4382 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004383 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004384 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004385 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004386 if (symbol->getQualifier().hasXfbBuffer())
4387 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4388 if (symbol->getQualifier().hasXfbOffset())
4389 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4390 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004391 // atomic counters use this:
4392 if (symbol->getQualifier().hasOffset())
4393 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004394 }
4395
scygan2c864272016-05-18 18:09:17 +02004396 if (symbol->getQualifier().hasLocation())
4397 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004398 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004399 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004400 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004401 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004402 }
John Kessenich140f3df2015-06-26 16:58:36 -06004403 if (symbol->getQualifier().hasSet())
4404 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004405 else if (IsDescriptorResource(symbol->getType())) {
4406 // default to 0
4407 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4408 }
John Kessenich140f3df2015-06-26 16:58:36 -06004409 if (symbol->getQualifier().hasBinding())
4410 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004411 if (symbol->getQualifier().hasAttachment())
4412 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004413 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004414 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004415 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004416 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004417 if (symbol->getQualifier().hasXfbBuffer())
4418 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4419 }
4420
Rex Xu1da878f2016-02-21 20:59:01 +08004421 if (symbol->getType().isImage()) {
4422 std::vector<spv::Decoration> memory;
4423 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4424 for (unsigned int i = 0; i < memory.size(); ++i)
4425 addDecoration(id, memory[i]);
4426 }
4427
John Kessenich140f3df2015-06-26 16:58:36 -06004428 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004429 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004430 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004431 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004432
John Kessenich140f3df2015-06-26 16:58:36 -06004433 return id;
4434}
4435
John Kessenich55e7d112015-11-15 21:33:39 -07004436// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004437void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4438{
John Kessenich4016e382016-07-15 11:53:56 -06004439 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004440 builder.addDecoration(id, dec);
4441}
4442
John Kessenich55e7d112015-11-15 21:33:39 -07004443// If 'dec' is valid, add a one-operand decoration to an object
4444void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4445{
John Kessenich4016e382016-07-15 11:53:56 -06004446 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004447 builder.addDecoration(id, dec, value);
4448}
4449
4450// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004451void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4452{
John Kessenich4016e382016-07-15 11:53:56 -06004453 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004454 builder.addMemberDecoration(id, (unsigned)member, dec);
4455}
4456
John Kessenich92187592016-02-01 13:45:25 -07004457// If 'dec' is valid, add a one-operand decoration to a struct member
4458void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4459{
John Kessenich4016e382016-07-15 11:53:56 -06004460 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004461 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4462}
4463
John Kessenich55e7d112015-11-15 21:33:39 -07004464// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004465// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004466//
4467// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4468//
4469// Recursively walk the nodes. The nodes form a tree whose leaves are
4470// regular constants, which themselves are trees that createSpvConstant()
4471// recursively walks. So, this function walks the "top" of the tree:
4472// - emit specialization constant-building instructions for specConstant
4473// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004474spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004475{
John Kessenich7cc0e282016-03-20 00:46:02 -06004476 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004477
qining4f4bb812016-04-03 23:55:17 -04004478 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004479 if (! node.getQualifier().specConstant) {
4480 // hand off to the non-spec-constant path
4481 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4482 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004483 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004484 nextConst, false);
4485 }
4486
4487 // We now know we have a specialization constant to build
4488
John Kessenichd94c0032016-05-30 19:29:40 -06004489 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004490 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4491 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4492 std::vector<spv::Id> dimConstId;
4493 for (int dim = 0; dim < 3; ++dim) {
4494 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4495 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4496 if (specConst)
4497 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4498 }
4499 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4500 }
4501
4502 // An AST node labelled as specialization constant should be a symbol node.
4503 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4504 if (auto* sn = node.getAsSymbolNode()) {
4505 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004506 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4507 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4508 // will set the builder into spec constant op instruction generating mode.
4509 sub_tree->traverse(this);
4510 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004511 } else if (auto* const_union_array = &sn->getConstArray()){
4512 int nextConst = 0;
4513 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004514 }
4515 }
qining4f4bb812016-04-03 23:55:17 -04004516
4517 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4518 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004519 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004520 exit(1);
4521 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004522}
4523
John Kessenich140f3df2015-06-26 16:58:36 -06004524// Use 'consts' as the flattened glslang source of scalar constants to recursively
4525// build the aggregate SPIR-V constant.
4526//
4527// If there are not enough elements present in 'consts', 0 will be substituted;
4528// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4529//
qining08408382016-03-21 09:51:37 -04004530spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004531{
4532 // vector of constants for SPIR-V
4533 std::vector<spv::Id> spvConsts;
4534
4535 // Type is used for struct and array constants
4536 spv::Id typeId = convertGlslangToSpvType(glslangType);
4537
4538 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004539 glslang::TType elementType(glslangType, 0);
4540 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004541 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004542 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004543 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004544 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004545 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004546 } else if (glslangType.getStruct()) {
4547 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4548 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004549 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004550 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004551 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4552 bool zero = nextConst >= consts.size();
4553 switch (glslangType.getBasicType()) {
4554 case glslang::EbtInt:
4555 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4556 break;
4557 case glslang::EbtUint:
4558 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4559 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004560 case glslang::EbtInt64:
4561 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4562 break;
4563 case glslang::EbtUint64:
4564 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4565 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004566 case glslang::EbtFloat:
4567 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4568 break;
4569 case glslang::EbtDouble:
4570 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4571 break;
4572 case glslang::EbtBool:
4573 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4574 break;
4575 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004576 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004577 break;
4578 }
4579 ++nextConst;
4580 }
4581 } else {
4582 // we have a non-aggregate (scalar) constant
4583 bool zero = nextConst >= consts.size();
4584 spv::Id scalar = 0;
4585 switch (glslangType.getBasicType()) {
4586 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004587 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004588 break;
4589 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004590 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004591 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004592 case glslang::EbtInt64:
4593 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4594 break;
4595 case glslang::EbtUint64:
4596 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4597 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004598 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004599 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004600 break;
4601 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004602 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004603 break;
4604 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004605 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004606 break;
4607 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004608 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004609 break;
4610 }
4611 ++nextConst;
4612 return scalar;
4613 }
4614
4615 return builder.makeCompositeConstant(typeId, spvConsts);
4616}
4617
John Kessenich7c1aa102015-10-15 13:29:11 -06004618// Return true if the node is a constant or symbol whose reading has no
4619// non-trivial observable cost or effect.
4620bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4621{
4622 // don't know what this is
4623 if (node == nullptr)
4624 return false;
4625
4626 // a constant is safe
4627 if (node->getAsConstantUnion() != nullptr)
4628 return true;
4629
4630 // not a symbol means non-trivial
4631 if (node->getAsSymbolNode() == nullptr)
4632 return false;
4633
4634 // a symbol, depends on what's being read
4635 switch (node->getType().getQualifier().storage) {
4636 case glslang::EvqTemporary:
4637 case glslang::EvqGlobal:
4638 case glslang::EvqIn:
4639 case glslang::EvqInOut:
4640 case glslang::EvqConst:
4641 case glslang::EvqConstReadOnly:
4642 case glslang::EvqUniform:
4643 return true;
4644 default:
4645 return false;
4646 }
qining25262b32016-05-06 17:25:16 -04004647}
John Kessenich7c1aa102015-10-15 13:29:11 -06004648
4649// A node is trivial if it is a single operation with no side effects.
4650// Error on the side of saying non-trivial.
4651// Return true if trivial.
4652bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4653{
4654 if (node == nullptr)
4655 return false;
4656
4657 // symbols and constants are trivial
4658 if (isTrivialLeaf(node))
4659 return true;
4660
4661 // otherwise, it needs to be a simple operation or one or two leaf nodes
4662
4663 // not a simple operation
4664 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4665 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4666 if (binaryNode == nullptr && unaryNode == nullptr)
4667 return false;
4668
4669 // not on leaf nodes
4670 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4671 return false;
4672
4673 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4674 return false;
4675 }
4676
4677 switch (node->getAsOperator()->getOp()) {
4678 case glslang::EOpLogicalNot:
4679 case glslang::EOpConvIntToBool:
4680 case glslang::EOpConvUintToBool:
4681 case glslang::EOpConvFloatToBool:
4682 case glslang::EOpConvDoubleToBool:
4683 case glslang::EOpEqual:
4684 case glslang::EOpNotEqual:
4685 case glslang::EOpLessThan:
4686 case glslang::EOpGreaterThan:
4687 case glslang::EOpLessThanEqual:
4688 case glslang::EOpGreaterThanEqual:
4689 case glslang::EOpIndexDirect:
4690 case glslang::EOpIndexDirectStruct:
4691 case glslang::EOpLogicalXor:
4692 case glslang::EOpAny:
4693 case glslang::EOpAll:
4694 return true;
4695 default:
4696 return false;
4697 }
4698}
4699
4700// Emit short-circuiting code, where 'right' is never evaluated unless
4701// the left side is true (for &&) or false (for ||).
4702spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4703{
4704 spv::Id boolTypeId = builder.makeBoolType();
4705
4706 // emit left operand
4707 builder.clearAccessChain();
4708 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004709 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004710
4711 // Operands to accumulate OpPhi operands
4712 std::vector<spv::Id> phiOperands;
4713 // accumulate left operand's phi information
4714 phiOperands.push_back(leftId);
4715 phiOperands.push_back(builder.getBuildPoint()->getId());
4716
4717 // Make the two kinds of operation symmetric with a "!"
4718 // || => emit "if (! left) result = right"
4719 // && => emit "if ( left) result = right"
4720 //
4721 // TODO: this runtime "not" for || could be avoided by adding functionality
4722 // to 'builder' to have an "else" without an "then"
4723 if (op == glslang::EOpLogicalOr)
4724 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4725
4726 // make an "if" based on the left value
4727 spv::Builder::If ifBuilder(leftId, builder);
4728
4729 // emit right operand as the "then" part of the "if"
4730 builder.clearAccessChain();
4731 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004732 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004733
4734 // accumulate left operand's phi information
4735 phiOperands.push_back(rightId);
4736 phiOperands.push_back(builder.getBuildPoint()->getId());
4737
4738 // finish the "if"
4739 ifBuilder.makeEndIf();
4740
4741 // phi together the two results
4742 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4743}
4744
Rex Xu9d93a232016-05-05 12:30:44 +08004745// Return type Id of the imported set of extended instructions corresponds to the name.
4746// Import this set if it has not been imported yet.
4747spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4748{
4749 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4750 return extBuiltinMap[name];
4751 else {
4752 builder.addExtensions(name);
4753 spv::Id extBuiltins = builder.import(name);
4754 extBuiltinMap[name] = extBuiltins;
4755 return extBuiltins;
4756 }
4757}
4758
John Kessenich140f3df2015-06-26 16:58:36 -06004759}; // end anonymous namespace
4760
4761namespace glslang {
4762
John Kessenich68d78fd2015-07-12 19:28:10 -06004763void GetSpirvVersion(std::string& version)
4764{
John Kessenich9e55f632015-07-15 10:03:39 -06004765 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004766 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004767 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004768 version = buf;
4769}
4770
John Kessenich140f3df2015-06-26 16:58:36 -06004771// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004772void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004773{
4774 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004775 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004776 for (int i = 0; i < (int)spirv.size(); ++i) {
4777 unsigned int word = spirv[i];
4778 out.write((const char*)&word, 4);
4779 }
4780 out.close();
4781}
4782
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004783// Write SPIR-V out to a text file with 32-bit hexadecimal words
4784void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4785{
4786 std::ofstream out;
4787 out.open(baseName, std::ios::binary | std::ios::out);
4788 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4789 const int WORDS_PER_LINE = 8;
4790 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4791 out << "\t";
4792 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4793 const unsigned int word = spirv[i + j];
4794 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4795 if (i + j + 1 < (int)spirv.size()) {
4796 out << ",";
4797 }
4798 }
4799 out << std::endl;
4800 }
4801 out.close();
4802}
4803
John Kessenich140f3df2015-06-26 16:58:36 -06004804//
4805// Set up the glslang traversal
4806//
4807void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4808{
Lei Zhang17535f72016-05-04 15:55:59 -04004809 spv::SpvBuildLogger logger;
4810 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004811}
4812
Lei Zhang17535f72016-05-04 15:55:59 -04004813void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004814{
John Kessenich140f3df2015-06-26 16:58:36 -06004815 TIntermNode* root = intermediate.getTreeRoot();
4816
4817 if (root == 0)
4818 return;
4819
4820 glslang::GetThreadPoolAllocator().push();
4821
Lei Zhang17535f72016-05-04 15:55:59 -04004822 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004823
4824 root->traverse(&it);
4825
4826 it.dumpSpv(spirv);
4827
4828 glslang::GetThreadPoolAllocator().pop();
4829}
4830
4831}; // end namespace glslang