blob: ddad636b84c59c7d444332c3fa874f8bb947d86e [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
John Kessenichf2b7f332016-09-01 17:05:23 -0600686bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700687{
John Kessenich7b9fa252016-01-21 18:56:57 -0700688 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600689 // - struct members might inherit from a struct declaration
690 // (note that non-block structs don't explicitly inherit,
691 // only implicitly, meaning no decoration involved)
692 // - affect decorations on the struct members
693 // (note smooth does not, and expecting something like volatile
694 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700695 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600696 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700697}
698
John Kessenich140f3df2015-06-26 16:58:36 -0600699//
700// Implement the TGlslangToSpvTraverser class.
701//
702
Lei Zhang17535f72016-05-04 15:55:59 -0400703TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
704 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
705 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600706 inMain(false), mainTerminated(false), linkageOnly(false),
707 glslangIntermediate(glslangIntermediate)
708{
709 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
710
711 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700712 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600713 stdBuiltins = builder.import("GLSL.std.450");
714 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700715 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
716 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600717
718 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600719 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
720 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600721 builder.addSourceExtension(it->c_str());
722
723 // Add the top-level modes for this shader.
724
John Kessenich92187592016-02-01 13:45:25 -0700725 if (glslangIntermediate->getXfbMode()) {
726 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700728 }
John Kessenich140f3df2015-06-26 16:58:36 -0600729
730 unsigned int mode;
731 switch (glslangIntermediate->getStage()) {
732 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600733 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600734 break;
735
736 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600737 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600738 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
739 break;
740
741 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600742 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600743 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700744 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
745 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
746 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600747 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600748 }
John Kessenich4016e382016-07-15 11:53:56 -0600749 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600750 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
751
John Kesseniche6903322015-10-13 16:29:02 -0600752 switch (glslangIntermediate->getVertexSpacing()) {
753 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
754 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
755 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600756 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600757 }
John Kessenich4016e382016-07-15 11:53:56 -0600758 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600759 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
760
761 switch (glslangIntermediate->getVertexOrder()) {
762 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
763 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600764 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600765 }
John Kessenich4016e382016-07-15 11:53:56 -0600766 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600767 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
768
769 if (glslangIntermediate->getPointMode())
770 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600771 break;
772
773 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600774 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600775 switch (glslangIntermediate->getInputPrimitive()) {
776 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
777 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
778 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700779 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600780 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600781 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600782 }
John Kessenich4016e382016-07-15 11:53:56 -0600783 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600784 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600785
John Kessenich140f3df2015-06-26 16:58:36 -0600786 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
787
788 switch (glslangIntermediate->getOutputPrimitive()) {
789 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
790 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
791 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600792 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600793 }
John Kessenich4016e382016-07-15 11:53:56 -0600794 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600795 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
796 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
797 break;
798
799 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600800 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600801 if (glslangIntermediate->getPixelCenterInteger())
802 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600803
John Kessenich140f3df2015-06-26 16:58:36 -0600804 if (glslangIntermediate->getOriginUpperLeft())
805 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600806 else
807 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600808
809 if (glslangIntermediate->getEarlyFragmentTests())
810 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
811
812 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600813 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
814 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600815 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600816 }
John Kessenich4016e382016-07-15 11:53:56 -0600817 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600818 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
819
820 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
821 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600822 break;
823
824 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600825 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600826 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
827 glslangIntermediate->getLocalSize(1),
828 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600829 break;
830
831 default:
832 break;
833 }
834
835}
836
John Kessenich7ba63412015-12-20 17:37:07 -0700837// Finish everything and dump
838void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
839{
840 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100841 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
842 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700843
qiningda397332016-03-09 19:54:03 -0500844 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700845 builder.dump(out);
846}
847
John Kessenich140f3df2015-06-26 16:58:36 -0600848TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
849{
850 if (! mainTerminated) {
851 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
852 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600853 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600854 }
855}
856
857//
858// Implement the traversal functions.
859//
860// Return true from interior nodes to have the external traversal
861// continue on to children. Return false if children were
862// already processed.
863//
864
865//
qining25262b32016-05-06 17:25:16 -0400866// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600867// - uniform/input reads
868// - output writes
869// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
870// - something simple that degenerates into the last bullet
871//
872void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
873{
qining75d1d802016-04-06 14:42:01 -0400874 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
875 if (symbol->getType().getQualifier().isSpecConstant())
876 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
877
John Kessenich140f3df2015-06-26 16:58:36 -0600878 // getSymbolId() will set up all the IO decorations on the first call.
879 // Formal function parameters were mapped during makeFunctions().
880 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700881
882 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
883 if (builder.isPointer(id)) {
884 spv::StorageClass sc = builder.getStorageClass(id);
885 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
886 iOSet.insert(id);
887 }
888
889 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700890 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600891 // Prepare to generate code for the access
892
893 // L-value chains will be computed left to right. We're on the symbol now,
894 // which is the left-most part of the access chain, so now is "clear" time,
895 // followed by setting the base.
896 builder.clearAccessChain();
897
898 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700899 // except for
900 // A) "const in" arguments to a function, which are an intermediate object.
901 // See comments in handleUserFunctionCall().
902 // B) Specialization constants (normal constant don't even come in as a variable),
903 // These are also pure R-values.
904 glslang::TQualifier qualifier = symbol->getQualifier();
905 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
906 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600907 builder.setAccessChainRValue(id);
908 else
909 builder.setAccessChainLValue(id);
910 }
911}
912
913bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
914{
qining40887662016-04-03 22:20:42 -0400915 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
916 if (node->getType().getQualifier().isSpecConstant())
917 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
918
John Kessenich140f3df2015-06-26 16:58:36 -0600919 // First, handle special cases
920 switch (node->getOp()) {
921 case glslang::EOpAssign:
922 case glslang::EOpAddAssign:
923 case glslang::EOpSubAssign:
924 case glslang::EOpMulAssign:
925 case glslang::EOpVectorTimesMatrixAssign:
926 case glslang::EOpVectorTimesScalarAssign:
927 case glslang::EOpMatrixTimesScalarAssign:
928 case glslang::EOpMatrixTimesMatrixAssign:
929 case glslang::EOpDivAssign:
930 case glslang::EOpModAssign:
931 case glslang::EOpAndAssign:
932 case glslang::EOpInclusiveOrAssign:
933 case glslang::EOpExclusiveOrAssign:
934 case glslang::EOpLeftShiftAssign:
935 case glslang::EOpRightShiftAssign:
936 // A bin-op assign "a += b" means the same thing as "a = a + b"
937 // where a is evaluated before b. For a simple assignment, GLSL
938 // says to evaluate the left before the right. So, always, left
939 // node then right node.
940 {
941 // get the left l-value, save it away
942 builder.clearAccessChain();
943 node->getLeft()->traverse(this);
944 spv::Builder::AccessChain lValue = builder.getAccessChain();
945
946 // evaluate the right
947 builder.clearAccessChain();
948 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700949 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600950
951 if (node->getOp() != glslang::EOpAssign) {
952 // the left is also an r-value
953 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700954 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600957 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400958 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600959 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
960 node->getType().getBasicType());
961
962 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700963 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
965
966 // store the result
967 builder.setAccessChain(lValue);
John Kessenichf2b7f332016-09-01 17:05:23 -0600968 if (builder.isStructType(builder.getTypeId(rValue))) {
969 //spv::Id lType = builder.getContainedTypeId(builder.getTypeId(builder.accessChainGetLValue()));
970 //spv::Id rType = builder.getTypeId(rValue);
971 //if (lType != rType) {
972 // TODO: do member-wise copy instead, this is current issue
973 // https://github.com/KhronosGroup/glslang/issues/304
974 //} else
975 accessChainStore(node->getType(), rValue);
976 } else
977 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600978
979 // assignments are expressions having an rValue after they are evaluated...
980 builder.clearAccessChain();
981 builder.setAccessChainRValue(rValue);
982 }
983 return false;
984 case glslang::EOpIndexDirect:
985 case glslang::EOpIndexDirectStruct:
986 {
987 // Get the left part of the access chain.
988 node->getLeft()->traverse(this);
989
990 // Add the next element in the chain
991
David Netoa901ffe2016-06-08 14:11:40 +0100992 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600993 if (! node->getLeft()->getType().isArray() &&
994 node->getLeft()->getType().isVector() &&
995 node->getOp() == glslang::EOpIndexDirect) {
996 // This is essentially a hard-coded vector swizzle of size 1,
997 // so short circuit the access-chain stuff with a swizzle.
998 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100999 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001000 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001001 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001002 int spvIndex = glslangIndex;
1003 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1004 node->getOp() == glslang::EOpIndexDirectStruct)
1005 {
1006 // This may be, e.g., an anonymous block-member selection, which generally need
1007 // index remapping due to hidden members in anonymous blocks.
1008 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1009 assert(remapper.size() > 0);
1010 spvIndex = remapper[glslangIndex];
1011 }
John Kessenichebb50532016-05-16 19:22:05 -06001012
David Netoa901ffe2016-06-08 14:11:40 +01001013 // normal case for indexing array or structure or block
1014 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1015
1016 // Add capabilities here for accessing PointSize and clip/cull distance.
1017 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001018 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001019 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001020 }
1021 }
1022 return false;
1023 case glslang::EOpIndexIndirect:
1024 {
1025 // Structure or array or vector indirection.
1026 // Will use native SPIR-V access-chain for struct and array indirection;
1027 // matrices are arrays of vectors, so will also work for a matrix.
1028 // Will use the access chain's 'component' for variable index into a vector.
1029
1030 // This adapter is building access chains left to right.
1031 // Set up the access chain to the left.
1032 node->getLeft()->traverse(this);
1033
1034 // save it so that computing the right side doesn't trash it
1035 spv::Builder::AccessChain partial = builder.getAccessChain();
1036
1037 // compute the next index in the chain
1038 builder.clearAccessChain();
1039 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001040 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001041
1042 // restore the saved access chain
1043 builder.setAccessChain(partial);
1044
1045 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001046 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001047 else
John Kessenichfa668da2015-09-13 14:46:30 -06001048 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001049 }
1050 return false;
1051 case glslang::EOpVectorSwizzle:
1052 {
1053 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001054 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001055 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001056 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001057 }
1058 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001059 case glslang::EOpLogicalOr:
1060 case glslang::EOpLogicalAnd:
1061 {
1062
1063 // These may require short circuiting, but can sometimes be done as straight
1064 // binary operations. The right operand must be short circuited if it has
1065 // side effects, and should probably be if it is complex.
1066 if (isTrivial(node->getRight()->getAsTyped()))
1067 break; // handle below as a normal binary operation
1068 // otherwise, we need to do dynamic short circuiting on the right operand
1069 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1070 builder.clearAccessChain();
1071 builder.setAccessChainRValue(result);
1072 }
1073 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001074 default:
1075 break;
1076 }
1077
1078 // Assume generic binary op...
1079
John Kessenich32cfd492016-02-02 12:37:46 -07001080 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001081 builder.clearAccessChain();
1082 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001083 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001084
John Kessenich32cfd492016-02-02 12:37:46 -07001085 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001086 builder.clearAccessChain();
1087 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001088 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001089
John Kessenich32cfd492016-02-02 12:37:46 -07001090 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001091 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001092 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001093 convertGlslangToSpvType(node->getType()), left, right,
1094 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001095
John Kessenich50e57562015-12-21 21:21:11 -07001096 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001097 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001098 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001099 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001100 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001101 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001102 return false;
1103 }
John Kessenich140f3df2015-06-26 16:58:36 -06001104}
1105
1106bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1107{
qining40887662016-04-03 22:20:42 -04001108 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1109 if (node->getType().getQualifier().isSpecConstant())
1110 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1111
John Kessenichfc51d282015-08-19 13:34:18 -06001112 spv::Id result = spv::NoResult;
1113
1114 // try texturing first
1115 result = createImageTextureFunctionCall(node);
1116 if (result != spv::NoResult) {
1117 builder.clearAccessChain();
1118 builder.setAccessChainRValue(result);
1119
1120 return false; // done with this node
1121 }
1122
1123 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001124
1125 if (node->getOp() == glslang::EOpArrayLength) {
1126 // Quite special; won't want to evaluate the operand.
1127
1128 // Normal .length() would have been constant folded by the front-end.
1129 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001130 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001131 assert(node->getOperand()->getType().isRuntimeSizedArray());
1132 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1133 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001134 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1135 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001136
1137 builder.clearAccessChain();
1138 builder.setAccessChainRValue(length);
1139
1140 return false;
1141 }
1142
John Kessenichfc51d282015-08-19 13:34:18 -06001143 // Start by evaluating the operand
1144
John Kessenich8c8505c2016-07-26 12:50:38 -06001145 // Does it need a swizzle inversion? If so, evaluation is inverted;
1146 // operate first on the swizzle base, then apply the swizzle.
1147 spv::Id invertedType = spv::NoType;
1148 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1149 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1150 invertedType = getInvertedSwizzleType(*node->getOperand());
1151
John Kessenich140f3df2015-06-26 16:58:36 -06001152 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001153 if (invertedType != spv::NoType)
1154 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1155 else
1156 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001157
Rex Xufc618912015-09-09 16:42:49 +08001158 spv::Id operand = spv::NoResult;
1159
1160 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1161 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001162 node->getOp() == glslang::EOpAtomicCounter ||
1163 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001164 operand = builder.accessChainGetLValue(); // Special case l-value operands
1165 else
John Kessenich32cfd492016-02-02 12:37:46 -07001166 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001167
John Kessenichf6640762016-08-01 19:44:00 -06001168 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001169 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001170
1171 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001172 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001173 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 // if not, then possibly an operation
1176 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001177 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001178
1179 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001180 if (invertedType)
1181 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1182
John Kessenich140f3df2015-06-26 16:58:36 -06001183 builder.clearAccessChain();
1184 builder.setAccessChainRValue(result);
1185
1186 return false; // done with this node
1187 }
1188
1189 // it must be a special case, check...
1190 switch (node->getOp()) {
1191 case glslang::EOpPostIncrement:
1192 case glslang::EOpPostDecrement:
1193 case glslang::EOpPreIncrement:
1194 case glslang::EOpPreDecrement:
1195 {
1196 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001197 spv::Id one = 0;
1198 if (node->getBasicType() == glslang::EbtFloat)
1199 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001200 else if (node->getBasicType() == glslang::EbtDouble)
1201 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001202 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1203 one = builder.makeInt64Constant(1);
1204 else
1205 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001206 glslang::TOperator op;
1207 if (node->getOp() == glslang::EOpPreIncrement ||
1208 node->getOp() == glslang::EOpPostIncrement)
1209 op = glslang::EOpAdd;
1210 else
1211 op = glslang::EOpSub;
1212
John Kessenichf6640762016-08-01 19:44:00 -06001213 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001214 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001215 convertGlslangToSpvType(node->getType()), operand, one,
1216 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001217 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001218
1219 // The result of operation is always stored, but conditionally the
1220 // consumed result. The consumed result is always an r-value.
1221 builder.accessChainStore(result);
1222 builder.clearAccessChain();
1223 if (node->getOp() == glslang::EOpPreIncrement ||
1224 node->getOp() == glslang::EOpPreDecrement)
1225 builder.setAccessChainRValue(result);
1226 else
1227 builder.setAccessChainRValue(operand);
1228 }
1229
1230 return false;
1231
1232 case glslang::EOpEmitStreamVertex:
1233 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1234 return false;
1235 case glslang::EOpEndStreamPrimitive:
1236 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1237 return false;
1238
1239 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001240 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001241 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001242 }
John Kessenich140f3df2015-06-26 16:58:36 -06001243}
1244
1245bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1246{
qining27e04a02016-04-14 16:40:20 -04001247 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1248 if (node->getType().getQualifier().isSpecConstant())
1249 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1250
John Kessenichfc51d282015-08-19 13:34:18 -06001251 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001252 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1253 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001254
1255 // try texturing
1256 result = createImageTextureFunctionCall(node);
1257 if (result != spv::NoResult) {
1258 builder.clearAccessChain();
1259 builder.setAccessChainRValue(result);
1260
1261 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001262 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001263 // "imageStore" is a special case, which has no result
1264 return false;
1265 }
John Kessenichfc51d282015-08-19 13:34:18 -06001266
John Kessenich140f3df2015-06-26 16:58:36 -06001267 glslang::TOperator binOp = glslang::EOpNull;
1268 bool reduceComparison = true;
1269 bool isMatrix = false;
1270 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001271 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001272
1273 assert(node->getOp());
1274
John Kessenichf6640762016-08-01 19:44:00 -06001275 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001276
1277 switch (node->getOp()) {
1278 case glslang::EOpSequence:
1279 {
1280 if (preVisit)
1281 ++sequenceDepth;
1282 else
1283 --sequenceDepth;
1284
1285 if (sequenceDepth == 1) {
1286 // If this is the parent node of all the functions, we want to see them
1287 // early, so all call points have actual SPIR-V functions to reference.
1288 // In all cases, still let the traverser visit the children for us.
1289 makeFunctions(node->getAsAggregate()->getSequence());
1290
1291 // Also, we want all globals initializers to go into the entry of main(), before
1292 // anything else gets there, so visit out of order, doing them all now.
1293 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1294
1295 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1296 // so do them manually.
1297 visitFunctions(node->getAsAggregate()->getSequence());
1298
1299 return false;
1300 }
1301
1302 return true;
1303 }
1304 case glslang::EOpLinkerObjects:
1305 {
1306 if (visit == glslang::EvPreVisit)
1307 linkageOnly = true;
1308 else
1309 linkageOnly = false;
1310
1311 return true;
1312 }
1313 case glslang::EOpComma:
1314 {
1315 // processing from left to right naturally leaves the right-most
1316 // lying around in the access chain
1317 glslang::TIntermSequence& glslangOperands = node->getSequence();
1318 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1319 glslangOperands[i]->traverse(this);
1320
1321 return false;
1322 }
1323 case glslang::EOpFunction:
1324 if (visit == glslang::EvPreVisit) {
1325 if (isShaderEntrypoint(node)) {
1326 inMain = true;
1327 builder.setBuildPoint(shaderEntry->getLastBlock());
1328 } else {
1329 handleFunctionEntry(node);
1330 }
1331 } else {
1332 if (inMain)
1333 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001334 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001335 inMain = false;
1336 }
1337
1338 return true;
1339 case glslang::EOpParameters:
1340 // Parameters will have been consumed by EOpFunction processing, but not
1341 // the body, so we still visited the function node's children, making this
1342 // child redundant.
1343 return false;
1344 case glslang::EOpFunctionCall:
1345 {
1346 if (node->isUserDefined())
1347 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001348 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1349 if (result) {
1350 builder.clearAccessChain();
1351 builder.setAccessChainRValue(result);
1352 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001353 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001354
1355 return false;
1356 }
1357 case glslang::EOpConstructMat2x2:
1358 case glslang::EOpConstructMat2x3:
1359 case glslang::EOpConstructMat2x4:
1360 case glslang::EOpConstructMat3x2:
1361 case glslang::EOpConstructMat3x3:
1362 case glslang::EOpConstructMat3x4:
1363 case glslang::EOpConstructMat4x2:
1364 case glslang::EOpConstructMat4x3:
1365 case glslang::EOpConstructMat4x4:
1366 case glslang::EOpConstructDMat2x2:
1367 case glslang::EOpConstructDMat2x3:
1368 case glslang::EOpConstructDMat2x4:
1369 case glslang::EOpConstructDMat3x2:
1370 case glslang::EOpConstructDMat3x3:
1371 case glslang::EOpConstructDMat3x4:
1372 case glslang::EOpConstructDMat4x2:
1373 case glslang::EOpConstructDMat4x3:
1374 case glslang::EOpConstructDMat4x4:
1375 isMatrix = true;
1376 // fall through
1377 case glslang::EOpConstructFloat:
1378 case glslang::EOpConstructVec2:
1379 case glslang::EOpConstructVec3:
1380 case glslang::EOpConstructVec4:
1381 case glslang::EOpConstructDouble:
1382 case glslang::EOpConstructDVec2:
1383 case glslang::EOpConstructDVec3:
1384 case glslang::EOpConstructDVec4:
1385 case glslang::EOpConstructBool:
1386 case glslang::EOpConstructBVec2:
1387 case glslang::EOpConstructBVec3:
1388 case glslang::EOpConstructBVec4:
1389 case glslang::EOpConstructInt:
1390 case glslang::EOpConstructIVec2:
1391 case glslang::EOpConstructIVec3:
1392 case glslang::EOpConstructIVec4:
1393 case glslang::EOpConstructUint:
1394 case glslang::EOpConstructUVec2:
1395 case glslang::EOpConstructUVec3:
1396 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001397 case glslang::EOpConstructInt64:
1398 case glslang::EOpConstructI64Vec2:
1399 case glslang::EOpConstructI64Vec3:
1400 case glslang::EOpConstructI64Vec4:
1401 case glslang::EOpConstructUint64:
1402 case glslang::EOpConstructU64Vec2:
1403 case glslang::EOpConstructU64Vec3:
1404 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001405 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001406 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001407 {
1408 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001409 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001410 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001411 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001412 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001413 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001414 std::vector<spv::Id> constituents;
1415 for (int c = 0; c < (int)arguments.size(); ++c)
1416 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001417 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001418 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001419 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001420 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001421 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001422
1423 builder.clearAccessChain();
1424 builder.setAccessChainRValue(constructed);
1425
1426 return false;
1427 }
1428
1429 // These six are component-wise compares with component-wise results.
1430 // Forward on to createBinaryOperation(), requesting a vector result.
1431 case glslang::EOpLessThan:
1432 case glslang::EOpGreaterThan:
1433 case glslang::EOpLessThanEqual:
1434 case glslang::EOpGreaterThanEqual:
1435 case glslang::EOpVectorEqual:
1436 case glslang::EOpVectorNotEqual:
1437 {
1438 // Map the operation to a binary
1439 binOp = node->getOp();
1440 reduceComparison = false;
1441 switch (node->getOp()) {
1442 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1443 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1444 default: binOp = node->getOp(); break;
1445 }
1446
1447 break;
1448 }
1449 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001450 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001451 binOp = glslang::EOpMul;
1452 break;
1453 case glslang::EOpOuterProduct:
1454 // two vectors multiplied to make a matrix
1455 binOp = glslang::EOpOuterProduct;
1456 break;
1457 case glslang::EOpDot:
1458 {
qining25262b32016-05-06 17:25:16 -04001459 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001460 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001461 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001462 binOp = glslang::EOpMul;
1463 break;
1464 }
1465 case glslang::EOpMod:
1466 // when an aggregate, this is the floating-point mod built-in function,
1467 // which can be emitted by the one in createBinaryOperation()
1468 binOp = glslang::EOpMod;
1469 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001470 case glslang::EOpEmitVertex:
1471 case glslang::EOpEndPrimitive:
1472 case glslang::EOpBarrier:
1473 case glslang::EOpMemoryBarrier:
1474 case glslang::EOpMemoryBarrierAtomicCounter:
1475 case glslang::EOpMemoryBarrierBuffer:
1476 case glslang::EOpMemoryBarrierImage:
1477 case glslang::EOpMemoryBarrierShared:
1478 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001479 case glslang::EOpAllMemoryBarrierWithGroupSync:
1480 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1481 case glslang::EOpWorkgroupMemoryBarrier:
1482 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001483 noReturnValue = true;
1484 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1485 break;
1486
John Kessenich426394d2015-07-23 10:22:48 -06001487 case glslang::EOpAtomicAdd:
1488 case glslang::EOpAtomicMin:
1489 case glslang::EOpAtomicMax:
1490 case glslang::EOpAtomicAnd:
1491 case glslang::EOpAtomicOr:
1492 case glslang::EOpAtomicXor:
1493 case glslang::EOpAtomicExchange:
1494 case glslang::EOpAtomicCompSwap:
1495 atomic = true;
1496 break;
1497
John Kessenich140f3df2015-06-26 16:58:36 -06001498 default:
1499 break;
1500 }
1501
1502 //
1503 // See if it maps to a regular operation.
1504 //
John Kessenich140f3df2015-06-26 16:58:36 -06001505 if (binOp != glslang::EOpNull) {
1506 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1507 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1508 assert(left && right);
1509
1510 builder.clearAccessChain();
1511 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001512 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001513
1514 builder.clearAccessChain();
1515 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001516 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001517
qining25262b32016-05-06 17:25:16 -04001518 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001519 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001520 left->getType().getBasicType(), reduceComparison);
1521
1522 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001523 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001524 builder.clearAccessChain();
1525 builder.setAccessChainRValue(result);
1526
1527 return false;
1528 }
1529
John Kessenich426394d2015-07-23 10:22:48 -06001530 //
1531 // Create the list of operands.
1532 //
John Kessenich140f3df2015-06-26 16:58:36 -06001533 glslang::TIntermSequence& glslangOperands = node->getSequence();
1534 std::vector<spv::Id> operands;
1535 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001536 // special case l-value operands; there are just a few
1537 bool lvalue = false;
1538 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001539 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001540 case glslang::EOpModf:
1541 if (arg == 1)
1542 lvalue = true;
1543 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001544 case glslang::EOpInterpolateAtSample:
1545 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001546#ifdef AMD_EXTENSIONS
1547 case glslang::EOpInterpolateAtVertex:
1548#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001549 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001550 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001551
1552 // Does it need a swizzle inversion? If so, evaluation is inverted;
1553 // operate first on the swizzle base, then apply the swizzle.
1554 if (glslangOperands[0]->getAsOperator() &&
1555 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1556 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1557 }
Rex Xu7a26c172015-12-08 17:12:09 +08001558 break;
Rex Xud4782c12015-09-06 16:30:11 +08001559 case glslang::EOpAtomicAdd:
1560 case glslang::EOpAtomicMin:
1561 case glslang::EOpAtomicMax:
1562 case glslang::EOpAtomicAnd:
1563 case glslang::EOpAtomicOr:
1564 case glslang::EOpAtomicXor:
1565 case glslang::EOpAtomicExchange:
1566 case glslang::EOpAtomicCompSwap:
1567 if (arg == 0)
1568 lvalue = true;
1569 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001570 case glslang::EOpAddCarry:
1571 case glslang::EOpSubBorrow:
1572 if (arg == 2)
1573 lvalue = true;
1574 break;
1575 case glslang::EOpUMulExtended:
1576 case glslang::EOpIMulExtended:
1577 if (arg >= 2)
1578 lvalue = true;
1579 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001580 default:
1581 break;
1582 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001583 builder.clearAccessChain();
1584 if (invertedType != spv::NoType && arg == 0)
1585 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1586 else
1587 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001588 if (lvalue)
1589 operands.push_back(builder.accessChainGetLValue());
1590 else
John Kessenich32cfd492016-02-02 12:37:46 -07001591 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001592 }
John Kessenich426394d2015-07-23 10:22:48 -06001593
1594 if (atomic) {
1595 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001596 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001597 } else {
1598 // Pass through to generic operations.
1599 switch (glslangOperands.size()) {
1600 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001601 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001602 break;
1603 case 1:
qining25262b32016-05-06 17:25:16 -04001604 result = createUnaryOperation(
1605 node->getOp(), precision,
1606 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001607 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001608 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001609 break;
1610 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001611 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001612 break;
1613 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001614 if (invertedType)
1615 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001616 }
1617
1618 if (noReturnValue)
1619 return false;
1620
1621 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001622 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001623 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001624 } else {
1625 builder.clearAccessChain();
1626 builder.setAccessChainRValue(result);
1627 return false;
1628 }
1629}
1630
1631bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1632{
1633 // This path handles both if-then-else and ?:
1634 // The if-then-else has a node type of void, while
1635 // ?: has a non-void node type
1636 spv::Id result = 0;
1637 if (node->getBasicType() != glslang::EbtVoid) {
1638 // don't handle this as just on-the-fly temporaries, because there will be two names
1639 // and better to leave SSA to later passes
1640 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1641 }
1642
1643 // emit the condition before doing anything with selection
1644 node->getCondition()->traverse(this);
1645
1646 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001647 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001648
1649 if (node->getTrueBlock()) {
1650 // emit the "then" statement
1651 node->getTrueBlock()->traverse(this);
1652 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001653 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001654 }
1655
1656 if (node->getFalseBlock()) {
1657 ifBuilder.makeBeginElse();
1658 // emit the "else" statement
1659 node->getFalseBlock()->traverse(this);
1660 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001661 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001662 }
1663
1664 ifBuilder.makeEndIf();
1665
1666 if (result) {
1667 // GLSL only has r-values as the result of a :?, but
1668 // if we have an l-value, that can be more efficient if it will
1669 // become the base of a complex r-value expression, because the
1670 // next layer copies r-values into memory to use the access-chain mechanism
1671 builder.clearAccessChain();
1672 builder.setAccessChainLValue(result);
1673 }
1674
1675 return false;
1676}
1677
1678bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1679{
1680 // emit and get the condition before doing anything with switch
1681 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001682 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001683
1684 // browse the children to sort out code segments
1685 int defaultSegment = -1;
1686 std::vector<TIntermNode*> codeSegments;
1687 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1688 std::vector<int> caseValues;
1689 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1690 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1691 TIntermNode* child = *c;
1692 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001693 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001694 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001695 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001696 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1697 } else
1698 codeSegments.push_back(child);
1699 }
1700
qining25262b32016-05-06 17:25:16 -04001701 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001702 // statements between the last case and the end of the switch statement
1703 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1704 (int)codeSegments.size() == defaultSegment)
1705 codeSegments.push_back(nullptr);
1706
1707 // make the switch statement
1708 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001709 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001710
1711 // emit all the code in the segments
1712 breakForLoop.push(false);
1713 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1714 builder.nextSwitchSegment(segmentBlocks, s);
1715 if (codeSegments[s])
1716 codeSegments[s]->traverse(this);
1717 else
1718 builder.addSwitchBreak();
1719 }
1720 breakForLoop.pop();
1721
1722 builder.endSwitch(segmentBlocks);
1723
1724 return false;
1725}
1726
1727void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1728{
1729 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001730 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001731
1732 builder.clearAccessChain();
1733 builder.setAccessChainRValue(constant);
1734}
1735
1736bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1737{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001738 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001739 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001740 // Spec requires back edges to target header blocks, and every header block
1741 // must dominate its merge block. Make a header block first to ensure these
1742 // conditions are met. By definition, it will contain OpLoopMerge, followed
1743 // by a block-ending branch. But we don't want to put any other body/test
1744 // instructions in it, since the body/test may have arbitrary instructions,
1745 // including merges of its own.
1746 builder.setBuildPoint(&blocks.head);
1747 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001748 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001749 spv::Block& test = builder.makeNewBlock();
1750 builder.createBranch(&test);
1751
1752 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001753 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001754 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001755 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001756 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1757
1758 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001759 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001760 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001761 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001762 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001763 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001764
1765 builder.setBuildPoint(&blocks.continue_target);
1766 if (node->getTerminal())
1767 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001768 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001769 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001770 builder.createBranch(&blocks.body);
1771
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001772 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001773 builder.setBuildPoint(&blocks.body);
1774 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001775 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001776 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001777 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001778
1779 builder.setBuildPoint(&blocks.continue_target);
1780 if (node->getTerminal())
1781 node->getTerminal()->traverse(this);
1782 if (node->getTest()) {
1783 node->getTest()->traverse(this);
1784 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001785 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001786 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001787 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001788 // TODO: unless there was a break/return/discard instruction
1789 // somewhere in the body, this is an infinite loop, so we should
1790 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001791 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001792 }
John Kessenich140f3df2015-06-26 16:58:36 -06001793 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001794 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001795 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001796 return false;
1797}
1798
1799bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1800{
1801 if (node->getExpression())
1802 node->getExpression()->traverse(this);
1803
1804 switch (node->getFlowOp()) {
1805 case glslang::EOpKill:
1806 builder.makeDiscard();
1807 break;
1808 case glslang::EOpBreak:
1809 if (breakForLoop.top())
1810 builder.createLoopExit();
1811 else
1812 builder.addSwitchBreak();
1813 break;
1814 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001815 builder.createLoopContinue();
1816 break;
1817 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001818 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001819 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001820 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001821 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001822
1823 builder.clearAccessChain();
1824 break;
1825
1826 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001827 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001828 break;
1829 }
1830
1831 return false;
1832}
1833
1834spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1835{
qining25262b32016-05-06 17:25:16 -04001836 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001837 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001838 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001839 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001840 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001841 }
1842
1843 // Now, handle actual variables
1844 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1845 spv::Id spvType = convertGlslangToSpvType(node->getType());
1846
1847 const char* name = node->getName().c_str();
1848 if (glslang::IsAnonymous(name))
1849 name = "";
1850
1851 return builder.createVariable(storageClass, spvType, name);
1852}
1853
1854// Return type Id of the sampled type.
1855spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1856{
1857 switch (sampler.type) {
1858 case glslang::EbtFloat: return builder.makeFloatType(32);
1859 case glslang::EbtInt: return builder.makeIntType(32);
1860 case glslang::EbtUint: return builder.makeUintType(32);
1861 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001862 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001863 return builder.makeFloatType(32);
1864 }
1865}
1866
John Kessenich8c8505c2016-07-26 12:50:38 -06001867// If node is a swizzle operation, return the type that should be used if
1868// the swizzle base is first consumed by another operation, before the swizzle
1869// is applied.
1870spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1871{
1872 if (node.getAsOperator() &&
1873 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1874 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1875 else
1876 return spv::NoType;
1877}
1878
1879// When inverting a swizzle with a parent op, this function
1880// will apply the swizzle operation to a completed parent operation.
1881spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1882{
1883 std::vector<unsigned> swizzle;
1884 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1885 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1886}
1887
1888
1889// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1890void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1891{
1892 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1893 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1894 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1895}
1896
John Kessenich3ac051e2015-12-20 11:29:16 -07001897// Convert from a glslang type to an SPV type, by calling into a
1898// recursive version of this function. This establishes the inherited
1899// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001900spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1901{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001902 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001903}
1904
1905// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001906// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001907// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001908spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001909{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001910 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001911
1912 switch (type.getBasicType()) {
1913 case glslang::EbtVoid:
1914 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001915 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001916 break;
1917 case glslang::EbtFloat:
1918 spvType = builder.makeFloatType(32);
1919 break;
1920 case glslang::EbtDouble:
1921 spvType = builder.makeFloatType(64);
1922 break;
1923 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001924 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1925 // a 32-bit int where non-0 means true.
1926 if (explicitLayout != glslang::ElpNone)
1927 spvType = builder.makeUintType(32);
1928 else
1929 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001930 break;
1931 case glslang::EbtInt:
1932 spvType = builder.makeIntType(32);
1933 break;
1934 case glslang::EbtUint:
1935 spvType = builder.makeUintType(32);
1936 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001937 case glslang::EbtInt64:
1938 builder.addCapability(spv::CapabilityInt64);
1939 spvType = builder.makeIntType(64);
1940 break;
1941 case glslang::EbtUint64:
1942 builder.addCapability(spv::CapabilityInt64);
1943 spvType = builder.makeUintType(64);
1944 break;
John Kessenich426394d2015-07-23 10:22:48 -06001945 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001946 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001947 spvType = builder.makeUintType(32);
1948 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001949 case glslang::EbtSampler:
1950 {
1951 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001952 if (sampler.sampler) {
1953 // pure sampler
1954 spvType = builder.makeSamplerType();
1955 } else {
1956 // an image is present, make its type
1957 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1958 sampler.image ? 2 : 1, TranslateImageFormat(type));
1959 if (sampler.combined) {
1960 // already has both image and sampler, make the combined type
1961 spvType = builder.makeSampledImageType(spvType);
1962 }
John Kessenich55e7d112015-11-15 21:33:39 -07001963 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001964 }
John Kessenich140f3df2015-06-26 16:58:36 -06001965 break;
1966 case glslang::EbtStruct:
1967 case glslang::EbtBlock:
1968 {
1969 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001970 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001971
1972 // Try to share structs for different layouts, but not yet for other
1973 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06001974 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001975 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001976 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001977 break;
1978
1979 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001980 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001981 memberRemapper[glslangMembers].resize(glslangMembers->size());
1982 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001983 }
1984 break;
1985 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001986 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001987 break;
1988 }
1989
1990 if (type.isMatrix())
1991 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1992 else {
1993 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1994 if (type.getVectorSize() > 1)
1995 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1996 }
1997
1998 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001999 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2000
John Kessenichc9a80832015-09-12 12:17:44 -06002001 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002002 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002003 // We need to decorate array strides for types needing explicit layout, except blocks.
2004 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002005 // Use a dummy glslang type for querying internal strides of
2006 // arrays of arrays, but using just a one-dimensional array.
2007 glslang::TType simpleArrayType(type, 0); // deference type of the array
2008 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2009 simpleArrayType.getArraySizes().dereference();
2010
2011 // Will compute the higher-order strides here, rather than making a whole
2012 // pile of types and doing repetitive recursion on their contents.
2013 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2014 }
John Kessenichf8842e52016-01-04 19:22:56 -07002015
2016 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002017 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002018 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002019 if (stride > 0)
2020 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002021 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002022 }
2023 } else {
2024 // single-dimensional array, and don't yet have stride
2025
John Kessenichf8842e52016-01-04 19:22:56 -07002026 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002027 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2028 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002029 }
John Kessenich31ed4832015-09-09 17:51:38 -06002030
John Kessenichc9a80832015-09-12 12:17:44 -06002031 // Do the outer dimension, which might not be known for a runtime-sized array
2032 if (type.isRuntimeSizedArray()) {
2033 spvType = builder.makeRuntimeArray(spvType);
2034 } else {
2035 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002036 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002037 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002038 if (stride > 0)
2039 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002040 }
2041
2042 return spvType;
2043}
2044
John Kessenich6090df02016-06-30 21:18:02 -06002045
2046// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2047// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2048// Mutually recursive with convertGlslangToSpvType().
2049spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2050 const glslang::TTypeList* glslangMembers,
2051 glslang::TLayoutPacking explicitLayout,
2052 const glslang::TQualifier& qualifier)
2053{
2054 // Create a vector of struct types for SPIR-V to consume
2055 std::vector<spv::Id> spvMembers;
2056 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2057 int locationOffset = 0; // for use across struct members, when they are called recursively
2058 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2059 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2060 if (glslangMember.hiddenMember()) {
2061 ++memberDelta;
2062 if (type.getBasicType() == glslang::EbtBlock)
2063 memberRemapper[glslangMembers][i] = -1;
2064 } else {
2065 if (type.getBasicType() == glslang::EbtBlock)
2066 memberRemapper[glslangMembers][i] = i - memberDelta;
2067 // modify just this child's view of the qualifier
2068 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2069 InheritQualifiers(memberQualifier, qualifier);
2070
2071 // manually inherit location; it's more complex
2072 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2073 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2074 if (qualifier.hasLocation())
2075 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2076
2077 // recurse
2078 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2079 }
2080 }
2081
2082 // Make the SPIR-V type
2083 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002084 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002085 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2086
2087 // Decorate it
2088 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2089
2090 return spvType;
2091}
2092
2093void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2094 const glslang::TTypeList* glslangMembers,
2095 glslang::TLayoutPacking explicitLayout,
2096 const glslang::TQualifier& qualifier,
2097 spv::Id spvType)
2098{
2099 // Name and decorate the non-hidden members
2100 int offset = -1;
2101 int locationOffset = 0; // for use within the members of this struct
2102 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2103 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2104 int member = i;
2105 if (type.getBasicType() == glslang::EbtBlock)
2106 member = memberRemapper[glslangMembers][i];
2107
2108 // modify just this child's view of the qualifier
2109 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2110 InheritQualifiers(memberQualifier, qualifier);
2111
2112 // using -1 above to indicate a hidden member
2113 if (member >= 0) {
2114 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2115 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2116 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2117 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2118 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2119 if (type.getBasicType() == glslang::EbtBlock) {
2120 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2121 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2122 }
2123 }
2124 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2125
2126 if (qualifier.storage == glslang::EvqBuffer) {
2127 std::vector<spv::Decoration> memory;
2128 TranslateMemoryDecoration(memberQualifier, memory);
2129 for (unsigned int i = 0; i < memory.size(); ++i)
2130 addMemberDecoration(spvType, member, memory[i]);
2131 }
2132
John Kessenich2f47bc92016-06-30 21:47:35 -06002133 // Compute location decoration; tricky based on whether inheritance is at play and
2134 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002135 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2136 // probably move to the linker stage of the front end proper, and just have the
2137 // answer sitting already distributed throughout the individual member locations.
2138 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002139 // Ignore member locations if the container is an array, as that's
2140 // ill-specified and decisions have been made to not allow this anyway.
2141 // The object itself must have a location, and that comes out from decorating the object,
2142 // not the type (this code decorates types).
2143 if (! type.isArray()) {
2144 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2145 // struct members should not have explicit locations
2146 assert(type.getBasicType() != glslang::EbtStruct);
2147 location = memberQualifier.layoutLocation;
2148 } else if (type.getBasicType() != glslang::EbtBlock) {
2149 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2150 // The members, and their nested types, must not themselves have Location decorations.
2151 } else if (qualifier.hasLocation()) // inheritance
2152 location = qualifier.layoutLocation + locationOffset;
2153 }
John Kessenich6090df02016-06-30 21:18:02 -06002154 if (location >= 0)
2155 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2156
John Kessenich2f47bc92016-06-30 21:47:35 -06002157 if (qualifier.hasLocation()) // track for upcoming inheritance
2158 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2159
John Kessenich6090df02016-06-30 21:18:02 -06002160 // component, XFB, others
2161 if (glslangMember.getQualifier().hasComponent())
2162 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2163 if (glslangMember.getQualifier().hasXfbOffset())
2164 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2165 else if (explicitLayout != glslang::ElpNone) {
2166 // figure out what to do with offset, which is accumulating
2167 int nextOffset;
2168 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2169 if (offset >= 0)
2170 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2171 offset = nextOffset;
2172 }
2173
2174 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2175 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2176
2177 // built-in variable decorations
2178 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002179 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002180 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2181 }
2182 }
2183
2184 // Decorate the structure
2185 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2186 addDecoration(spvType, TranslateBlockDecoration(type));
2187 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2188 builder.addCapability(spv::CapabilityGeometryStreams);
2189 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2190 }
2191 if (glslangIntermediate->getXfbMode()) {
2192 builder.addCapability(spv::CapabilityTransformFeedback);
2193 if (type.getQualifier().hasXfbStride())
2194 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2195 if (type.getQualifier().hasXfbBuffer())
2196 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2197 }
2198}
2199
John Kessenich6c292d32016-02-15 20:58:50 -07002200// Turn the expression forming the array size into an id.
2201// This is not quite trivial, because of specialization constants.
2202// Sometimes, a raw constant is turned into an Id, and sometimes
2203// a specialization constant expression is.
2204spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2205{
2206 // First, see if this is sized with a node, meaning a specialization constant:
2207 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2208 if (specNode != nullptr) {
2209 builder.clearAccessChain();
2210 specNode->traverse(this);
2211 return accessChainLoad(specNode->getAsTyped()->getType());
2212 }
qining25262b32016-05-06 17:25:16 -04002213
John Kessenich6c292d32016-02-15 20:58:50 -07002214 // Otherwise, need a compile-time (front end) size, get it:
2215 int size = arraySizes.getDimSize(dim);
2216 assert(size > 0);
2217 return builder.makeUintConstant(size);
2218}
2219
John Kessenich103bef92016-02-08 21:38:15 -07002220// Wrap the builder's accessChainLoad to:
2221// - localize handling of RelaxedPrecision
2222// - use the SPIR-V inferred type instead of another conversion of the glslang type
2223// (avoids unnecessary work and possible type punning for structures)
2224// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002225spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2226{
John Kessenich103bef92016-02-08 21:38:15 -07002227 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2228 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2229
2230 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002231 if (type.getBasicType() == glslang::EbtBool) {
2232 if (builder.isScalarType(nominalTypeId)) {
2233 // Conversion for bool
2234 spv::Id boolType = builder.makeBoolType();
2235 if (nominalTypeId != boolType)
2236 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2237 } else if (builder.isVectorType(nominalTypeId)) {
2238 // Conversion for bvec
2239 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2240 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2241 if (nominalTypeId != bvecType)
2242 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2243 }
2244 }
John Kessenich103bef92016-02-08 21:38:15 -07002245
2246 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002247}
2248
Rex Xu27253232016-02-23 17:51:09 +08002249// Wrap the builder's accessChainStore to:
2250// - do conversion of concrete to abstract type
2251void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2252{
2253 // Need to convert to abstract types when necessary
2254 if (type.getBasicType() == glslang::EbtBool) {
2255 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2256
2257 if (builder.isScalarType(nominalTypeId)) {
2258 // Conversion for bool
2259 spv::Id boolType = builder.makeBoolType();
2260 if (nominalTypeId != boolType) {
2261 spv::Id zero = builder.makeUintConstant(0);
2262 spv::Id one = builder.makeUintConstant(1);
2263 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2264 }
2265 } else if (builder.isVectorType(nominalTypeId)) {
2266 // Conversion for bvec
2267 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2268 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2269 if (nominalTypeId != bvecType) {
2270 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2271 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2272 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2273 }
2274 }
2275 }
2276
2277 builder.accessChainStore(rvalue);
2278}
2279
John Kessenichf85e8062015-12-19 13:57:10 -07002280// Decide whether or not this type should be
2281// decorated with offsets and strides, and if so
2282// whether std140 or std430 rules should be applied.
2283glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002284{
John Kessenichf85e8062015-12-19 13:57:10 -07002285 // has to be a block
2286 if (type.getBasicType() != glslang::EbtBlock)
2287 return glslang::ElpNone;
2288
2289 // has to be a uniform or buffer block
2290 if (type.getQualifier().storage != glslang::EvqUniform &&
2291 type.getQualifier().storage != glslang::EvqBuffer)
2292 return glslang::ElpNone;
2293
2294 // return the layout to use
2295 switch (type.getQualifier().layoutPacking) {
2296 case glslang::ElpStd140:
2297 case glslang::ElpStd430:
2298 return type.getQualifier().layoutPacking;
2299 default:
2300 return glslang::ElpNone;
2301 }
John Kessenich31ed4832015-09-09 17:51:38 -06002302}
2303
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002304// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002305int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002306{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002307 int size;
John Kessenich49987892015-12-29 17:11:44 -07002308 int stride;
2309 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002310
2311 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002312}
2313
John Kessenich49987892015-12-29 17:11:44 -07002314// 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 -07002315// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002316int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002317{
John Kessenich49987892015-12-29 17:11:44 -07002318 glslang::TType elementType;
2319 elementType.shallowCopy(matrixType);
2320 elementType.clearArraySizes();
2321
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002322 int size;
John Kessenich49987892015-12-29 17:11:44 -07002323 int stride;
2324 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2325
2326 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002327}
2328
John Kessenich5e4b1242015-08-06 22:53:06 -06002329// Given a member type of a struct, realign the current offset for it, and compute
2330// the next (not yet aligned) offset for the next member, which will get aligned
2331// on the next call.
2332// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2333// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2334// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002335void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002336 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002337{
2338 // this will get a positive value when deemed necessary
2339 nextOffset = -1;
2340
John Kessenich5e4b1242015-08-06 22:53:06 -06002341 // override anything in currentOffset with user-set offset
2342 if (memberType.getQualifier().hasOffset())
2343 currentOffset = memberType.getQualifier().layoutOffset;
2344
2345 // It could be that current linker usage in glslang updated all the layoutOffset,
2346 // in which case the following code does not matter. But, that's not quite right
2347 // once cross-compilation unit GLSL validation is done, as the original user
2348 // settings are needed in layoutOffset, and then the following will come into play.
2349
John Kessenichf85e8062015-12-19 13:57:10 -07002350 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002351 if (! memberType.getQualifier().hasOffset())
2352 currentOffset = -1;
2353
2354 return;
2355 }
2356
John Kessenichf85e8062015-12-19 13:57:10 -07002357 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002358 if (currentOffset < 0)
2359 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002360
John Kessenich5e4b1242015-08-06 22:53:06 -06002361 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2362 // but possibly not yet correctly aligned.
2363
2364 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002365 int dummyStride;
2366 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002367 glslang::RoundToPow2(currentOffset, memberAlignment);
2368 nextOffset = currentOffset + memberSize;
2369}
2370
David Netoa901ffe2016-06-08 14:11:40 +01002371void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002372{
David Netoa901ffe2016-06-08 14:11:40 +01002373 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2374 switch (glslangBuiltIn)
2375 {
2376 case glslang::EbvClipDistance:
2377 case glslang::EbvCullDistance:
2378 case glslang::EbvPointSize:
2379 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2380 // Alternately, we could just call this for any glslang built-in, since the
2381 // capability already guards against duplicates.
2382 TranslateBuiltInDecoration(glslangBuiltIn, false);
2383 break;
2384 default:
2385 // Capabilities were already generated when the struct was declared.
2386 break;
2387 }
John Kessenichebb50532016-05-16 19:22:05 -06002388}
2389
John Kessenich140f3df2015-06-26 16:58:36 -06002390bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2391{
John Kessenich4d65ee32016-03-12 18:17:47 -07002392 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002393 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002394 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002395}
2396
2397// Make all the functions, skeletally, without actually visiting their bodies.
2398void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2399{
2400 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2401 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2402 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2403 continue;
2404
2405 // We're on a user function. Set up the basic interface for the function now,
2406 // so that it's available to call.
2407 // Translating the body will happen later.
2408 //
qining25262b32016-05-06 17:25:16 -04002409 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002410 // function. What it is an address of varies:
2411 //
2412 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2413 // so that write needs to be to a copy, hence the address of a copy works.
2414 //
2415 // - "const in" parameters can just be the r-value, as no writes need occur.
2416 //
2417 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2418 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2419
2420 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002421 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002422 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2423
2424 for (int p = 0; p < (int)parameters.size(); ++p) {
2425 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2426 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002427 if (paramType.isOpaque())
2428 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2429 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002430 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2431 else
2432 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002433 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002434 paramTypes.push_back(typeId);
2435 }
2436
2437 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002438 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2439 convertGlslangToSpvType(glslFunction->getType()),
2440 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002441
2442 // Track function to emit/call later
2443 functionMap[glslFunction->getName().c_str()] = function;
2444
2445 // Set the parameter id's
2446 for (int p = 0; p < (int)parameters.size(); ++p) {
2447 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2448 // give a name too
2449 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2450 }
2451 }
2452}
2453
2454// Process all the initializers, while skipping the functions and link objects
2455void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2456{
2457 builder.setBuildPoint(shaderEntry->getLastBlock());
2458 for (int i = 0; i < (int)initializers.size(); ++i) {
2459 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2460 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2461
2462 // We're on a top-level node that's not a function. Treat as an initializer, whose
2463 // code goes into the beginning of main.
2464 initializer->traverse(this);
2465 }
2466 }
2467}
2468
2469// Process all the functions, while skipping initializers.
2470void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2471{
2472 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2473 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2474 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2475 node->traverse(this);
2476 }
2477}
2478
2479void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2480{
qining25262b32016-05-06 17:25:16 -04002481 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002482 // that called makeFunctions().
2483 spv::Function* function = functionMap[node->getName().c_str()];
2484 spv::Block* functionBlock = function->getEntryBlock();
2485 builder.setBuildPoint(functionBlock);
2486}
2487
Rex Xu04db3f52015-09-16 11:44:02 +08002488void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002489{
Rex Xufc618912015-09-09 16:42:49 +08002490 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002491
2492 glslang::TSampler sampler = {};
2493 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002494 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002495 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2496 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2497 }
2498
John Kessenich140f3df2015-06-26 16:58:36 -06002499 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2500 builder.clearAccessChain();
2501 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002502
2503 // Special case l-value operands
2504 bool lvalue = false;
2505 switch (node.getOp()) {
2506 case glslang::EOpImageAtomicAdd:
2507 case glslang::EOpImageAtomicMin:
2508 case glslang::EOpImageAtomicMax:
2509 case glslang::EOpImageAtomicAnd:
2510 case glslang::EOpImageAtomicOr:
2511 case glslang::EOpImageAtomicXor:
2512 case glslang::EOpImageAtomicExchange:
2513 case glslang::EOpImageAtomicCompSwap:
2514 if (i == 0)
2515 lvalue = true;
2516 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002517 case glslang::EOpSparseImageLoad:
2518 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2519 lvalue = true;
2520 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002521 case glslang::EOpSparseTexture:
2522 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2523 lvalue = true;
2524 break;
2525 case glslang::EOpSparseTextureClamp:
2526 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2527 lvalue = true;
2528 break;
2529 case glslang::EOpSparseTextureLod:
2530 case glslang::EOpSparseTextureOffset:
2531 if (i == 3)
2532 lvalue = true;
2533 break;
2534 case glslang::EOpSparseTextureFetch:
2535 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2536 lvalue = true;
2537 break;
2538 case glslang::EOpSparseTextureFetchOffset:
2539 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2540 lvalue = true;
2541 break;
2542 case glslang::EOpSparseTextureLodOffset:
2543 case glslang::EOpSparseTextureGrad:
2544 case glslang::EOpSparseTextureOffsetClamp:
2545 if (i == 4)
2546 lvalue = true;
2547 break;
2548 case glslang::EOpSparseTextureGradOffset:
2549 case glslang::EOpSparseTextureGradClamp:
2550 if (i == 5)
2551 lvalue = true;
2552 break;
2553 case glslang::EOpSparseTextureGradOffsetClamp:
2554 if (i == 6)
2555 lvalue = true;
2556 break;
2557 case glslang::EOpSparseTextureGather:
2558 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2559 lvalue = true;
2560 break;
2561 case glslang::EOpSparseTextureGatherOffset:
2562 case glslang::EOpSparseTextureGatherOffsets:
2563 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2564 lvalue = true;
2565 break;
Rex Xufc618912015-09-09 16:42:49 +08002566 default:
2567 break;
2568 }
2569
Rex Xu6b86d492015-09-16 17:48:22 +08002570 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002571 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002572 else
John Kessenich32cfd492016-02-02 12:37:46 -07002573 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002574 }
2575}
2576
John Kessenichfc51d282015-08-19 13:34:18 -06002577void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002578{
John Kessenichfc51d282015-08-19 13:34:18 -06002579 builder.clearAccessChain();
2580 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002581 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002582}
John Kessenich140f3df2015-06-26 16:58:36 -06002583
John Kessenichfc51d282015-08-19 13:34:18 -06002584spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2585{
Rex Xufc618912015-09-09 16:42:49 +08002586 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002587 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002588 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002589 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002590
John Kessenichfc51d282015-08-19 13:34:18 -06002591 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002592 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2593 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2594 std::vector<spv::Id> arguments;
2595 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002596 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002597 else
2598 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002599 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002600
2601 spv::Builder::TextureParameters params = { };
2602 params.sampler = arguments[0];
2603
Rex Xu04db3f52015-09-16 11:44:02 +08002604 glslang::TCrackedTextureOp cracked;
2605 node->crackTexture(sampler, cracked);
2606
John Kessenichfc51d282015-08-19 13:34:18 -06002607 // Check for queries
2608 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002609 // a sampled image needs to have the image extracted first
2610 if (builder.isSampledImage(params.sampler))
2611 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002612 switch (node->getOp()) {
2613 case glslang::EOpImageQuerySize:
2614 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002615 if (arguments.size() > 1) {
2616 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002617 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002618 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002619 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002620 case glslang::EOpImageQuerySamples:
2621 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002622 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002623 case glslang::EOpTextureQueryLod:
2624 params.coords = arguments[1];
2625 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2626 case glslang::EOpTextureQueryLevels:
2627 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002628 case glslang::EOpSparseTexelsResident:
2629 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002630 default:
2631 assert(0);
2632 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002633 }
John Kessenich140f3df2015-06-26 16:58:36 -06002634 }
2635
Rex Xufc618912015-09-09 16:42:49 +08002636 // Check for image functions other than queries
2637 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002638 std::vector<spv::Id> operands;
2639 auto opIt = arguments.begin();
2640 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002641
2642 // Handle subpass operations
2643 // TODO: GLSL should change to have the "MS" only on the type rather than the
2644 // built-in function.
2645 if (cracked.subpass) {
2646 // add on the (0,0) coordinate
2647 spv::Id zero = builder.makeIntConstant(0);
2648 std::vector<spv::Id> comps;
2649 comps.push_back(zero);
2650 comps.push_back(zero);
2651 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2652 if (sampler.ms) {
2653 operands.push_back(spv::ImageOperandsSampleMask);
2654 operands.push_back(*(opIt++));
2655 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002656 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002657 }
2658
John Kessenich56bab042015-09-16 10:54:31 -06002659 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002660 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002661 if (sampler.ms) {
2662 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002663 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002664 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002665 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2666 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002667 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002668 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002669 if (sampler.ms) {
2670 operands.push_back(*(opIt + 1));
2671 operands.push_back(spv::ImageOperandsSampleMask);
2672 operands.push_back(*opIt);
2673 } else
2674 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002675 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002676 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2677 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002678 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002679 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2680 builder.addCapability(spv::CapabilitySparseResidency);
2681 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2682 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2683
2684 if (sampler.ms) {
2685 operands.push_back(spv::ImageOperandsSampleMask);
2686 operands.push_back(*opIt++);
2687 }
2688
2689 // Create the return type that was a special structure
2690 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002691 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002692 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2693 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2694
2695 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2696
2697 // Decode the return type
2698 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2699 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002700 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002701 // Process image atomic operations
2702
2703 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2704 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002705 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002706
John Kessenich8c8505c2016-07-26 12:50:38 -06002707 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002708 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002709
2710 std::vector<spv::Id> operands;
2711 operands.push_back(pointer);
2712 for (; opIt != arguments.end(); ++opIt)
2713 operands.push_back(*opIt);
2714
John Kessenich8c8505c2016-07-26 12:50:38 -06002715 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002716 }
2717 }
2718
2719 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002720 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002721 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2722
John Kessenichfc51d282015-08-19 13:34:18 -06002723 // check for bias argument
2724 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002725 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002726 int nonBiasArgCount = 2;
2727 if (cracked.offset)
2728 ++nonBiasArgCount;
2729 if (cracked.grad)
2730 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002731 if (cracked.lodClamp)
2732 ++nonBiasArgCount;
2733 if (sparse)
2734 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002735
2736 if ((int)arguments.size() > nonBiasArgCount)
2737 bias = true;
2738 }
2739
John Kessenicha5c33d62016-06-02 23:45:21 -06002740 // See if the sampler param should really be just the SPV image part
2741 if (cracked.fetch) {
2742 // a fetch needs to have the image extracted first
2743 if (builder.isSampledImage(params.sampler))
2744 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2745 }
2746
John Kessenichfc51d282015-08-19 13:34:18 -06002747 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002748
John Kessenichfc51d282015-08-19 13:34:18 -06002749 params.coords = arguments[1];
2750 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002751 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002752
2753 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002754 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002755 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002756 ++extraArgs;
2757 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002758 params.Dref = arguments[2];
2759 ++extraArgs;
2760 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002761 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002762 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002763 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002764 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002765 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002766 dRefComp = builder.getNumComponents(params.coords) - 1;
2767 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002768 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2769 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002770
2771 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002772 if (cracked.lod) {
2773 params.lod = arguments[2];
2774 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002775 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2776 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2777 noImplicitLod = true;
2778 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002779
2780 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002781 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002782 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002783 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002784 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002785
2786 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002787 if (cracked.grad) {
2788 params.gradX = arguments[2 + extraArgs];
2789 params.gradY = arguments[3 + extraArgs];
2790 extraArgs += 2;
2791 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002792
2793 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002794 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002795 params.offset = arguments[2 + extraArgs];
2796 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002797 } else if (cracked.offsets) {
2798 params.offsets = arguments[2 + extraArgs];
2799 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002800 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002801
2802 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002803 if (cracked.lodClamp) {
2804 params.lodClamp = arguments[2 + extraArgs];
2805 ++extraArgs;
2806 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002807
2808 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002809 if (sparse) {
2810 params.texelOut = arguments[2 + extraArgs];
2811 ++extraArgs;
2812 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002813
2814 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002815 if (bias) {
2816 params.bias = arguments[2 + extraArgs];
2817 ++extraArgs;
2818 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002819
2820 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002821 if (cracked.gather && ! sampler.shadow) {
2822 // default component is 0, if missing, otherwise an argument
2823 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002824 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002825 ++extraArgs;
2826 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002827 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002828 }
2829 }
John Kessenichfc51d282015-08-19 13:34:18 -06002830
John Kessenich65336482016-06-16 14:06:26 -06002831 // projective component (might not to move)
2832 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2833 // are divided by the last component of P."
2834 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2835 // unused components will appear after all used components."
2836 if (cracked.proj) {
2837 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2838 int projTargetComp;
2839 switch (sampler.dim) {
2840 case glslang::Esd1D: projTargetComp = 1; break;
2841 case glslang::Esd2D: projTargetComp = 2; break;
2842 case glslang::EsdRect: projTargetComp = 2; break;
2843 default: projTargetComp = projSourceComp; break;
2844 }
2845 // copy the projective coordinate if we have to
2846 if (projTargetComp != projSourceComp) {
2847 spv::Id projComp = builder.createCompositeExtract(params.coords,
2848 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2849 projSourceComp);
2850 params.coords = builder.createCompositeInsert(projComp, params.coords,
2851 builder.getTypeId(params.coords), projTargetComp);
2852 }
2853 }
2854
John Kessenich8c8505c2016-07-26 12:50:38 -06002855 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002856}
2857
2858spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2859{
2860 // Grab the function's pointer from the previously created function
2861 spv::Function* function = functionMap[node->getName().c_str()];
2862 if (! function)
2863 return 0;
2864
2865 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2866 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2867
2868 // See comments in makeFunctions() for details about the semantics for parameter passing.
2869 //
2870 // These imply we need a four step process:
2871 // 1. Evaluate the arguments
2872 // 2. Allocate and make copies of in, out, and inout arguments
2873 // 3. Make the call
2874 // 4. Copy back the results
2875
2876 // 1. Evaluate the arguments
2877 std::vector<spv::Builder::AccessChain> lValues;
2878 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002879 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002880 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002881 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002882 // build l-value
2883 builder.clearAccessChain();
2884 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002885 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002886 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002887 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002888 // save l-value
2889 lValues.push_back(builder.getAccessChain());
2890 } else {
2891 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002892 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002893 }
2894 }
2895
2896 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2897 // copy the original into that space.
2898 //
2899 // Also, build up the list of actual arguments to pass in for the call
2900 int lValueCount = 0;
2901 int rValueCount = 0;
2902 std::vector<spv::Id> spvArgs;
2903 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002904 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002905 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002906 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002907 builder.setAccessChain(lValues[lValueCount]);
2908 arg = builder.accessChainGetLValue();
2909 ++lValueCount;
2910 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002911 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002912 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2913 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2914 // need to copy the input into output space
2915 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002916 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002917 builder.createStore(copy, arg);
2918 }
2919 ++lValueCount;
2920 } else {
2921 arg = rValues[rValueCount];
2922 ++rValueCount;
2923 }
2924 spvArgs.push_back(arg);
2925 }
2926
2927 // 3. Make the call.
2928 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002929 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002930
2931 // 4. Copy back out an "out" arguments.
2932 lValueCount = 0;
2933 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2934 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2935 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2936 spv::Id copy = builder.createLoad(spvArgs[a]);
2937 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002938 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002939 }
2940 ++lValueCount;
2941 }
2942 }
2943
2944 return result;
2945}
2946
2947// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002948spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2949 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002950 spv::Id typeId, spv::Id left, spv::Id right,
2951 glslang::TBasicType typeProxy, bool reduceComparison)
2952{
Rex Xu8ff43de2016-04-22 16:51:45 +08002953 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002954 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002955 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002956
2957 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002958 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002959 bool comparison = false;
2960
2961 switch (op) {
2962 case glslang::EOpAdd:
2963 case glslang::EOpAddAssign:
2964 if (isFloat)
2965 binOp = spv::OpFAdd;
2966 else
2967 binOp = spv::OpIAdd;
2968 break;
2969 case glslang::EOpSub:
2970 case glslang::EOpSubAssign:
2971 if (isFloat)
2972 binOp = spv::OpFSub;
2973 else
2974 binOp = spv::OpISub;
2975 break;
2976 case glslang::EOpMul:
2977 case glslang::EOpMulAssign:
2978 if (isFloat)
2979 binOp = spv::OpFMul;
2980 else
2981 binOp = spv::OpIMul;
2982 break;
2983 case glslang::EOpVectorTimesScalar:
2984 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002985 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002986 if (builder.isVector(right))
2987 std::swap(left, right);
2988 assert(builder.isScalar(right));
2989 needMatchingVectors = false;
2990 binOp = spv::OpVectorTimesScalar;
2991 } else
2992 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 break;
2994 case glslang::EOpVectorTimesMatrix:
2995 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002996 binOp = spv::OpVectorTimesMatrix;
2997 break;
2998 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002999 binOp = spv::OpMatrixTimesVector;
3000 break;
3001 case glslang::EOpMatrixTimesScalar:
3002 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003003 binOp = spv::OpMatrixTimesScalar;
3004 break;
3005 case glslang::EOpMatrixTimesMatrix:
3006 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003007 binOp = spv::OpMatrixTimesMatrix;
3008 break;
3009 case glslang::EOpOuterProduct:
3010 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003011 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003012 break;
3013
3014 case glslang::EOpDiv:
3015 case glslang::EOpDivAssign:
3016 if (isFloat)
3017 binOp = spv::OpFDiv;
3018 else if (isUnsigned)
3019 binOp = spv::OpUDiv;
3020 else
3021 binOp = spv::OpSDiv;
3022 break;
3023 case glslang::EOpMod:
3024 case glslang::EOpModAssign:
3025 if (isFloat)
3026 binOp = spv::OpFMod;
3027 else if (isUnsigned)
3028 binOp = spv::OpUMod;
3029 else
3030 binOp = spv::OpSMod;
3031 break;
3032 case glslang::EOpRightShift:
3033 case glslang::EOpRightShiftAssign:
3034 if (isUnsigned)
3035 binOp = spv::OpShiftRightLogical;
3036 else
3037 binOp = spv::OpShiftRightArithmetic;
3038 break;
3039 case glslang::EOpLeftShift:
3040 case glslang::EOpLeftShiftAssign:
3041 binOp = spv::OpShiftLeftLogical;
3042 break;
3043 case glslang::EOpAnd:
3044 case glslang::EOpAndAssign:
3045 binOp = spv::OpBitwiseAnd;
3046 break;
3047 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003048 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 binOp = spv::OpLogicalAnd;
3050 break;
3051 case glslang::EOpInclusiveOr:
3052 case glslang::EOpInclusiveOrAssign:
3053 binOp = spv::OpBitwiseOr;
3054 break;
3055 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003056 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 binOp = spv::OpLogicalOr;
3058 break;
3059 case glslang::EOpExclusiveOr:
3060 case glslang::EOpExclusiveOrAssign:
3061 binOp = spv::OpBitwiseXor;
3062 break;
3063 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003064 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003065 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003066 break;
3067
3068 case glslang::EOpLessThan:
3069 case glslang::EOpGreaterThan:
3070 case glslang::EOpLessThanEqual:
3071 case glslang::EOpGreaterThanEqual:
3072 case glslang::EOpEqual:
3073 case glslang::EOpNotEqual:
3074 case glslang::EOpVectorEqual:
3075 case glslang::EOpVectorNotEqual:
3076 comparison = true;
3077 break;
3078 default:
3079 break;
3080 }
3081
John Kessenich7c1aa102015-10-15 13:29:11 -06003082 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003083 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003084 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003085 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003086 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003087
3088 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003089 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003090 builder.promoteScalar(precision, left, right);
3091
qining25262b32016-05-06 17:25:16 -04003092 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3093 addDecoration(result, noContraction);
3094 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003095 }
3096
3097 if (! comparison)
3098 return 0;
3099
John Kessenich7c1aa102015-10-15 13:29:11 -06003100 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003101
John Kessenich4583b612016-08-07 19:14:22 -06003102 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3103 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003104 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003105
3106 switch (op) {
3107 case glslang::EOpLessThan:
3108 if (isFloat)
3109 binOp = spv::OpFOrdLessThan;
3110 else if (isUnsigned)
3111 binOp = spv::OpULessThan;
3112 else
3113 binOp = spv::OpSLessThan;
3114 break;
3115 case glslang::EOpGreaterThan:
3116 if (isFloat)
3117 binOp = spv::OpFOrdGreaterThan;
3118 else if (isUnsigned)
3119 binOp = spv::OpUGreaterThan;
3120 else
3121 binOp = spv::OpSGreaterThan;
3122 break;
3123 case glslang::EOpLessThanEqual:
3124 if (isFloat)
3125 binOp = spv::OpFOrdLessThanEqual;
3126 else if (isUnsigned)
3127 binOp = spv::OpULessThanEqual;
3128 else
3129 binOp = spv::OpSLessThanEqual;
3130 break;
3131 case glslang::EOpGreaterThanEqual:
3132 if (isFloat)
3133 binOp = spv::OpFOrdGreaterThanEqual;
3134 else if (isUnsigned)
3135 binOp = spv::OpUGreaterThanEqual;
3136 else
3137 binOp = spv::OpSGreaterThanEqual;
3138 break;
3139 case glslang::EOpEqual:
3140 case glslang::EOpVectorEqual:
3141 if (isFloat)
3142 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003143 else if (isBool)
3144 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003145 else
3146 binOp = spv::OpIEqual;
3147 break;
3148 case glslang::EOpNotEqual:
3149 case glslang::EOpVectorNotEqual:
3150 if (isFloat)
3151 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003152 else if (isBool)
3153 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 else
3155 binOp = spv::OpINotEqual;
3156 break;
3157 default:
3158 break;
3159 }
3160
qining25262b32016-05-06 17:25:16 -04003161 if (binOp != spv::OpNop) {
3162 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3163 addDecoration(result, noContraction);
3164 return builder.setPrecision(result, precision);
3165 }
John Kessenich140f3df2015-06-26 16:58:36 -06003166
3167 return 0;
3168}
3169
John Kessenich04bb8a02015-12-12 12:28:14 -07003170//
3171// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3172// These can be any of:
3173//
3174// matrix * scalar
3175// scalar * matrix
3176// matrix * matrix linear algebraic
3177// matrix * vector
3178// vector * matrix
3179// matrix * matrix componentwise
3180// matrix op matrix op in {+, -, /}
3181// matrix op scalar op in {+, -, /}
3182// scalar op matrix op in {+, -, /}
3183//
qining25262b32016-05-06 17:25:16 -04003184spv::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 -07003185{
3186 bool firstClass = true;
3187
3188 // First, handle first-class matrix operations (* and matrix/scalar)
3189 switch (op) {
3190 case spv::OpFDiv:
3191 if (builder.isMatrix(left) && builder.isScalar(right)) {
3192 // turn matrix / scalar into a multiply...
3193 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3194 op = spv::OpMatrixTimesScalar;
3195 } else
3196 firstClass = false;
3197 break;
3198 case spv::OpMatrixTimesScalar:
3199 if (builder.isMatrix(right))
3200 std::swap(left, right);
3201 assert(builder.isScalar(right));
3202 break;
3203 case spv::OpVectorTimesMatrix:
3204 assert(builder.isVector(left));
3205 assert(builder.isMatrix(right));
3206 break;
3207 case spv::OpMatrixTimesVector:
3208 assert(builder.isMatrix(left));
3209 assert(builder.isVector(right));
3210 break;
3211 case spv::OpMatrixTimesMatrix:
3212 assert(builder.isMatrix(left));
3213 assert(builder.isMatrix(right));
3214 break;
3215 default:
3216 firstClass = false;
3217 break;
3218 }
3219
qining25262b32016-05-06 17:25:16 -04003220 if (firstClass) {
3221 spv::Id result = builder.createBinOp(op, typeId, left, right);
3222 addDecoration(result, noContraction);
3223 return builder.setPrecision(result, precision);
3224 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003225
LoopDawg592860c2016-06-09 08:57:35 -06003226 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003227 // The result type of all of them is the same type as the (a) matrix operand.
3228 // The algorithm is to:
3229 // - break the matrix(es) into vectors
3230 // - smear any scalar to a vector
3231 // - do vector operations
3232 // - make a matrix out the vector results
3233 switch (op) {
3234 case spv::OpFAdd:
3235 case spv::OpFSub:
3236 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003237 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003238 case spv::OpFMul:
3239 {
3240 // one time set up...
3241 bool leftMat = builder.isMatrix(left);
3242 bool rightMat = builder.isMatrix(right);
3243 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3244 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3245 spv::Id scalarType = builder.getScalarTypeId(typeId);
3246 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3247 std::vector<spv::Id> results;
3248 spv::Id smearVec = spv::NoResult;
3249 if (builder.isScalar(left))
3250 smearVec = builder.smearScalar(precision, left, vecType);
3251 else if (builder.isScalar(right))
3252 smearVec = builder.smearScalar(precision, right, vecType);
3253
3254 // do each vector op
3255 for (unsigned int c = 0; c < numCols; ++c) {
3256 std::vector<unsigned int> indexes;
3257 indexes.push_back(c);
3258 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3259 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003260 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3261 addDecoration(result, noContraction);
3262 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003263 }
3264
3265 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003266 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003267 }
3268 default:
3269 assert(0);
3270 return spv::NoResult;
3271 }
3272}
3273
qining25262b32016-05-06 17:25:16 -04003274spv::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 -06003275{
3276 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003277 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003278 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003279 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003280 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003281
3282 switch (op) {
3283 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003284 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003285 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003286 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003287 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003288 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003289 unaryOp = spv::OpSNegate;
3290 break;
3291
3292 case glslang::EOpLogicalNot:
3293 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003294 unaryOp = spv::OpLogicalNot;
3295 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003296 case glslang::EOpBitwiseNot:
3297 unaryOp = spv::OpNot;
3298 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003299
John Kessenich140f3df2015-06-26 16:58:36 -06003300 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003301 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003302 break;
3303 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003304 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003305 break;
3306 case glslang::EOpTranspose:
3307 unaryOp = spv::OpTranspose;
3308 break;
3309
3310 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003311 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003312 break;
3313 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003314 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003315 break;
3316 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003317 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003318 break;
3319 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003320 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003321 break;
3322 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003323 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 break;
3325 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003326 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003327 break;
3328 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003329 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003330 break;
3331 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003332 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003333 break;
3334
3335 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003336 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003337 break;
3338 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003339 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003340 break;
3341 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003342 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003343 break;
3344 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003345 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003346 break;
3347 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003348 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003349 break;
3350 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003351 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353
3354 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003355 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003356 break;
3357 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003358 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003359 break;
3360
3361 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003362 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003363 break;
3364 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003365 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003366 break;
3367 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003369 break;
3370 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003371 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003372 break;
3373 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003374 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003375 break;
3376 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003377 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003378 break;
3379
3380 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003381 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003382 break;
3383 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003384 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003385 break;
3386 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003387 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003388 break;
3389 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003390 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003391 break;
3392 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003393 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003394 break;
3395 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003396 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398
3399 case glslang::EOpIsNan:
3400 unaryOp = spv::OpIsNan;
3401 break;
3402 case glslang::EOpIsInf:
3403 unaryOp = spv::OpIsInf;
3404 break;
LoopDawg592860c2016-06-09 08:57:35 -06003405 case glslang::EOpIsFinite:
3406 unaryOp = spv::OpIsFinite;
3407 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003408
Rex Xucbc426e2015-12-15 16:03:10 +08003409 case glslang::EOpFloatBitsToInt:
3410 case glslang::EOpFloatBitsToUint:
3411 case glslang::EOpIntBitsToFloat:
3412 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003413 case glslang::EOpDoubleBitsToInt64:
3414 case glslang::EOpDoubleBitsToUint64:
3415 case glslang::EOpInt64BitsToDouble:
3416 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003417 unaryOp = spv::OpBitcast;
3418 break;
3419
John Kessenich140f3df2015-06-26 16:58:36 -06003420 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003421 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003422 break;
3423 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003424 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003425 break;
3426 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003428 break;
3429 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003430 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003431 break;
3432 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003433 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003434 break;
3435 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003436 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003437 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003438 case glslang::EOpPackSnorm4x8:
3439 libCall = spv::GLSLstd450PackSnorm4x8;
3440 break;
3441 case glslang::EOpUnpackSnorm4x8:
3442 libCall = spv::GLSLstd450UnpackSnorm4x8;
3443 break;
3444 case glslang::EOpPackUnorm4x8:
3445 libCall = spv::GLSLstd450PackUnorm4x8;
3446 break;
3447 case glslang::EOpUnpackUnorm4x8:
3448 libCall = spv::GLSLstd450UnpackUnorm4x8;
3449 break;
3450 case glslang::EOpPackDouble2x32:
3451 libCall = spv::GLSLstd450PackDouble2x32;
3452 break;
3453 case glslang::EOpUnpackDouble2x32:
3454 libCall = spv::GLSLstd450UnpackDouble2x32;
3455 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003456
Rex Xu8ff43de2016-04-22 16:51:45 +08003457 case glslang::EOpPackInt2x32:
3458 case glslang::EOpUnpackInt2x32:
3459 case glslang::EOpPackUint2x32:
3460 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003461 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003462 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3463 break;
3464
John Kessenich140f3df2015-06-26 16:58:36 -06003465 case glslang::EOpDPdx:
3466 unaryOp = spv::OpDPdx;
3467 break;
3468 case glslang::EOpDPdy:
3469 unaryOp = spv::OpDPdy;
3470 break;
3471 case glslang::EOpFwidth:
3472 unaryOp = spv::OpFwidth;
3473 break;
3474 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003475 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003476 unaryOp = spv::OpDPdxFine;
3477 break;
3478 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003479 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003480 unaryOp = spv::OpDPdyFine;
3481 break;
3482 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003483 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003484 unaryOp = spv::OpFwidthFine;
3485 break;
3486 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003487 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003488 unaryOp = spv::OpDPdxCoarse;
3489 break;
3490 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003491 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003492 unaryOp = spv::OpDPdyCoarse;
3493 break;
3494 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003495 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003496 unaryOp = spv::OpFwidthCoarse;
3497 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003498 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003499 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003500 libCall = spv::GLSLstd450InterpolateAtCentroid;
3501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 case glslang::EOpAny:
3503 unaryOp = spv::OpAny;
3504 break;
3505 case glslang::EOpAll:
3506 unaryOp = spv::OpAll;
3507 break;
3508
3509 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003510 if (isFloat)
3511 libCall = spv::GLSLstd450FAbs;
3512 else
3513 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003514 break;
3515 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 if (isFloat)
3517 libCall = spv::GLSLstd450FSign;
3518 else
3519 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521
John Kessenichfc51d282015-08-19 13:34:18 -06003522 case glslang::EOpAtomicCounterIncrement:
3523 case glslang::EOpAtomicCounterDecrement:
3524 case glslang::EOpAtomicCounter:
3525 {
3526 // Handle all of the atomics in one place, in createAtomicOperation()
3527 std::vector<spv::Id> operands;
3528 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003529 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003530 }
3531
John Kessenichfc51d282015-08-19 13:34:18 -06003532 case glslang::EOpBitFieldReverse:
3533 unaryOp = spv::OpBitReverse;
3534 break;
3535 case glslang::EOpBitCount:
3536 unaryOp = spv::OpBitCount;
3537 break;
3538 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003539 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003540 break;
3541 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003542 if (isUnsigned)
3543 libCall = spv::GLSLstd450FindUMsb;
3544 else
3545 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003546 break;
3547
Rex Xu574ab042016-04-14 16:53:07 +08003548 case glslang::EOpBallot:
3549 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003550 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003551 libCall = spv::GLSLstd450Bad;
3552 break;
3553
Rex Xu338b1852016-05-05 20:38:33 +08003554 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003555 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003556 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003557#ifdef AMD_EXTENSIONS
3558 case glslang::EOpMinInvocations:
3559 case glslang::EOpMaxInvocations:
3560 case glslang::EOpAddInvocations:
3561 case glslang::EOpMinInvocationsNonUniform:
3562 case glslang::EOpMaxInvocationsNonUniform:
3563 case glslang::EOpAddInvocationsNonUniform:
3564#endif
3565 return createInvocationsOperation(op, typeId, operand, typeProxy);
3566
3567#ifdef AMD_EXTENSIONS
3568 case glslang::EOpMbcnt:
3569 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3570 libCall = spv::MbcntAMD;
3571 break;
3572
3573 case glslang::EOpCubeFaceIndex:
3574 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3575 libCall = spv::CubeFaceIndexAMD;
3576 break;
3577
3578 case glslang::EOpCubeFaceCoord:
3579 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3580 libCall = spv::CubeFaceCoordAMD;
3581 break;
3582#endif
Rex Xu338b1852016-05-05 20:38:33 +08003583
John Kessenich140f3df2015-06-26 16:58:36 -06003584 default:
3585 return 0;
3586 }
3587
3588 spv::Id id;
3589 if (libCall >= 0) {
3590 std::vector<spv::Id> args;
3591 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003592 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003593 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003594 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003595 }
John Kessenich140f3df2015-06-26 16:58:36 -06003596
qining25262b32016-05-06 17:25:16 -04003597 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003598 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003599}
3600
John Kessenich7a53f762016-01-20 11:19:27 -07003601// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003602spv::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 -07003603{
3604 // Handle unary operations vector by vector.
3605 // The result type is the same type as the original type.
3606 // The algorithm is to:
3607 // - break the matrix into vectors
3608 // - apply the operation to each vector
3609 // - make a matrix out the vector results
3610
3611 // get the types sorted out
3612 int numCols = builder.getNumColumns(operand);
3613 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003614 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3615 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003616 std::vector<spv::Id> results;
3617
3618 // do each vector op
3619 for (int c = 0; c < numCols; ++c) {
3620 std::vector<unsigned int> indexes;
3621 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003622 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3623 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3624 addDecoration(destVec, noContraction);
3625 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003626 }
3627
3628 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003629 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003630}
3631
Rex Xu73e3ce72016-04-27 18:48:17 +08003632spv::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 -06003633{
3634 spv::Op convOp = spv::OpNop;
3635 spv::Id zero = 0;
3636 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003637 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003638
3639 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3640
3641 switch (op) {
3642 case glslang::EOpConvIntToBool:
3643 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003644 case glslang::EOpConvInt64ToBool:
3645 case glslang::EOpConvUint64ToBool:
3646 zero = (op == glslang::EOpConvInt64ToBool ||
3647 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003648 zero = makeSmearedConstant(zero, vectorSize);
3649 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3650
3651 case glslang::EOpConvFloatToBool:
3652 zero = builder.makeFloatConstant(0.0F);
3653 zero = makeSmearedConstant(zero, vectorSize);
3654 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3655
3656 case glslang::EOpConvDoubleToBool:
3657 zero = builder.makeDoubleConstant(0.0);
3658 zero = makeSmearedConstant(zero, vectorSize);
3659 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3660
3661 case glslang::EOpConvBoolToFloat:
3662 convOp = spv::OpSelect;
3663 zero = builder.makeFloatConstant(0.0);
3664 one = builder.makeFloatConstant(1.0);
3665 break;
3666 case glslang::EOpConvBoolToDouble:
3667 convOp = spv::OpSelect;
3668 zero = builder.makeDoubleConstant(0.0);
3669 one = builder.makeDoubleConstant(1.0);
3670 break;
3671 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003672 case glslang::EOpConvBoolToInt64:
3673 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3674 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003675 convOp = spv::OpSelect;
3676 break;
3677 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003678 case glslang::EOpConvBoolToUint64:
3679 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3680 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003681 convOp = spv::OpSelect;
3682 break;
3683
3684 case glslang::EOpConvIntToFloat:
3685 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003686 case glslang::EOpConvInt64ToFloat:
3687 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003688 convOp = spv::OpConvertSToF;
3689 break;
3690
3691 case glslang::EOpConvUintToFloat:
3692 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003693 case glslang::EOpConvUint64ToFloat:
3694 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003695 convOp = spv::OpConvertUToF;
3696 break;
3697
3698 case glslang::EOpConvDoubleToFloat:
3699 case glslang::EOpConvFloatToDouble:
3700 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003701 if (builder.isMatrixType(destType))
3702 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704
3705 case glslang::EOpConvFloatToInt:
3706 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003707 case glslang::EOpConvFloatToInt64:
3708 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003709 convOp = spv::OpConvertFToS;
3710 break;
3711
3712 case glslang::EOpConvUintToInt:
3713 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003714 case glslang::EOpConvUint64ToInt64:
3715 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003716 if (builder.isInSpecConstCodeGenMode()) {
3717 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003718 zero = (op == glslang::EOpConvUintToInt64 ||
3719 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003720 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003721 // Use OpIAdd, instead of OpBitcast to do the conversion when
3722 // generating for OpSpecConstantOp instruction.
3723 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3724 }
3725 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003726 convOp = spv::OpBitcast;
3727 break;
3728
3729 case glslang::EOpConvFloatToUint:
3730 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003731 case glslang::EOpConvFloatToUint64:
3732 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003733 convOp = spv::OpConvertFToU;
3734 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003735
3736 case glslang::EOpConvIntToInt64:
3737 case glslang::EOpConvInt64ToInt:
3738 convOp = spv::OpSConvert;
3739 break;
3740
3741 case glslang::EOpConvUintToUint64:
3742 case glslang::EOpConvUint64ToUint:
3743 convOp = spv::OpUConvert;
3744 break;
3745
3746 case glslang::EOpConvIntToUint64:
3747 case glslang::EOpConvInt64ToUint:
3748 case glslang::EOpConvUint64ToInt:
3749 case glslang::EOpConvUintToInt64:
3750 // OpSConvert/OpUConvert + OpBitCast
3751 switch (op) {
3752 case glslang::EOpConvIntToUint64:
3753 convOp = spv::OpSConvert;
3754 type = builder.makeIntType(64);
3755 break;
3756 case glslang::EOpConvInt64ToUint:
3757 convOp = spv::OpSConvert;
3758 type = builder.makeIntType(32);
3759 break;
3760 case glslang::EOpConvUint64ToInt:
3761 convOp = spv::OpUConvert;
3762 type = builder.makeUintType(32);
3763 break;
3764 case glslang::EOpConvUintToInt64:
3765 convOp = spv::OpUConvert;
3766 type = builder.makeUintType(64);
3767 break;
3768 default:
3769 assert(0);
3770 break;
3771 }
3772
3773 if (vectorSize > 0)
3774 type = builder.makeVectorType(type, vectorSize);
3775
3776 operand = builder.createUnaryOp(convOp, type, operand);
3777
3778 if (builder.isInSpecConstCodeGenMode()) {
3779 // Build zero scalar or vector for OpIAdd.
3780 zero = (op == glslang::EOpConvIntToUint64 ||
3781 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3782 zero = makeSmearedConstant(zero, vectorSize);
3783 // Use OpIAdd, instead of OpBitcast to do the conversion when
3784 // generating for OpSpecConstantOp instruction.
3785 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3786 }
3787 // For normal run-time conversion instruction, use OpBitcast.
3788 convOp = spv::OpBitcast;
3789 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003790 default:
3791 break;
3792 }
3793
3794 spv::Id result = 0;
3795 if (convOp == spv::OpNop)
3796 return result;
3797
3798 if (convOp == spv::OpSelect) {
3799 zero = makeSmearedConstant(zero, vectorSize);
3800 one = makeSmearedConstant(one, vectorSize);
3801 result = builder.createTriOp(convOp, destType, operand, one, zero);
3802 } else
3803 result = builder.createUnaryOp(convOp, destType, operand);
3804
John Kessenich32cfd492016-02-02 12:37:46 -07003805 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003806}
3807
3808spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3809{
3810 if (vectorSize == 0)
3811 return constant;
3812
3813 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3814 std::vector<spv::Id> components;
3815 for (int c = 0; c < vectorSize; ++c)
3816 components.push_back(constant);
3817 return builder.makeCompositeConstant(vectorTypeId, components);
3818}
3819
John Kessenich426394d2015-07-23 10:22:48 -06003820// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003821spv::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 -06003822{
3823 spv::Op opCode = spv::OpNop;
3824
3825 switch (op) {
3826 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003827 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003828 opCode = spv::OpAtomicIAdd;
3829 break;
3830 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003831 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003832 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003833 break;
3834 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003835 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003836 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003837 break;
3838 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003839 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003840 opCode = spv::OpAtomicAnd;
3841 break;
3842 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003843 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003844 opCode = spv::OpAtomicOr;
3845 break;
3846 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003847 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003848 opCode = spv::OpAtomicXor;
3849 break;
3850 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003851 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003852 opCode = spv::OpAtomicExchange;
3853 break;
3854 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003855 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003856 opCode = spv::OpAtomicCompareExchange;
3857 break;
3858 case glslang::EOpAtomicCounterIncrement:
3859 opCode = spv::OpAtomicIIncrement;
3860 break;
3861 case glslang::EOpAtomicCounterDecrement:
3862 opCode = spv::OpAtomicIDecrement;
3863 break;
3864 case glslang::EOpAtomicCounter:
3865 opCode = spv::OpAtomicLoad;
3866 break;
3867 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003868 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003869 break;
3870 }
3871
3872 // Sort out the operands
3873 // - mapping from glslang -> SPV
3874 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003875 // - compare-exchange swaps the value and comparator
3876 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003877 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3878 auto opIt = operands.begin(); // walk the glslang operands
3879 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003880 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3881 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3882 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003883 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3884 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003885 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003886 spvAtomicOperands.push_back(*(opIt + 1));
3887 spvAtomicOperands.push_back(*opIt);
3888 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003889 }
John Kessenich426394d2015-07-23 10:22:48 -06003890
John Kessenich3e60a6f2015-09-14 22:45:16 -06003891 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003892 for (; opIt != operands.end(); ++opIt)
3893 spvAtomicOperands.push_back(*opIt);
3894
3895 return builder.createOp(opCode, typeId, spvAtomicOperands);
3896}
3897
John Kessenich91cef522016-05-05 16:45:40 -06003898// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003899spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003900{
Rex Xu9d93a232016-05-05 12:30:44 +08003901 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3902 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3903
John Kessenich91cef522016-05-05 16:45:40 -06003904 builder.addCapability(spv::CapabilityGroups);
3905
3906 std::vector<spv::Id> operands;
3907 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003908#ifdef AMD_EXTENSIONS
3909 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3910 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3911 operands.push_back(spv::GroupOperationReduce);
3912#endif
John Kessenich91cef522016-05-05 16:45:40 -06003913 operands.push_back(operand);
3914
3915 switch (op) {
3916 case glslang::EOpAnyInvocation:
3917 case glslang::EOpAllInvocations:
3918 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3919
3920 case glslang::EOpAllInvocationsEqual:
3921 {
3922 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3923 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3924
3925 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3926 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3927 }
Rex Xu9d93a232016-05-05 12:30:44 +08003928#ifdef AMD_EXTENSIONS
3929 case glslang::EOpMinInvocations:
3930 case glslang::EOpMaxInvocations:
3931 case glslang::EOpAddInvocations:
3932 {
3933 spv::Op spvOp = spv::OpNop;
3934 if (op == glslang::EOpMinInvocations) {
3935 if (isFloat)
3936 spvOp = spv::OpGroupFMin;
3937 else {
3938 if (isUnsigned)
3939 spvOp = spv::OpGroupUMin;
3940 else
3941 spvOp = spv::OpGroupSMin;
3942 }
3943 } else if (op == glslang::EOpMaxInvocations) {
3944 if (isFloat)
3945 spvOp = spv::OpGroupFMax;
3946 else {
3947 if (isUnsigned)
3948 spvOp = spv::OpGroupUMax;
3949 else
3950 spvOp = spv::OpGroupSMax;
3951 }
3952 } else {
3953 if (isFloat)
3954 spvOp = spv::OpGroupFAdd;
3955 else
3956 spvOp = spv::OpGroupIAdd;
3957 }
3958
Rex Xu2bbbe062016-08-23 15:41:05 +08003959 if (builder.isVectorType(typeId))
3960 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
3961 else
3962 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08003963 }
3964 case glslang::EOpMinInvocationsNonUniform:
3965 case glslang::EOpMaxInvocationsNonUniform:
3966 case glslang::EOpAddInvocationsNonUniform:
3967 {
3968 spv::Op spvOp = spv::OpNop;
3969 if (op == glslang::EOpMinInvocationsNonUniform) {
3970 if (isFloat)
3971 spvOp = spv::OpGroupFMinNonUniformAMD;
3972 else {
3973 if (isUnsigned)
3974 spvOp = spv::OpGroupUMinNonUniformAMD;
3975 else
3976 spvOp = spv::OpGroupSMinNonUniformAMD;
3977 }
3978 }
3979 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3980 if (isFloat)
3981 spvOp = spv::OpGroupFMaxNonUniformAMD;
3982 else {
3983 if (isUnsigned)
3984 spvOp = spv::OpGroupUMaxNonUniformAMD;
3985 else
3986 spvOp = spv::OpGroupSMaxNonUniformAMD;
3987 }
3988 }
3989 else {
3990 if (isFloat)
3991 spvOp = spv::OpGroupFAddNonUniformAMD;
3992 else
3993 spvOp = spv::OpGroupIAddNonUniformAMD;
3994 }
3995
Rex Xu2bbbe062016-08-23 15:41:05 +08003996 if (builder.isVectorType(typeId))
3997 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
3998 else
3999 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08004000 }
4001#endif
John Kessenich91cef522016-05-05 16:45:40 -06004002 default:
4003 logger->missingFunctionality("invocation operation");
4004 return spv::NoResult;
4005 }
4006}
4007
Rex Xu2bbbe062016-08-23 15:41:05 +08004008#ifdef AMD_EXTENSIONS
4009// Create group invocation operations on a vector
4010spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand)
4011{
4012 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4013 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4014 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd ||
4015 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4016 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4017 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
4018
4019 // Handle group invocation operations scalar by scalar.
4020 // The result type is the same type as the original type.
4021 // The algorithm is to:
4022 // - break the vector into scalars
4023 // - apply the operation to each scalar
4024 // - make a vector out the scalar results
4025
4026 // get the types sorted out
4027 int numComponents = builder.getNumComponents(operand);
4028 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operand));
4029 std::vector<spv::Id> results;
4030
4031 // do each scalar op
4032 for (int comp = 0; comp < numComponents; ++comp) {
4033 std::vector<unsigned int> indexes;
4034 indexes.push_back(comp);
4035 spv::Id scalar = builder.createCompositeExtract(operand, scalarType, indexes);
4036
4037 std::vector<spv::Id> operands;
4038 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4039 operands.push_back(spv::GroupOperationReduce);
4040 operands.push_back(scalar);
4041
4042 results.push_back(builder.createOp(op, scalarType, operands));
4043 }
4044
4045 // put the pieces together
4046 return builder.createCompositeConstruct(typeId, results);
4047}
4048#endif
4049
John Kessenich5e4b1242015-08-06 22:53:06 -06004050spv::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 -06004051{
Rex Xu8ff43de2016-04-22 16:51:45 +08004052 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
4054
John Kessenich140f3df2015-06-26 16:58:36 -06004055 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004056 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004058 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004059 spv::Id typeId0 = 0;
4060 if (consumedOperands > 0)
4061 typeId0 = builder.getTypeId(operands[0]);
4062 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004063
4064 switch (op) {
4065 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004066 if (isFloat)
4067 libCall = spv::GLSLstd450FMin;
4068 else if (isUnsigned)
4069 libCall = spv::GLSLstd450UMin;
4070 else
4071 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004072 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004073 break;
4074 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004076 break;
4077 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 if (isFloat)
4079 libCall = spv::GLSLstd450FMax;
4080 else if (isUnsigned)
4081 libCall = spv::GLSLstd450UMax;
4082 else
4083 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004084 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpDot:
4090 opCode = spv::OpDot;
4091 break;
4092 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095
4096 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 if (isFloat)
4098 libCall = spv::GLSLstd450FClamp;
4099 else if (isUnsigned)
4100 libCall = spv::GLSLstd450UClamp;
4101 else
4102 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004103 builder.promoteScalar(precision, operands.front(), operands[1]);
4104 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004105 break;
4106 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004107 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4108 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004109 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004110 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004111 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004112 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004113 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004114 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004115 break;
4116 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004118 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
4120 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004121 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004122 builder.promoteScalar(precision, operands[0], operands[2]);
4123 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125
4126 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004127 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004128 break;
4129 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004130 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004131 break;
4132 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004133 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004134 break;
4135 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004136 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004137 break;
4138 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004139 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004141 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004142 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004143 libCall = spv::GLSLstd450InterpolateAtSample;
4144 break;
4145 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004146 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004147 libCall = spv::GLSLstd450InterpolateAtOffset;
4148 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004149 case glslang::EOpAddCarry:
4150 opCode = spv::OpIAddCarry;
4151 typeId = builder.makeStructResultType(typeId0, typeId0);
4152 consumedOperands = 2;
4153 break;
4154 case glslang::EOpSubBorrow:
4155 opCode = spv::OpISubBorrow;
4156 typeId = builder.makeStructResultType(typeId0, typeId0);
4157 consumedOperands = 2;
4158 break;
4159 case glslang::EOpUMulExtended:
4160 opCode = spv::OpUMulExtended;
4161 typeId = builder.makeStructResultType(typeId0, typeId0);
4162 consumedOperands = 2;
4163 break;
4164 case glslang::EOpIMulExtended:
4165 opCode = spv::OpSMulExtended;
4166 typeId = builder.makeStructResultType(typeId0, typeId0);
4167 consumedOperands = 2;
4168 break;
4169 case glslang::EOpBitfieldExtract:
4170 if (isUnsigned)
4171 opCode = spv::OpBitFieldUExtract;
4172 else
4173 opCode = spv::OpBitFieldSExtract;
4174 break;
4175 case glslang::EOpBitfieldInsert:
4176 opCode = spv::OpBitFieldInsert;
4177 break;
4178
4179 case glslang::EOpFma:
4180 libCall = spv::GLSLstd450Fma;
4181 break;
4182 case glslang::EOpFrexp:
4183 libCall = spv::GLSLstd450FrexpStruct;
4184 if (builder.getNumComponents(operands[0]) == 1)
4185 frexpIntType = builder.makeIntegerType(32, true);
4186 else
4187 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4188 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4189 consumedOperands = 1;
4190 break;
4191 case glslang::EOpLdexp:
4192 libCall = spv::GLSLstd450Ldexp;
4193 break;
4194
Rex Xu574ab042016-04-14 16:53:07 +08004195 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004196 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004197 libCall = spv::GLSLstd450Bad;
4198 break;
4199
Rex Xu9d93a232016-05-05 12:30:44 +08004200#ifdef AMD_EXTENSIONS
4201 case glslang::EOpSwizzleInvocations:
4202 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4203 libCall = spv::SwizzleInvocationsAMD;
4204 break;
4205 case glslang::EOpSwizzleInvocationsMasked:
4206 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4207 libCall = spv::SwizzleInvocationsMaskedAMD;
4208 break;
4209 case glslang::EOpWriteInvocation:
4210 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4211 libCall = spv::WriteInvocationAMD;
4212 break;
4213
4214 case glslang::EOpMin3:
4215 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4216 if (isFloat)
4217 libCall = spv::FMin3AMD;
4218 else {
4219 if (isUnsigned)
4220 libCall = spv::UMin3AMD;
4221 else
4222 libCall = spv::SMin3AMD;
4223 }
4224 break;
4225 case glslang::EOpMax3:
4226 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4227 if (isFloat)
4228 libCall = spv::FMax3AMD;
4229 else {
4230 if (isUnsigned)
4231 libCall = spv::UMax3AMD;
4232 else
4233 libCall = spv::SMax3AMD;
4234 }
4235 break;
4236 case glslang::EOpMid3:
4237 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4238 if (isFloat)
4239 libCall = spv::FMid3AMD;
4240 else {
4241 if (isUnsigned)
4242 libCall = spv::UMid3AMD;
4243 else
4244 libCall = spv::SMid3AMD;
4245 }
4246 break;
4247
4248 case glslang::EOpInterpolateAtVertex:
4249 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4250 libCall = spv::InterpolateAtVertexAMD;
4251 break;
4252#endif
4253
John Kessenich140f3df2015-06-26 16:58:36 -06004254 default:
4255 return 0;
4256 }
4257
4258 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004259 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004260 // Use an extended instruction from the standard library.
4261 // Construct the call arguments, without modifying the original operands vector.
4262 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4263 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004264 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004265 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004266 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004267 case 0:
4268 // should all be handled by visitAggregate and createNoArgOperation
4269 assert(0);
4270 return 0;
4271 case 1:
4272 // should all be handled by createUnaryOperation
4273 assert(0);
4274 return 0;
4275 case 2:
4276 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4277 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004278 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004279 // anything 3 or over doesn't have l-value operands, so all should be consumed
4280 assert(consumedOperands == operands.size());
4281 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004282 break;
4283 }
4284 }
4285
John Kessenich55e7d112015-11-15 21:33:39 -07004286 // Decode the return types that were structures
4287 switch (op) {
4288 case glslang::EOpAddCarry:
4289 case glslang::EOpSubBorrow:
4290 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4291 id = builder.createCompositeExtract(id, typeId0, 0);
4292 break;
4293 case glslang::EOpUMulExtended:
4294 case glslang::EOpIMulExtended:
4295 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4296 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4297 break;
4298 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004299 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004300 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4301 id = builder.createCompositeExtract(id, typeId0, 0);
4302 break;
4303 default:
4304 break;
4305 }
4306
John Kessenich32cfd492016-02-02 12:37:46 -07004307 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004308}
4309
Rex Xu9d93a232016-05-05 12:30:44 +08004310// Intrinsics with no arguments (or no return value, and no precision).
4311spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004312{
4313 // TODO: get the barrier operands correct
4314
4315 switch (op) {
4316 case glslang::EOpEmitVertex:
4317 builder.createNoResultOp(spv::OpEmitVertex);
4318 return 0;
4319 case glslang::EOpEndPrimitive:
4320 builder.createNoResultOp(spv::OpEndPrimitive);
4321 return 0;
4322 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004323 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004324 return 0;
4325 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004326 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004327 return 0;
4328 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004329 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004330 return 0;
4331 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004332 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004333 return 0;
4334 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004335 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004336 return 0;
4337 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004338 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004339 return 0;
4340 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004341 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004342 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004343 case glslang::EOpAllMemoryBarrierWithGroupSync:
4344 // Control barrier with non-"None" semantic is also a memory barrier.
4345 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4346 return 0;
4347 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4348 // Control barrier with non-"None" semantic is also a memory barrier.
4349 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4350 return 0;
4351 case glslang::EOpWorkgroupMemoryBarrier:
4352 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4353 return 0;
4354 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4355 // Control barrier with non-"None" semantic is also a memory barrier.
4356 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4357 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004358#ifdef AMD_EXTENSIONS
4359 case glslang::EOpTime:
4360 {
4361 std::vector<spv::Id> args; // Dummy arguments
4362 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4363 return builder.setPrecision(id, precision);
4364 }
4365#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004366 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004367 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004368 return 0;
4369 }
4370}
4371
4372spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4373{
John Kessenich2f273362015-07-18 22:34:27 -06004374 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004375 spv::Id id;
4376 if (symbolValues.end() != iter) {
4377 id = iter->second;
4378 return id;
4379 }
4380
4381 // it was not found, create it
4382 id = createSpvVariable(symbol);
4383 symbolValues[symbol->getId()] = id;
4384
Rex Xuc884b4a2016-06-29 15:03:44 +08004385 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004386 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004387 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004388 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004389 if (symbol->getType().getQualifier().hasSpecConstantId())
4390 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004391 if (symbol->getQualifier().hasIndex())
4392 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4393 if (symbol->getQualifier().hasComponent())
4394 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4395 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004396 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004397 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004398 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004399 if (symbol->getQualifier().hasXfbBuffer())
4400 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4401 if (symbol->getQualifier().hasXfbOffset())
4402 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4403 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004404 // atomic counters use this:
4405 if (symbol->getQualifier().hasOffset())
4406 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004407 }
4408
scygan2c864272016-05-18 18:09:17 +02004409 if (symbol->getQualifier().hasLocation())
4410 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004411 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004412 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004413 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004414 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004415 }
John Kessenich140f3df2015-06-26 16:58:36 -06004416 if (symbol->getQualifier().hasSet())
4417 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004418 else if (IsDescriptorResource(symbol->getType())) {
4419 // default to 0
4420 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4421 }
John Kessenich140f3df2015-06-26 16:58:36 -06004422 if (symbol->getQualifier().hasBinding())
4423 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004424 if (symbol->getQualifier().hasAttachment())
4425 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004426 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004427 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004428 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004429 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004430 if (symbol->getQualifier().hasXfbBuffer())
4431 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4432 }
4433
Rex Xu1da878f2016-02-21 20:59:01 +08004434 if (symbol->getType().isImage()) {
4435 std::vector<spv::Decoration> memory;
4436 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4437 for (unsigned int i = 0; i < memory.size(); ++i)
4438 addDecoration(id, memory[i]);
4439 }
4440
John Kessenich140f3df2015-06-26 16:58:36 -06004441 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004442 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004443 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004444 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004445
John Kessenich140f3df2015-06-26 16:58:36 -06004446 return id;
4447}
4448
John Kessenich55e7d112015-11-15 21:33:39 -07004449// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004450void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4451{
John Kessenich4016e382016-07-15 11:53:56 -06004452 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004453 builder.addDecoration(id, dec);
4454}
4455
John Kessenich55e7d112015-11-15 21:33:39 -07004456// If 'dec' is valid, add a one-operand decoration to an object
4457void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4458{
John Kessenich4016e382016-07-15 11:53:56 -06004459 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004460 builder.addDecoration(id, dec, value);
4461}
4462
4463// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004464void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4465{
John Kessenich4016e382016-07-15 11:53:56 -06004466 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004467 builder.addMemberDecoration(id, (unsigned)member, dec);
4468}
4469
John Kessenich92187592016-02-01 13:45:25 -07004470// If 'dec' is valid, add a one-operand decoration to a struct member
4471void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4472{
John Kessenich4016e382016-07-15 11:53:56 -06004473 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004474 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4475}
4476
John Kessenich55e7d112015-11-15 21:33:39 -07004477// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004478// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004479//
4480// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4481//
4482// Recursively walk the nodes. The nodes form a tree whose leaves are
4483// regular constants, which themselves are trees that createSpvConstant()
4484// recursively walks. So, this function walks the "top" of the tree:
4485// - emit specialization constant-building instructions for specConstant
4486// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004487spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004488{
John Kessenich7cc0e282016-03-20 00:46:02 -06004489 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004490
qining4f4bb812016-04-03 23:55:17 -04004491 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004492 if (! node.getQualifier().specConstant) {
4493 // hand off to the non-spec-constant path
4494 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4495 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004496 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004497 nextConst, false);
4498 }
4499
4500 // We now know we have a specialization constant to build
4501
John Kessenichd94c0032016-05-30 19:29:40 -06004502 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004503 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4504 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4505 std::vector<spv::Id> dimConstId;
4506 for (int dim = 0; dim < 3; ++dim) {
4507 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4508 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4509 if (specConst)
4510 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4511 }
4512 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4513 }
4514
4515 // An AST node labelled as specialization constant should be a symbol node.
4516 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4517 if (auto* sn = node.getAsSymbolNode()) {
4518 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004519 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4520 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4521 // will set the builder into spec constant op instruction generating mode.
4522 sub_tree->traverse(this);
4523 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004524 } else if (auto* const_union_array = &sn->getConstArray()){
4525 int nextConst = 0;
4526 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004527 }
4528 }
qining4f4bb812016-04-03 23:55:17 -04004529
4530 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4531 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004532 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004533 exit(1);
4534 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004535}
4536
John Kessenich140f3df2015-06-26 16:58:36 -06004537// Use 'consts' as the flattened glslang source of scalar constants to recursively
4538// build the aggregate SPIR-V constant.
4539//
4540// If there are not enough elements present in 'consts', 0 will be substituted;
4541// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4542//
qining08408382016-03-21 09:51:37 -04004543spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004544{
4545 // vector of constants for SPIR-V
4546 std::vector<spv::Id> spvConsts;
4547
4548 // Type is used for struct and array constants
4549 spv::Id typeId = convertGlslangToSpvType(glslangType);
4550
4551 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004552 glslang::TType elementType(glslangType, 0);
4553 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004554 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004555 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004556 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004557 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004558 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004559 } else if (glslangType.getStruct()) {
4560 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4561 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004562 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004563 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004564 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4565 bool zero = nextConst >= consts.size();
4566 switch (glslangType.getBasicType()) {
4567 case glslang::EbtInt:
4568 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4569 break;
4570 case glslang::EbtUint:
4571 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4572 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004573 case glslang::EbtInt64:
4574 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4575 break;
4576 case glslang::EbtUint64:
4577 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4578 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004579 case glslang::EbtFloat:
4580 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4581 break;
4582 case glslang::EbtDouble:
4583 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4584 break;
4585 case glslang::EbtBool:
4586 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4587 break;
4588 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004589 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004590 break;
4591 }
4592 ++nextConst;
4593 }
4594 } else {
4595 // we have a non-aggregate (scalar) constant
4596 bool zero = nextConst >= consts.size();
4597 spv::Id scalar = 0;
4598 switch (glslangType.getBasicType()) {
4599 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004600 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004601 break;
4602 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004603 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004604 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004605 case glslang::EbtInt64:
4606 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4607 break;
4608 case glslang::EbtUint64:
4609 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4610 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004611 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004612 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004613 break;
4614 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004615 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004616 break;
4617 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004618 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004619 break;
4620 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004621 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004622 break;
4623 }
4624 ++nextConst;
4625 return scalar;
4626 }
4627
4628 return builder.makeCompositeConstant(typeId, spvConsts);
4629}
4630
John Kessenich7c1aa102015-10-15 13:29:11 -06004631// Return true if the node is a constant or symbol whose reading has no
4632// non-trivial observable cost or effect.
4633bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4634{
4635 // don't know what this is
4636 if (node == nullptr)
4637 return false;
4638
4639 // a constant is safe
4640 if (node->getAsConstantUnion() != nullptr)
4641 return true;
4642
4643 // not a symbol means non-trivial
4644 if (node->getAsSymbolNode() == nullptr)
4645 return false;
4646
4647 // a symbol, depends on what's being read
4648 switch (node->getType().getQualifier().storage) {
4649 case glslang::EvqTemporary:
4650 case glslang::EvqGlobal:
4651 case glslang::EvqIn:
4652 case glslang::EvqInOut:
4653 case glslang::EvqConst:
4654 case glslang::EvqConstReadOnly:
4655 case glslang::EvqUniform:
4656 return true;
4657 default:
4658 return false;
4659 }
qining25262b32016-05-06 17:25:16 -04004660}
John Kessenich7c1aa102015-10-15 13:29:11 -06004661
4662// A node is trivial if it is a single operation with no side effects.
4663// Error on the side of saying non-trivial.
4664// Return true if trivial.
4665bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4666{
4667 if (node == nullptr)
4668 return false;
4669
4670 // symbols and constants are trivial
4671 if (isTrivialLeaf(node))
4672 return true;
4673
4674 // otherwise, it needs to be a simple operation or one or two leaf nodes
4675
4676 // not a simple operation
4677 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4678 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4679 if (binaryNode == nullptr && unaryNode == nullptr)
4680 return false;
4681
4682 // not on leaf nodes
4683 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4684 return false;
4685
4686 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4687 return false;
4688 }
4689
4690 switch (node->getAsOperator()->getOp()) {
4691 case glslang::EOpLogicalNot:
4692 case glslang::EOpConvIntToBool:
4693 case glslang::EOpConvUintToBool:
4694 case glslang::EOpConvFloatToBool:
4695 case glslang::EOpConvDoubleToBool:
4696 case glslang::EOpEqual:
4697 case glslang::EOpNotEqual:
4698 case glslang::EOpLessThan:
4699 case glslang::EOpGreaterThan:
4700 case glslang::EOpLessThanEqual:
4701 case glslang::EOpGreaterThanEqual:
4702 case glslang::EOpIndexDirect:
4703 case glslang::EOpIndexDirectStruct:
4704 case glslang::EOpLogicalXor:
4705 case glslang::EOpAny:
4706 case glslang::EOpAll:
4707 return true;
4708 default:
4709 return false;
4710 }
4711}
4712
4713// Emit short-circuiting code, where 'right' is never evaluated unless
4714// the left side is true (for &&) or false (for ||).
4715spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4716{
4717 spv::Id boolTypeId = builder.makeBoolType();
4718
4719 // emit left operand
4720 builder.clearAccessChain();
4721 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004722 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004723
4724 // Operands to accumulate OpPhi operands
4725 std::vector<spv::Id> phiOperands;
4726 // accumulate left operand's phi information
4727 phiOperands.push_back(leftId);
4728 phiOperands.push_back(builder.getBuildPoint()->getId());
4729
4730 // Make the two kinds of operation symmetric with a "!"
4731 // || => emit "if (! left) result = right"
4732 // && => emit "if ( left) result = right"
4733 //
4734 // TODO: this runtime "not" for || could be avoided by adding functionality
4735 // to 'builder' to have an "else" without an "then"
4736 if (op == glslang::EOpLogicalOr)
4737 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4738
4739 // make an "if" based on the left value
4740 spv::Builder::If ifBuilder(leftId, builder);
4741
4742 // emit right operand as the "then" part of the "if"
4743 builder.clearAccessChain();
4744 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004745 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004746
4747 // accumulate left operand's phi information
4748 phiOperands.push_back(rightId);
4749 phiOperands.push_back(builder.getBuildPoint()->getId());
4750
4751 // finish the "if"
4752 ifBuilder.makeEndIf();
4753
4754 // phi together the two results
4755 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4756}
4757
Rex Xu9d93a232016-05-05 12:30:44 +08004758// Return type Id of the imported set of extended instructions corresponds to the name.
4759// Import this set if it has not been imported yet.
4760spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4761{
4762 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4763 return extBuiltinMap[name];
4764 else {
4765 builder.addExtensions(name);
4766 spv::Id extBuiltins = builder.import(name);
4767 extBuiltinMap[name] = extBuiltins;
4768 return extBuiltins;
4769 }
4770}
4771
John Kessenich140f3df2015-06-26 16:58:36 -06004772}; // end anonymous namespace
4773
4774namespace glslang {
4775
John Kessenich68d78fd2015-07-12 19:28:10 -06004776void GetSpirvVersion(std::string& version)
4777{
John Kessenich9e55f632015-07-15 10:03:39 -06004778 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004779 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004780 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004781 version = buf;
4782}
4783
John Kessenich140f3df2015-06-26 16:58:36 -06004784// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004785void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004786{
4787 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004788 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004789 for (int i = 0; i < (int)spirv.size(); ++i) {
4790 unsigned int word = spirv[i];
4791 out.write((const char*)&word, 4);
4792 }
4793 out.close();
4794}
4795
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004796// Write SPIR-V out to a text file with 32-bit hexadecimal words
4797void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4798{
4799 std::ofstream out;
4800 out.open(baseName, std::ios::binary | std::ios::out);
4801 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4802 const int WORDS_PER_LINE = 8;
4803 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4804 out << "\t";
4805 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4806 const unsigned int word = spirv[i + j];
4807 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4808 if (i + j + 1 < (int)spirv.size()) {
4809 out << ",";
4810 }
4811 }
4812 out << std::endl;
4813 }
4814 out.close();
4815}
4816
John Kessenich140f3df2015-06-26 16:58:36 -06004817//
4818// Set up the glslang traversal
4819//
4820void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4821{
Lei Zhang17535f72016-05-04 15:55:59 -04004822 spv::SpvBuildLogger logger;
4823 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004824}
4825
Lei Zhang17535f72016-05-04 15:55:59 -04004826void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004827{
John Kessenich140f3df2015-06-26 16:58:36 -06004828 TIntermNode* root = intermediate.getTreeRoot();
4829
4830 if (root == 0)
4831 return;
4832
4833 glslang::GetThreadPoolAllocator().push();
4834
Lei Zhang17535f72016-05-04 15:55:59 -04004835 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004836
4837 root->traverse(&it);
4838
4839 it.dumpSpv(spirv);
4840
4841 glslang::GetThreadPoolAllocator().pop();
4842}
4843
4844}; // end namespace glslang