blob: 5f631b4db1f374956297b958dd9a20cb94024586 [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);
152 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +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 Xu9d93a232016-05-05 12:30:44 +0800156 spv::Id createInvocationsOperation(glslang::TOperator, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600157 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 +0800158 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600159 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
160 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700161 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700163 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400164 spv::Id createSpvConstant(const glslang::TIntermTyped&);
165 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600166 bool isTrivialLeaf(const glslang::TIntermTyped* node);
167 bool isTrivial(const glslang::TIntermTyped* node);
168 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800169 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600170
171 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700172 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600173 int sequenceDepth;
174
Lei Zhang17535f72016-05-04 15:55:59 -0400175 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400176
John Kessenich140f3df2015-06-26 16:58:36 -0600177 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
178 spv::Builder builder;
179 bool inMain;
180 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700181 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 -0700182 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600183 const glslang::TIntermediate* glslangIntermediate;
184 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800185 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600186
John Kessenich2f273362015-07-18 22:34:27 -0600187 std::unordered_map<int, spv::Id> symbolValues;
188 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
189 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700190 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600191 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 -0600192 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600193};
194
195//
196// Helper functions for translating glslang representations to SPIR-V enumerants.
197//
198
199// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700200spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600201{
John Kessenich66e2faf2016-03-12 18:34:36 -0700202 switch (source) {
203 case glslang::EShSourceGlsl:
204 switch (profile) {
205 case ENoProfile:
206 case ECoreProfile:
207 case ECompatibilityProfile:
208 return spv::SourceLanguageGLSL;
209 case EEsProfile:
210 return spv::SourceLanguageESSL;
211 default:
212 return spv::SourceLanguageUnknown;
213 }
214 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400215 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
216 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600217 default:
218 return spv::SourceLanguageUnknown;
219 }
220}
221
222// Translate glslang language (stage) to SPIR-V execution model.
223spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
224{
225 switch (stage) {
226 case EShLangVertex: return spv::ExecutionModelVertex;
227 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
228 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
229 case EShLangGeometry: return spv::ExecutionModelGeometry;
230 case EShLangFragment: return spv::ExecutionModelFragment;
231 case EShLangCompute: return spv::ExecutionModelGLCompute;
232 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700233 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600234 return spv::ExecutionModelFragment;
235 }
236}
237
238// Translate glslang type to SPIR-V storage class.
239spv::StorageClass TranslateStorageClass(const glslang::TType& type)
240{
241 if (type.getQualifier().isPipeInput())
242 return spv::StorageClassInput;
243 else if (type.getQualifier().isPipeOutput())
244 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700245 else if (type.getBasicType() == glslang::EbtSampler)
246 return spv::StorageClassUniformConstant;
247 else if (type.getBasicType() == glslang::EbtAtomicUint)
248 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600249 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700250 if (type.getQualifier().layoutPushConstant)
251 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600252 if (type.getBasicType() == glslang::EbtBlock)
253 return spv::StorageClassUniform;
254 else
255 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600256 // 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 -0600257 } else {
258 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700259 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
260 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
262 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400263 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700264 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600265 return spv::StorageClassFunction;
266 }
267 }
268}
269
270// Translate glslang sampler type to SPIR-V dimensionality.
271spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
272{
273 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700274 case glslang::Esd1D: return spv::Dim1D;
275 case glslang::Esd2D: return spv::Dim2D;
276 case glslang::Esd3D: return spv::Dim3D;
277 case glslang::EsdCube: return spv::DimCube;
278 case glslang::EsdRect: return spv::DimRect;
279 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700280 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600281 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700282 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600283 return spv::Dim2D;
284 }
285}
286
John Kessenichf6640762016-08-01 19:44:00 -0600287// Translate glslang precision to SPIR-V precision decorations.
288spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600289{
John Kessenichf6640762016-08-01 19:44:00 -0600290 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700291 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600292 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600293 default:
294 return spv::NoPrecision;
295 }
296}
297
John Kessenichf6640762016-08-01 19:44:00 -0600298// Translate glslang type to SPIR-V precision decorations.
299spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
300{
301 return TranslatePrecisionDecoration(type.getQualifier().precision);
302}
303
John Kessenich140f3df2015-06-26 16:58:36 -0600304// Translate glslang type to SPIR-V block decorations.
305spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
306{
307 if (type.getBasicType() == glslang::EbtBlock) {
308 switch (type.getQualifier().storage) {
309 case glslang::EvqUniform: return spv::DecorationBlock;
310 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
311 case glslang::EvqVaryingIn: return spv::DecorationBlock;
312 case glslang::EvqVaryingOut: return spv::DecorationBlock;
313 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700314 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600315 break;
316 }
317 }
318
John Kessenich4016e382016-07-15 11:53:56 -0600319 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600320}
321
Rex Xu1da878f2016-02-21 20:59:01 +0800322// Translate glslang type to SPIR-V memory decorations.
323void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
324{
325 if (qualifier.coherent)
326 memory.push_back(spv::DecorationCoherent);
327 if (qualifier.volatil)
328 memory.push_back(spv::DecorationVolatile);
329 if (qualifier.restrict)
330 memory.push_back(spv::DecorationRestrict);
331 if (qualifier.readonly)
332 memory.push_back(spv::DecorationNonWritable);
333 if (qualifier.writeonly)
334 memory.push_back(spv::DecorationNonReadable);
335}
336
John Kessenich140f3df2015-06-26 16:58:36 -0600337// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700338spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600339{
340 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700341 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::ElmRowMajor:
343 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700344 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700346 default:
347 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600348 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600349 }
350 } else {
351 switch (type.getBasicType()) {
352 default:
John Kessenich4016e382016-07-15 11:53:56 -0600353 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 break;
355 case glslang::EbtBlock:
356 switch (type.getQualifier().storage) {
357 case glslang::EvqUniform:
358 case glslang::EvqBuffer:
359 switch (type.getQualifier().layoutPacking) {
360 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
362 default:
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 }
365 case glslang::EvqVaryingIn:
366 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700367 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600368 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700370 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 }
373 }
374 }
375}
376
377// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600378// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700379// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800380spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600381{
Rex Xubbceed72016-05-21 09:40:44 +0800382 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700383 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600384 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800385 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700386 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800389#ifdef AMD_EXTENSIONS
390 else if (qualifier.explicitInterp)
391 return spv::DecorationExplicitInterpAMD;
392#endif
Rex Xubbceed72016-05-21 09:40:44 +0800393 else
John Kessenich4016e382016-07-15 11:53:56 -0600394 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800395}
396
397// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600398// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800399// should be applied.
400spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
401{
402 if (qualifier.patch)
403 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700404 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600405 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700406 else if (qualifier.sample) {
407 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600408 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700409 } else
John Kessenich4016e382016-07-15 11:53:56 -0600410 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600411}
412
John Kessenich92187592016-02-01 13:45:25 -0700413// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700414spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600415{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700416 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600417 return spv::DecorationInvariant;
418 else
John Kessenich4016e382016-07-15 11:53:56 -0600419 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600420}
421
qining9220dbb2016-05-04 17:34:38 -0400422// If glslang type is noContraction, return SPIR-V NoContraction decoration.
423spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
424{
425 if (qualifier.noContraction)
426 return spv::DecorationNoContraction;
427 else
John Kessenich4016e382016-07-15 11:53:56 -0600428 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400429}
430
David Netoa901ffe2016-06-08 14:11:40 +0100431// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
432// associated capabilities when required. For some built-in variables, a capability
433// is generated only when using the variable in an executable instruction, but not when
434// just declaring a struct member variable with it. This is true for PointSize,
435// ClipDistance, and CullDistance.
436spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600437{
438 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700439 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600440 // Defer adding the capability until the built-in is actually used.
441 if (! memberDeclaration) {
442 switch (glslangIntermediate->getStage()) {
443 case EShLangGeometry:
444 builder.addCapability(spv::CapabilityGeometryPointSize);
445 break;
446 case EShLangTessControl:
447 case EShLangTessEvaluation:
448 builder.addCapability(spv::CapabilityTessellationPointSize);
449 break;
450 default:
451 break;
452 }
John Kessenich92187592016-02-01 13:45:25 -0700453 }
454 return spv::BuiltInPointSize;
455
John Kessenichebb50532016-05-16 19:22:05 -0600456 // These *Distance capabilities logically belong here, but if the member is declared and
457 // then never used, consumers of SPIR-V prefer the capability not be declared.
458 // They are now generated when used, rather than here when declared.
459 // Potentially, the specification should be more clear what the minimum
460 // use needed is to trigger the capability.
461 //
John Kessenich92187592016-02-01 13:45:25 -0700462 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100463 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600464 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700465 return spv::BuiltInClipDistance;
466
467 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100468 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600469 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700470 return spv::BuiltInCullDistance;
471
472 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500473 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700474 return spv::BuiltInViewportIndex;
475
John Kessenich5e801132016-02-15 11:09:46 -0700476 case glslang::EbvSampleId:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleId;
479
480 case glslang::EbvSamplePosition:
481 builder.addCapability(spv::CapabilitySampleRateShading);
482 return spv::BuiltInSamplePosition;
483
484 case glslang::EbvSampleMask:
485 builder.addCapability(spv::CapabilitySampleRateShading);
486 return spv::BuiltInSampleMask;
487
John Kessenich78a45572016-07-08 14:05:15 -0600488 case glslang::EbvLayer:
489 builder.addCapability(spv::CapabilityGeometry);
490 return spv::BuiltInLayer;
491
John Kessenich140f3df2015-06-26 16:58:36 -0600492 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600493 case glslang::EbvVertexId: return spv::BuiltInVertexId;
494 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700495 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
496 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600497 case glslang::EbvBaseVertex:
498 case glslang::EbvBaseInstance:
499 case glslang::EbvDrawId:
500 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600501 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600502 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600503 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
504 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600505 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
506 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
507 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
508 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
509 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
510 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
511 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600512 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
513 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
514 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
515 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
516 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
517 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
518 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
519 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800520 case glslang::EbvSubGroupSize:
521 case glslang::EbvSubGroupInvocation:
522 case glslang::EbvSubGroupEqMask:
523 case glslang::EbvSubGroupGeMask:
524 case glslang::EbvSubGroupGtMask:
525 case glslang::EbvSubGroupLeMask:
526 case glslang::EbvSubGroupLtMask:
527 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600528 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600529 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800530#ifdef AMD_EXTENSIONS
531 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
532 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
533 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
534 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
535 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
536 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
537 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
538#endif
John Kessenich4016e382016-07-15 11:53:56 -0600539 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600540 }
541}
542
Rex Xufc618912015-09-09 16:42:49 +0800543// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700544spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800545{
546 assert(type.getBasicType() == glslang::EbtSampler);
547
John Kessenich5d0fa972016-02-15 11:57:00 -0700548 // Check for capabilities
549 switch (type.getQualifier().layoutFormat) {
550 case glslang::ElfRg32f:
551 case glslang::ElfRg16f:
552 case glslang::ElfR11fG11fB10f:
553 case glslang::ElfR16f:
554 case glslang::ElfRgba16:
555 case glslang::ElfRgb10A2:
556 case glslang::ElfRg16:
557 case glslang::ElfRg8:
558 case glslang::ElfR16:
559 case glslang::ElfR8:
560 case glslang::ElfRgba16Snorm:
561 case glslang::ElfRg16Snorm:
562 case glslang::ElfRg8Snorm:
563 case glslang::ElfR16Snorm:
564 case glslang::ElfR8Snorm:
565
566 case glslang::ElfRg32i:
567 case glslang::ElfRg16i:
568 case glslang::ElfRg8i:
569 case glslang::ElfR16i:
570 case glslang::ElfR8i:
571
572 case glslang::ElfRgb10a2ui:
573 case glslang::ElfRg32ui:
574 case glslang::ElfRg16ui:
575 case glslang::ElfRg8ui:
576 case glslang::ElfR16ui:
577 case glslang::ElfR8ui:
578 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
579 break;
580
581 default:
582 break;
583 }
584
585 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800586 switch (type.getQualifier().layoutFormat) {
587 case glslang::ElfNone: return spv::ImageFormatUnknown;
588 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
589 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
590 case glslang::ElfR32f: return spv::ImageFormatR32f;
591 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
592 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
593 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
594 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
595 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
596 case glslang::ElfR16f: return spv::ImageFormatR16f;
597 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
598 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
599 case glslang::ElfRg16: return spv::ImageFormatRg16;
600 case glslang::ElfRg8: return spv::ImageFormatRg8;
601 case glslang::ElfR16: return spv::ImageFormatR16;
602 case glslang::ElfR8: return spv::ImageFormatR8;
603 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
604 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
605 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
606 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
607 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
608 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
609 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
610 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
611 case glslang::ElfR32i: return spv::ImageFormatR32i;
612 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
613 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
614 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
615 case glslang::ElfR16i: return spv::ImageFormatR16i;
616 case glslang::ElfR8i: return spv::ImageFormatR8i;
617 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
618 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
619 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
620 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
621 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
622 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
623 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
624 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
625 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
626 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600627 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800628 }
629}
630
qining25262b32016-05-06 17:25:16 -0400631// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700632// descriptor set.
633bool IsDescriptorResource(const glslang::TType& type)
634{
John Kessenichf7497e22016-03-08 21:36:22 -0700635 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700636 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700637 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700638
639 // non block...
640 // basically samplerXXX/subpass/sampler/texture are all included
641 // if they are the global-scope-class, not the function parameter
642 // (or local, if they ever exist) class.
643 if (type.getBasicType() == glslang::EbtSampler)
644 return type.getQualifier().isUniformOrBuffer();
645
646 // None of the above.
647 return false;
648}
649
John Kesseniche0b6cad2015-12-24 10:30:13 -0700650void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
651{
652 if (child.layoutMatrix == glslang::ElmNone)
653 child.layoutMatrix = parent.layoutMatrix;
654
655 if (parent.invariant)
656 child.invariant = true;
657 if (parent.nopersp)
658 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800659#ifdef AMD_EXTENSIONS
660 if (parent.explicitInterp)
661 child.explicitInterp = true;
662#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700663 if (parent.flat)
664 child.flat = true;
665 if (parent.centroid)
666 child.centroid = true;
667 if (parent.patch)
668 child.patch = true;
669 if (parent.sample)
670 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800671 if (parent.coherent)
672 child.coherent = true;
673 if (parent.volatil)
674 child.volatil = true;
675 if (parent.restrict)
676 child.restrict = true;
677 if (parent.readonly)
678 child.readonly = true;
679 if (parent.writeonly)
680 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700681}
682
683bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
684{
John Kessenich7b9fa252016-01-21 18:56:57 -0700685 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700686 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600687 // - affect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700688 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600689 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700690}
691
John Kessenich140f3df2015-06-26 16:58:36 -0600692//
693// Implement the TGlslangToSpvTraverser class.
694//
695
Lei Zhang17535f72016-05-04 15:55:59 -0400696TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
697 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
698 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600699 inMain(false), mainTerminated(false), linkageOnly(false),
700 glslangIntermediate(glslangIntermediate)
701{
702 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
703
704 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700705 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600706 stdBuiltins = builder.import("GLSL.std.450");
707 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700708 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
709 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600710
711 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600712 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
713 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600714 builder.addSourceExtension(it->c_str());
715
716 // Add the top-level modes for this shader.
717
John Kessenich92187592016-02-01 13:45:25 -0700718 if (glslangIntermediate->getXfbMode()) {
719 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600720 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700721 }
John Kessenich140f3df2015-06-26 16:58:36 -0600722
723 unsigned int mode;
724 switch (glslangIntermediate->getStage()) {
725 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600726 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600727 break;
728
729 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600730 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600731 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
732 break;
733
734 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600735 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600736 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700737 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
738 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
739 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600740 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600741 }
John Kessenich4016e382016-07-15 11:53:56 -0600742 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600743 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
744
John Kesseniche6903322015-10-13 16:29:02 -0600745 switch (glslangIntermediate->getVertexSpacing()) {
746 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
747 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
748 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600749 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600750 }
John Kessenich4016e382016-07-15 11:53:56 -0600751 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600752 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
753
754 switch (glslangIntermediate->getVertexOrder()) {
755 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
756 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600757 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600758 }
John Kessenich4016e382016-07-15 11:53:56 -0600759 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600760 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
761
762 if (glslangIntermediate->getPointMode())
763 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600764 break;
765
766 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600767 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600768 switch (glslangIntermediate->getInputPrimitive()) {
769 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
770 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
771 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700772 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600773 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600774 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600775 }
John Kessenich4016e382016-07-15 11:53:56 -0600776 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600777 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600778
John Kessenich140f3df2015-06-26 16:58:36 -0600779 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
780
781 switch (glslangIntermediate->getOutputPrimitive()) {
782 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
783 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
784 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600785 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600786 }
John Kessenich4016e382016-07-15 11:53:56 -0600787 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600788 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
789 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
790 break;
791
792 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600793 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600794 if (glslangIntermediate->getPixelCenterInteger())
795 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600796
John Kessenich140f3df2015-06-26 16:58:36 -0600797 if (glslangIntermediate->getOriginUpperLeft())
798 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600799 else
800 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600801
802 if (glslangIntermediate->getEarlyFragmentTests())
803 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
804
805 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600806 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
807 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600808 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600809 }
John Kessenich4016e382016-07-15 11:53:56 -0600810 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600811 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
812
813 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
814 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600815 break;
816
817 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600818 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600819 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
820 glslangIntermediate->getLocalSize(1),
821 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600822 break;
823
824 default:
825 break;
826 }
827
828}
829
John Kessenich7ba63412015-12-20 17:37:07 -0700830// Finish everything and dump
831void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
832{
833 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100834 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
835 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700836
qiningda397332016-03-09 19:54:03 -0500837 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700838 builder.dump(out);
839}
840
John Kessenich140f3df2015-06-26 16:58:36 -0600841TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
842{
843 if (! mainTerminated) {
844 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
845 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600846 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600847 }
848}
849
850//
851// Implement the traversal functions.
852//
853// Return true from interior nodes to have the external traversal
854// continue on to children. Return false if children were
855// already processed.
856//
857
858//
qining25262b32016-05-06 17:25:16 -0400859// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600860// - uniform/input reads
861// - output writes
862// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
863// - something simple that degenerates into the last bullet
864//
865void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
866{
qining75d1d802016-04-06 14:42:01 -0400867 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
868 if (symbol->getType().getQualifier().isSpecConstant())
869 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
870
John Kessenich140f3df2015-06-26 16:58:36 -0600871 // getSymbolId() will set up all the IO decorations on the first call.
872 // Formal function parameters were mapped during makeFunctions().
873 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700874
875 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
876 if (builder.isPointer(id)) {
877 spv::StorageClass sc = builder.getStorageClass(id);
878 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
879 iOSet.insert(id);
880 }
881
882 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700883 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600884 // Prepare to generate code for the access
885
886 // L-value chains will be computed left to right. We're on the symbol now,
887 // which is the left-most part of the access chain, so now is "clear" time,
888 // followed by setting the base.
889 builder.clearAccessChain();
890
891 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700892 // except for
893 // A) "const in" arguments to a function, which are an intermediate object.
894 // See comments in handleUserFunctionCall().
895 // B) Specialization constants (normal constant don't even come in as a variable),
896 // These are also pure R-values.
897 glslang::TQualifier qualifier = symbol->getQualifier();
898 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
899 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600900 builder.setAccessChainRValue(id);
901 else
902 builder.setAccessChainLValue(id);
903 }
904}
905
906bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
907{
qining40887662016-04-03 22:20:42 -0400908 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
909 if (node->getType().getQualifier().isSpecConstant())
910 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
911
John Kessenich140f3df2015-06-26 16:58:36 -0600912 // First, handle special cases
913 switch (node->getOp()) {
914 case glslang::EOpAssign:
915 case glslang::EOpAddAssign:
916 case glslang::EOpSubAssign:
917 case glslang::EOpMulAssign:
918 case glslang::EOpVectorTimesMatrixAssign:
919 case glslang::EOpVectorTimesScalarAssign:
920 case glslang::EOpMatrixTimesScalarAssign:
921 case glslang::EOpMatrixTimesMatrixAssign:
922 case glslang::EOpDivAssign:
923 case glslang::EOpModAssign:
924 case glslang::EOpAndAssign:
925 case glslang::EOpInclusiveOrAssign:
926 case glslang::EOpExclusiveOrAssign:
927 case glslang::EOpLeftShiftAssign:
928 case glslang::EOpRightShiftAssign:
929 // A bin-op assign "a += b" means the same thing as "a = a + b"
930 // where a is evaluated before b. For a simple assignment, GLSL
931 // says to evaluate the left before the right. So, always, left
932 // node then right node.
933 {
934 // get the left l-value, save it away
935 builder.clearAccessChain();
936 node->getLeft()->traverse(this);
937 spv::Builder::AccessChain lValue = builder.getAccessChain();
938
939 // evaluate the right
940 builder.clearAccessChain();
941 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700942 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600943
944 if (node->getOp() != glslang::EOpAssign) {
945 // the left is also an r-value
946 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700947 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600948
949 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600950 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400951 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600952 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
953 node->getType().getBasicType());
954
955 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700956 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600957 }
958
959 // store the result
960 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800961 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600962
963 // assignments are expressions having an rValue after they are evaluated...
964 builder.clearAccessChain();
965 builder.setAccessChainRValue(rValue);
966 }
967 return false;
968 case glslang::EOpIndexDirect:
969 case glslang::EOpIndexDirectStruct:
970 {
971 // Get the left part of the access chain.
972 node->getLeft()->traverse(this);
973
974 // Add the next element in the chain
975
David Netoa901ffe2016-06-08 14:11:40 +0100976 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600977 if (! node->getLeft()->getType().isArray() &&
978 node->getLeft()->getType().isVector() &&
979 node->getOp() == glslang::EOpIndexDirect) {
980 // This is essentially a hard-coded vector swizzle of size 1,
981 // so short circuit the access-chain stuff with a swizzle.
982 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100983 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600984 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600985 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100986 int spvIndex = glslangIndex;
987 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
988 node->getOp() == glslang::EOpIndexDirectStruct)
989 {
990 // This may be, e.g., an anonymous block-member selection, which generally need
991 // index remapping due to hidden members in anonymous blocks.
992 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
993 assert(remapper.size() > 0);
994 spvIndex = remapper[glslangIndex];
995 }
John Kessenichebb50532016-05-16 19:22:05 -0600996
David Netoa901ffe2016-06-08 14:11:40 +0100997 // normal case for indexing array or structure or block
998 builder.accessChainPush(builder.makeIntConstant(spvIndex));
999
1000 // Add capabilities here for accessing PointSize and clip/cull distance.
1001 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001002 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001003 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001004 }
1005 }
1006 return false;
1007 case glslang::EOpIndexIndirect:
1008 {
1009 // Structure or array or vector indirection.
1010 // Will use native SPIR-V access-chain for struct and array indirection;
1011 // matrices are arrays of vectors, so will also work for a matrix.
1012 // Will use the access chain's 'component' for variable index into a vector.
1013
1014 // This adapter is building access chains left to right.
1015 // Set up the access chain to the left.
1016 node->getLeft()->traverse(this);
1017
1018 // save it so that computing the right side doesn't trash it
1019 spv::Builder::AccessChain partial = builder.getAccessChain();
1020
1021 // compute the next index in the chain
1022 builder.clearAccessChain();
1023 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001024 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001025
1026 // restore the saved access chain
1027 builder.setAccessChain(partial);
1028
1029 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001030 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001031 else
John Kessenichfa668da2015-09-13 14:46:30 -06001032 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001033 }
1034 return false;
1035 case glslang::EOpVectorSwizzle:
1036 {
1037 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001038 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001039 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001040 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001041 }
1042 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001043 case glslang::EOpLogicalOr:
1044 case glslang::EOpLogicalAnd:
1045 {
1046
1047 // These may require short circuiting, but can sometimes be done as straight
1048 // binary operations. The right operand must be short circuited if it has
1049 // side effects, and should probably be if it is complex.
1050 if (isTrivial(node->getRight()->getAsTyped()))
1051 break; // handle below as a normal binary operation
1052 // otherwise, we need to do dynamic short circuiting on the right operand
1053 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1054 builder.clearAccessChain();
1055 builder.setAccessChainRValue(result);
1056 }
1057 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001058 default:
1059 break;
1060 }
1061
1062 // Assume generic binary op...
1063
John Kessenich32cfd492016-02-02 12:37:46 -07001064 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001065 builder.clearAccessChain();
1066 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001067 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001068
John Kessenich32cfd492016-02-02 12:37:46 -07001069 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001070 builder.clearAccessChain();
1071 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001072 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001073
John Kessenich32cfd492016-02-02 12:37:46 -07001074 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001075 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001076 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001077 convertGlslangToSpvType(node->getType()), left, right,
1078 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001079
John Kessenich50e57562015-12-21 21:21:11 -07001080 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001081 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001082 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001083 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001084 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001085 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001086 return false;
1087 }
John Kessenich140f3df2015-06-26 16:58:36 -06001088}
1089
1090bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1091{
qining40887662016-04-03 22:20:42 -04001092 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1093 if (node->getType().getQualifier().isSpecConstant())
1094 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1095
John Kessenichfc51d282015-08-19 13:34:18 -06001096 spv::Id result = spv::NoResult;
1097
1098 // try texturing first
1099 result = createImageTextureFunctionCall(node);
1100 if (result != spv::NoResult) {
1101 builder.clearAccessChain();
1102 builder.setAccessChainRValue(result);
1103
1104 return false; // done with this node
1105 }
1106
1107 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001108
1109 if (node->getOp() == glslang::EOpArrayLength) {
1110 // Quite special; won't want to evaluate the operand.
1111
1112 // Normal .length() would have been constant folded by the front-end.
1113 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001114 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001115 assert(node->getOperand()->getType().isRuntimeSizedArray());
1116 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1117 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001118 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1119 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001120
1121 builder.clearAccessChain();
1122 builder.setAccessChainRValue(length);
1123
1124 return false;
1125 }
1126
John Kessenichfc51d282015-08-19 13:34:18 -06001127 // Start by evaluating the operand
1128
John Kessenich8c8505c2016-07-26 12:50:38 -06001129 // Does it need a swizzle inversion? If so, evaluation is inverted;
1130 // operate first on the swizzle base, then apply the swizzle.
1131 spv::Id invertedType = spv::NoType;
1132 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1133 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1134 invertedType = getInvertedSwizzleType(*node->getOperand());
1135
John Kessenich140f3df2015-06-26 16:58:36 -06001136 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001137 if (invertedType != spv::NoType)
1138 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1139 else
1140 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001141
Rex Xufc618912015-09-09 16:42:49 +08001142 spv::Id operand = spv::NoResult;
1143
1144 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1145 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001146 node->getOp() == glslang::EOpAtomicCounter ||
1147 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001148 operand = builder.accessChainGetLValue(); // Special case l-value operands
1149 else
John Kessenich32cfd492016-02-02 12:37:46 -07001150 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001151
John Kessenichf6640762016-08-01 19:44:00 -06001152 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001153 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001154
1155 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001156 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001157 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001158
1159 // if not, then possibly an operation
1160 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001161 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001162
1163 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001164 if (invertedType)
1165 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1166
John Kessenich140f3df2015-06-26 16:58:36 -06001167 builder.clearAccessChain();
1168 builder.setAccessChainRValue(result);
1169
1170 return false; // done with this node
1171 }
1172
1173 // it must be a special case, check...
1174 switch (node->getOp()) {
1175 case glslang::EOpPostIncrement:
1176 case glslang::EOpPostDecrement:
1177 case glslang::EOpPreIncrement:
1178 case glslang::EOpPreDecrement:
1179 {
1180 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001181 spv::Id one = 0;
1182 if (node->getBasicType() == glslang::EbtFloat)
1183 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001184 else if (node->getBasicType() == glslang::EbtDouble)
1185 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001186 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1187 one = builder.makeInt64Constant(1);
1188 else
1189 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001190 glslang::TOperator op;
1191 if (node->getOp() == glslang::EOpPreIncrement ||
1192 node->getOp() == glslang::EOpPostIncrement)
1193 op = glslang::EOpAdd;
1194 else
1195 op = glslang::EOpSub;
1196
John Kessenichf6640762016-08-01 19:44:00 -06001197 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001198 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001199 convertGlslangToSpvType(node->getType()), operand, one,
1200 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001201 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001202
1203 // The result of operation is always stored, but conditionally the
1204 // consumed result. The consumed result is always an r-value.
1205 builder.accessChainStore(result);
1206 builder.clearAccessChain();
1207 if (node->getOp() == glslang::EOpPreIncrement ||
1208 node->getOp() == glslang::EOpPreDecrement)
1209 builder.setAccessChainRValue(result);
1210 else
1211 builder.setAccessChainRValue(operand);
1212 }
1213
1214 return false;
1215
1216 case glslang::EOpEmitStreamVertex:
1217 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1218 return false;
1219 case glslang::EOpEndStreamPrimitive:
1220 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1221 return false;
1222
1223 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001224 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001225 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001226 }
John Kessenich140f3df2015-06-26 16:58:36 -06001227}
1228
1229bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1230{
qining27e04a02016-04-14 16:40:20 -04001231 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1232 if (node->getType().getQualifier().isSpecConstant())
1233 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1234
John Kessenichfc51d282015-08-19 13:34:18 -06001235 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001236 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1237 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001238
1239 // try texturing
1240 result = createImageTextureFunctionCall(node);
1241 if (result != spv::NoResult) {
1242 builder.clearAccessChain();
1243 builder.setAccessChainRValue(result);
1244
1245 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001246 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001247 // "imageStore" is a special case, which has no result
1248 return false;
1249 }
John Kessenichfc51d282015-08-19 13:34:18 -06001250
John Kessenich140f3df2015-06-26 16:58:36 -06001251 glslang::TOperator binOp = glslang::EOpNull;
1252 bool reduceComparison = true;
1253 bool isMatrix = false;
1254 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001255 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001256
1257 assert(node->getOp());
1258
John Kessenichf6640762016-08-01 19:44:00 -06001259 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001260
1261 switch (node->getOp()) {
1262 case glslang::EOpSequence:
1263 {
1264 if (preVisit)
1265 ++sequenceDepth;
1266 else
1267 --sequenceDepth;
1268
1269 if (sequenceDepth == 1) {
1270 // If this is the parent node of all the functions, we want to see them
1271 // early, so all call points have actual SPIR-V functions to reference.
1272 // In all cases, still let the traverser visit the children for us.
1273 makeFunctions(node->getAsAggregate()->getSequence());
1274
1275 // Also, we want all globals initializers to go into the entry of main(), before
1276 // anything else gets there, so visit out of order, doing them all now.
1277 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1278
1279 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1280 // so do them manually.
1281 visitFunctions(node->getAsAggregate()->getSequence());
1282
1283 return false;
1284 }
1285
1286 return true;
1287 }
1288 case glslang::EOpLinkerObjects:
1289 {
1290 if (visit == glslang::EvPreVisit)
1291 linkageOnly = true;
1292 else
1293 linkageOnly = false;
1294
1295 return true;
1296 }
1297 case glslang::EOpComma:
1298 {
1299 // processing from left to right naturally leaves the right-most
1300 // lying around in the access chain
1301 glslang::TIntermSequence& glslangOperands = node->getSequence();
1302 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1303 glslangOperands[i]->traverse(this);
1304
1305 return false;
1306 }
1307 case glslang::EOpFunction:
1308 if (visit == glslang::EvPreVisit) {
1309 if (isShaderEntrypoint(node)) {
1310 inMain = true;
1311 builder.setBuildPoint(shaderEntry->getLastBlock());
1312 } else {
1313 handleFunctionEntry(node);
1314 }
1315 } else {
1316 if (inMain)
1317 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001318 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001319 inMain = false;
1320 }
1321
1322 return true;
1323 case glslang::EOpParameters:
1324 // Parameters will have been consumed by EOpFunction processing, but not
1325 // the body, so we still visited the function node's children, making this
1326 // child redundant.
1327 return false;
1328 case glslang::EOpFunctionCall:
1329 {
1330 if (node->isUserDefined())
1331 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001332 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1333 if (result) {
1334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001337 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 return false;
1340 }
1341 case glslang::EOpConstructMat2x2:
1342 case glslang::EOpConstructMat2x3:
1343 case glslang::EOpConstructMat2x4:
1344 case glslang::EOpConstructMat3x2:
1345 case glslang::EOpConstructMat3x3:
1346 case glslang::EOpConstructMat3x4:
1347 case glslang::EOpConstructMat4x2:
1348 case glslang::EOpConstructMat4x3:
1349 case glslang::EOpConstructMat4x4:
1350 case glslang::EOpConstructDMat2x2:
1351 case glslang::EOpConstructDMat2x3:
1352 case glslang::EOpConstructDMat2x4:
1353 case glslang::EOpConstructDMat3x2:
1354 case glslang::EOpConstructDMat3x3:
1355 case glslang::EOpConstructDMat3x4:
1356 case glslang::EOpConstructDMat4x2:
1357 case glslang::EOpConstructDMat4x3:
1358 case glslang::EOpConstructDMat4x4:
1359 isMatrix = true;
1360 // fall through
1361 case glslang::EOpConstructFloat:
1362 case glslang::EOpConstructVec2:
1363 case glslang::EOpConstructVec3:
1364 case glslang::EOpConstructVec4:
1365 case glslang::EOpConstructDouble:
1366 case glslang::EOpConstructDVec2:
1367 case glslang::EOpConstructDVec3:
1368 case glslang::EOpConstructDVec4:
1369 case glslang::EOpConstructBool:
1370 case glslang::EOpConstructBVec2:
1371 case glslang::EOpConstructBVec3:
1372 case glslang::EOpConstructBVec4:
1373 case glslang::EOpConstructInt:
1374 case glslang::EOpConstructIVec2:
1375 case glslang::EOpConstructIVec3:
1376 case glslang::EOpConstructIVec4:
1377 case glslang::EOpConstructUint:
1378 case glslang::EOpConstructUVec2:
1379 case glslang::EOpConstructUVec3:
1380 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001381 case glslang::EOpConstructInt64:
1382 case glslang::EOpConstructI64Vec2:
1383 case glslang::EOpConstructI64Vec3:
1384 case glslang::EOpConstructI64Vec4:
1385 case glslang::EOpConstructUint64:
1386 case glslang::EOpConstructU64Vec2:
1387 case glslang::EOpConstructU64Vec3:
1388 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001389 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001390 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001391 {
1392 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001393 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001394 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001395 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001396 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001397 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001398 std::vector<spv::Id> constituents;
1399 for (int c = 0; c < (int)arguments.size(); ++c)
1400 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001401 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001402 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001403 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001404 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001405 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001406
1407 builder.clearAccessChain();
1408 builder.setAccessChainRValue(constructed);
1409
1410 return false;
1411 }
1412
1413 // These six are component-wise compares with component-wise results.
1414 // Forward on to createBinaryOperation(), requesting a vector result.
1415 case glslang::EOpLessThan:
1416 case glslang::EOpGreaterThan:
1417 case glslang::EOpLessThanEqual:
1418 case glslang::EOpGreaterThanEqual:
1419 case glslang::EOpVectorEqual:
1420 case glslang::EOpVectorNotEqual:
1421 {
1422 // Map the operation to a binary
1423 binOp = node->getOp();
1424 reduceComparison = false;
1425 switch (node->getOp()) {
1426 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1427 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1428 default: binOp = node->getOp(); break;
1429 }
1430
1431 break;
1432 }
1433 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001434 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001435 binOp = glslang::EOpMul;
1436 break;
1437 case glslang::EOpOuterProduct:
1438 // two vectors multiplied to make a matrix
1439 binOp = glslang::EOpOuterProduct;
1440 break;
1441 case glslang::EOpDot:
1442 {
qining25262b32016-05-06 17:25:16 -04001443 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001444 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001445 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001446 binOp = glslang::EOpMul;
1447 break;
1448 }
1449 case glslang::EOpMod:
1450 // when an aggregate, this is the floating-point mod built-in function,
1451 // which can be emitted by the one in createBinaryOperation()
1452 binOp = glslang::EOpMod;
1453 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001454 case glslang::EOpEmitVertex:
1455 case glslang::EOpEndPrimitive:
1456 case glslang::EOpBarrier:
1457 case glslang::EOpMemoryBarrier:
1458 case glslang::EOpMemoryBarrierAtomicCounter:
1459 case glslang::EOpMemoryBarrierBuffer:
1460 case glslang::EOpMemoryBarrierImage:
1461 case glslang::EOpMemoryBarrierShared:
1462 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001463 case glslang::EOpAllMemoryBarrierWithGroupSync:
1464 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1465 case glslang::EOpWorkgroupMemoryBarrier:
1466 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001467 noReturnValue = true;
1468 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1469 break;
1470
John Kessenich426394d2015-07-23 10:22:48 -06001471 case glslang::EOpAtomicAdd:
1472 case glslang::EOpAtomicMin:
1473 case glslang::EOpAtomicMax:
1474 case glslang::EOpAtomicAnd:
1475 case glslang::EOpAtomicOr:
1476 case glslang::EOpAtomicXor:
1477 case glslang::EOpAtomicExchange:
1478 case glslang::EOpAtomicCompSwap:
1479 atomic = true;
1480 break;
1481
John Kessenich140f3df2015-06-26 16:58:36 -06001482 default:
1483 break;
1484 }
1485
1486 //
1487 // See if it maps to a regular operation.
1488 //
John Kessenich140f3df2015-06-26 16:58:36 -06001489 if (binOp != glslang::EOpNull) {
1490 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1491 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1492 assert(left && right);
1493
1494 builder.clearAccessChain();
1495 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001496 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001497
1498 builder.clearAccessChain();
1499 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001500 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001501
qining25262b32016-05-06 17:25:16 -04001502 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001503 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001504 left->getType().getBasicType(), reduceComparison);
1505
1506 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001507 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001508 builder.clearAccessChain();
1509 builder.setAccessChainRValue(result);
1510
1511 return false;
1512 }
1513
John Kessenich426394d2015-07-23 10:22:48 -06001514 //
1515 // Create the list of operands.
1516 //
John Kessenich140f3df2015-06-26 16:58:36 -06001517 glslang::TIntermSequence& glslangOperands = node->getSequence();
1518 std::vector<spv::Id> operands;
1519 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001520 // special case l-value operands; there are just a few
1521 bool lvalue = false;
1522 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001523 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001524 case glslang::EOpModf:
1525 if (arg == 1)
1526 lvalue = true;
1527 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001528 case glslang::EOpInterpolateAtSample:
1529 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001530#ifdef AMD_EXTENSIONS
1531 case glslang::EOpInterpolateAtVertex:
1532#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001533 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001534 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001535
1536 // Does it need a swizzle inversion? If so, evaluation is inverted;
1537 // operate first on the swizzle base, then apply the swizzle.
1538 if (glslangOperands[0]->getAsOperator() &&
1539 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1540 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1541 }
Rex Xu7a26c172015-12-08 17:12:09 +08001542 break;
Rex Xud4782c12015-09-06 16:30:11 +08001543 case glslang::EOpAtomicAdd:
1544 case glslang::EOpAtomicMin:
1545 case glslang::EOpAtomicMax:
1546 case glslang::EOpAtomicAnd:
1547 case glslang::EOpAtomicOr:
1548 case glslang::EOpAtomicXor:
1549 case glslang::EOpAtomicExchange:
1550 case glslang::EOpAtomicCompSwap:
1551 if (arg == 0)
1552 lvalue = true;
1553 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001554 case glslang::EOpAddCarry:
1555 case glslang::EOpSubBorrow:
1556 if (arg == 2)
1557 lvalue = true;
1558 break;
1559 case glslang::EOpUMulExtended:
1560 case glslang::EOpIMulExtended:
1561 if (arg >= 2)
1562 lvalue = true;
1563 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001564 default:
1565 break;
1566 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001567 builder.clearAccessChain();
1568 if (invertedType != spv::NoType && arg == 0)
1569 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1570 else
1571 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001572 if (lvalue)
1573 operands.push_back(builder.accessChainGetLValue());
1574 else
John Kessenich32cfd492016-02-02 12:37:46 -07001575 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001576 }
John Kessenich426394d2015-07-23 10:22:48 -06001577
1578 if (atomic) {
1579 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001580 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001581 } else {
1582 // Pass through to generic operations.
1583 switch (glslangOperands.size()) {
1584 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001585 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001586 break;
1587 case 1:
qining25262b32016-05-06 17:25:16 -04001588 result = createUnaryOperation(
1589 node->getOp(), precision,
1590 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001591 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001592 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001593 break;
1594 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001595 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001596 break;
1597 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001598 if (invertedType)
1599 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001600 }
1601
1602 if (noReturnValue)
1603 return false;
1604
1605 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001606 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001607 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001608 } else {
1609 builder.clearAccessChain();
1610 builder.setAccessChainRValue(result);
1611 return false;
1612 }
1613}
1614
1615bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1616{
1617 // This path handles both if-then-else and ?:
1618 // The if-then-else has a node type of void, while
1619 // ?: has a non-void node type
1620 spv::Id result = 0;
1621 if (node->getBasicType() != glslang::EbtVoid) {
1622 // don't handle this as just on-the-fly temporaries, because there will be two names
1623 // and better to leave SSA to later passes
1624 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1625 }
1626
1627 // emit the condition before doing anything with selection
1628 node->getCondition()->traverse(this);
1629
1630 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001631 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001632
1633 if (node->getTrueBlock()) {
1634 // emit the "then" statement
1635 node->getTrueBlock()->traverse(this);
1636 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001637 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001638 }
1639
1640 if (node->getFalseBlock()) {
1641 ifBuilder.makeBeginElse();
1642 // emit the "else" statement
1643 node->getFalseBlock()->traverse(this);
1644 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001645 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001646 }
1647
1648 ifBuilder.makeEndIf();
1649
1650 if (result) {
1651 // GLSL only has r-values as the result of a :?, but
1652 // if we have an l-value, that can be more efficient if it will
1653 // become the base of a complex r-value expression, because the
1654 // next layer copies r-values into memory to use the access-chain mechanism
1655 builder.clearAccessChain();
1656 builder.setAccessChainLValue(result);
1657 }
1658
1659 return false;
1660}
1661
1662bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1663{
1664 // emit and get the condition before doing anything with switch
1665 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001666 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001667
1668 // browse the children to sort out code segments
1669 int defaultSegment = -1;
1670 std::vector<TIntermNode*> codeSegments;
1671 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1672 std::vector<int> caseValues;
1673 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1674 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1675 TIntermNode* child = *c;
1676 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001677 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001678 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001679 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001680 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1681 } else
1682 codeSegments.push_back(child);
1683 }
1684
qining25262b32016-05-06 17:25:16 -04001685 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001686 // statements between the last case and the end of the switch statement
1687 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1688 (int)codeSegments.size() == defaultSegment)
1689 codeSegments.push_back(nullptr);
1690
1691 // make the switch statement
1692 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001693 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001694
1695 // emit all the code in the segments
1696 breakForLoop.push(false);
1697 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1698 builder.nextSwitchSegment(segmentBlocks, s);
1699 if (codeSegments[s])
1700 codeSegments[s]->traverse(this);
1701 else
1702 builder.addSwitchBreak();
1703 }
1704 breakForLoop.pop();
1705
1706 builder.endSwitch(segmentBlocks);
1707
1708 return false;
1709}
1710
1711void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1712{
1713 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001714 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001715
1716 builder.clearAccessChain();
1717 builder.setAccessChainRValue(constant);
1718}
1719
1720bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1721{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001722 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001723 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001724 // Spec requires back edges to target header blocks, and every header block
1725 // must dominate its merge block. Make a header block first to ensure these
1726 // conditions are met. By definition, it will contain OpLoopMerge, followed
1727 // by a block-ending branch. But we don't want to put any other body/test
1728 // instructions in it, since the body/test may have arbitrary instructions,
1729 // including merges of its own.
1730 builder.setBuildPoint(&blocks.head);
1731 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001732 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001733 spv::Block& test = builder.makeNewBlock();
1734 builder.createBranch(&test);
1735
1736 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001737 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001738 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001739 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001740 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1741
1742 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001743 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001744 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001745 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001746 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001747 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001748
1749 builder.setBuildPoint(&blocks.continue_target);
1750 if (node->getTerminal())
1751 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001752 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001753 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001754 builder.createBranch(&blocks.body);
1755
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001756 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001757 builder.setBuildPoint(&blocks.body);
1758 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001759 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001760 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001761 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001762
1763 builder.setBuildPoint(&blocks.continue_target);
1764 if (node->getTerminal())
1765 node->getTerminal()->traverse(this);
1766 if (node->getTest()) {
1767 node->getTest()->traverse(this);
1768 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001769 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001770 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001771 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001772 // TODO: unless there was a break/return/discard instruction
1773 // somewhere in the body, this is an infinite loop, so we should
1774 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001775 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001776 }
John Kessenich140f3df2015-06-26 16:58:36 -06001777 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001778 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001779 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001780 return false;
1781}
1782
1783bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1784{
1785 if (node->getExpression())
1786 node->getExpression()->traverse(this);
1787
1788 switch (node->getFlowOp()) {
1789 case glslang::EOpKill:
1790 builder.makeDiscard();
1791 break;
1792 case glslang::EOpBreak:
1793 if (breakForLoop.top())
1794 builder.createLoopExit();
1795 else
1796 builder.addSwitchBreak();
1797 break;
1798 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001799 builder.createLoopContinue();
1800 break;
1801 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001802 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001803 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001804 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001805 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001806
1807 builder.clearAccessChain();
1808 break;
1809
1810 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001811 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001812 break;
1813 }
1814
1815 return false;
1816}
1817
1818spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1819{
qining25262b32016-05-06 17:25:16 -04001820 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001821 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001822 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001823 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001824 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001825 }
1826
1827 // Now, handle actual variables
1828 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1829 spv::Id spvType = convertGlslangToSpvType(node->getType());
1830
1831 const char* name = node->getName().c_str();
1832 if (glslang::IsAnonymous(name))
1833 name = "";
1834
1835 return builder.createVariable(storageClass, spvType, name);
1836}
1837
1838// Return type Id of the sampled type.
1839spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1840{
1841 switch (sampler.type) {
1842 case glslang::EbtFloat: return builder.makeFloatType(32);
1843 case glslang::EbtInt: return builder.makeIntType(32);
1844 case glslang::EbtUint: return builder.makeUintType(32);
1845 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001846 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001847 return builder.makeFloatType(32);
1848 }
1849}
1850
John Kessenich8c8505c2016-07-26 12:50:38 -06001851// If node is a swizzle operation, return the type that should be used if
1852// the swizzle base is first consumed by another operation, before the swizzle
1853// is applied.
1854spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1855{
1856 if (node.getAsOperator() &&
1857 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1858 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1859 else
1860 return spv::NoType;
1861}
1862
1863// When inverting a swizzle with a parent op, this function
1864// will apply the swizzle operation to a completed parent operation.
1865spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1866{
1867 std::vector<unsigned> swizzle;
1868 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1869 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1870}
1871
1872
1873// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1874void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1875{
1876 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1877 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1878 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1879}
1880
John Kessenich3ac051e2015-12-20 11:29:16 -07001881// Convert from a glslang type to an SPV type, by calling into a
1882// recursive version of this function. This establishes the inherited
1883// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001884spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1885{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001886 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001887}
1888
1889// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001890// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001891// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001892spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001893{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001894 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001895
1896 switch (type.getBasicType()) {
1897 case glslang::EbtVoid:
1898 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001899 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001900 break;
1901 case glslang::EbtFloat:
1902 spvType = builder.makeFloatType(32);
1903 break;
1904 case glslang::EbtDouble:
1905 spvType = builder.makeFloatType(64);
1906 break;
1907 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001908 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1909 // a 32-bit int where non-0 means true.
1910 if (explicitLayout != glslang::ElpNone)
1911 spvType = builder.makeUintType(32);
1912 else
1913 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001914 break;
1915 case glslang::EbtInt:
1916 spvType = builder.makeIntType(32);
1917 break;
1918 case glslang::EbtUint:
1919 spvType = builder.makeUintType(32);
1920 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001921 case glslang::EbtInt64:
1922 builder.addCapability(spv::CapabilityInt64);
1923 spvType = builder.makeIntType(64);
1924 break;
1925 case glslang::EbtUint64:
1926 builder.addCapability(spv::CapabilityInt64);
1927 spvType = builder.makeUintType(64);
1928 break;
John Kessenich426394d2015-07-23 10:22:48 -06001929 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001930 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001931 spvType = builder.makeUintType(32);
1932 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001933 case glslang::EbtSampler:
1934 {
1935 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001936 if (sampler.sampler) {
1937 // pure sampler
1938 spvType = builder.makeSamplerType();
1939 } else {
1940 // an image is present, make its type
1941 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1942 sampler.image ? 2 : 1, TranslateImageFormat(type));
1943 if (sampler.combined) {
1944 // already has both image and sampler, make the combined type
1945 spvType = builder.makeSampledImageType(spvType);
1946 }
John Kessenich55e7d112015-11-15 21:33:39 -07001947 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001948 }
John Kessenich140f3df2015-06-26 16:58:36 -06001949 break;
1950 case glslang::EbtStruct:
1951 case glslang::EbtBlock:
1952 {
1953 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001954 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001955
1956 // Try to share structs for different layouts, but not yet for other
1957 // kinds of qualification (primarily not yet including interpolant qualification).
1958 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001959 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001960 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001961 break;
1962
1963 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001964 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001965 memberRemapper[glslangMembers].resize(glslangMembers->size());
1966 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001967 }
1968 break;
1969 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001970 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001971 break;
1972 }
1973
1974 if (type.isMatrix())
1975 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1976 else {
1977 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1978 if (type.getVectorSize() > 1)
1979 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1980 }
1981
1982 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001983 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1984
John Kessenichc9a80832015-09-12 12:17:44 -06001985 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001986 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001987 // We need to decorate array strides for types needing explicit layout, except blocks.
1988 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001989 // Use a dummy glslang type for querying internal strides of
1990 // arrays of arrays, but using just a one-dimensional array.
1991 glslang::TType simpleArrayType(type, 0); // deference type of the array
1992 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1993 simpleArrayType.getArraySizes().dereference();
1994
1995 // Will compute the higher-order strides here, rather than making a whole
1996 // pile of types and doing repetitive recursion on their contents.
1997 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1998 }
John Kessenichf8842e52016-01-04 19:22:56 -07001999
2000 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002001 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002002 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002003 if (stride > 0)
2004 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002005 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002006 }
2007 } else {
2008 // single-dimensional array, and don't yet have stride
2009
John Kessenichf8842e52016-01-04 19:22:56 -07002010 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002011 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2012 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002013 }
John Kessenich31ed4832015-09-09 17:51:38 -06002014
John Kessenichc9a80832015-09-12 12:17:44 -06002015 // Do the outer dimension, which might not be known for a runtime-sized array
2016 if (type.isRuntimeSizedArray()) {
2017 spvType = builder.makeRuntimeArray(spvType);
2018 } else {
2019 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002020 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002021 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002022 if (stride > 0)
2023 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002024 }
2025
2026 return spvType;
2027}
2028
John Kessenich6090df02016-06-30 21:18:02 -06002029
2030// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2031// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2032// Mutually recursive with convertGlslangToSpvType().
2033spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2034 const glslang::TTypeList* glslangMembers,
2035 glslang::TLayoutPacking explicitLayout,
2036 const glslang::TQualifier& qualifier)
2037{
2038 // Create a vector of struct types for SPIR-V to consume
2039 std::vector<spv::Id> spvMembers;
2040 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2041 int locationOffset = 0; // for use across struct members, when they are called recursively
2042 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2043 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2044 if (glslangMember.hiddenMember()) {
2045 ++memberDelta;
2046 if (type.getBasicType() == glslang::EbtBlock)
2047 memberRemapper[glslangMembers][i] = -1;
2048 } else {
2049 if (type.getBasicType() == glslang::EbtBlock)
2050 memberRemapper[glslangMembers][i] = i - memberDelta;
2051 // modify just this child's view of the qualifier
2052 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2053 InheritQualifiers(memberQualifier, qualifier);
2054
2055 // manually inherit location; it's more complex
2056 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2057 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2058 if (qualifier.hasLocation())
2059 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2060
2061 // recurse
2062 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2063 }
2064 }
2065
2066 // Make the SPIR-V type
2067 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
2068 if (! HasNonLayoutQualifiers(qualifier))
2069 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2070
2071 // Decorate it
2072 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2073
2074 return spvType;
2075}
2076
2077void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2078 const glslang::TTypeList* glslangMembers,
2079 glslang::TLayoutPacking explicitLayout,
2080 const glslang::TQualifier& qualifier,
2081 spv::Id spvType)
2082{
2083 // Name and decorate the non-hidden members
2084 int offset = -1;
2085 int locationOffset = 0; // for use within the members of this struct
2086 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2087 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2088 int member = i;
2089 if (type.getBasicType() == glslang::EbtBlock)
2090 member = memberRemapper[glslangMembers][i];
2091
2092 // modify just this child's view of the qualifier
2093 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2094 InheritQualifiers(memberQualifier, qualifier);
2095
2096 // using -1 above to indicate a hidden member
2097 if (member >= 0) {
2098 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2099 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2100 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2101 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2102 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2103 if (type.getBasicType() == glslang::EbtBlock) {
2104 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2105 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2106 }
2107 }
2108 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2109
2110 if (qualifier.storage == glslang::EvqBuffer) {
2111 std::vector<spv::Decoration> memory;
2112 TranslateMemoryDecoration(memberQualifier, memory);
2113 for (unsigned int i = 0; i < memory.size(); ++i)
2114 addMemberDecoration(spvType, member, memory[i]);
2115 }
2116
John Kessenich2f47bc92016-06-30 21:47:35 -06002117 // Compute location decoration; tricky based on whether inheritance is at play and
2118 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002119 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2120 // probably move to the linker stage of the front end proper, and just have the
2121 // answer sitting already distributed throughout the individual member locations.
2122 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002123 // Ignore member locations if the container is an array, as that's
2124 // ill-specified and decisions have been made to not allow this anyway.
2125 // The object itself must have a location, and that comes out from decorating the object,
2126 // not the type (this code decorates types).
2127 if (! type.isArray()) {
2128 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2129 // struct members should not have explicit locations
2130 assert(type.getBasicType() != glslang::EbtStruct);
2131 location = memberQualifier.layoutLocation;
2132 } else if (type.getBasicType() != glslang::EbtBlock) {
2133 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2134 // The members, and their nested types, must not themselves have Location decorations.
2135 } else if (qualifier.hasLocation()) // inheritance
2136 location = qualifier.layoutLocation + locationOffset;
2137 }
John Kessenich6090df02016-06-30 21:18:02 -06002138 if (location >= 0)
2139 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2140
John Kessenich2f47bc92016-06-30 21:47:35 -06002141 if (qualifier.hasLocation()) // track for upcoming inheritance
2142 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2143
John Kessenich6090df02016-06-30 21:18:02 -06002144 // component, XFB, others
2145 if (glslangMember.getQualifier().hasComponent())
2146 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2147 if (glslangMember.getQualifier().hasXfbOffset())
2148 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2149 else if (explicitLayout != glslang::ElpNone) {
2150 // figure out what to do with offset, which is accumulating
2151 int nextOffset;
2152 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2153 if (offset >= 0)
2154 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2155 offset = nextOffset;
2156 }
2157
2158 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2159 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2160
2161 // built-in variable decorations
2162 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002163 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002164 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2165 }
2166 }
2167
2168 // Decorate the structure
2169 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2170 addDecoration(spvType, TranslateBlockDecoration(type));
2171 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2172 builder.addCapability(spv::CapabilityGeometryStreams);
2173 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2174 }
2175 if (glslangIntermediate->getXfbMode()) {
2176 builder.addCapability(spv::CapabilityTransformFeedback);
2177 if (type.getQualifier().hasXfbStride())
2178 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2179 if (type.getQualifier().hasXfbBuffer())
2180 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2181 }
2182}
2183
John Kessenich6c292d32016-02-15 20:58:50 -07002184// Turn the expression forming the array size into an id.
2185// This is not quite trivial, because of specialization constants.
2186// Sometimes, a raw constant is turned into an Id, and sometimes
2187// a specialization constant expression is.
2188spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2189{
2190 // First, see if this is sized with a node, meaning a specialization constant:
2191 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2192 if (specNode != nullptr) {
2193 builder.clearAccessChain();
2194 specNode->traverse(this);
2195 return accessChainLoad(specNode->getAsTyped()->getType());
2196 }
qining25262b32016-05-06 17:25:16 -04002197
John Kessenich6c292d32016-02-15 20:58:50 -07002198 // Otherwise, need a compile-time (front end) size, get it:
2199 int size = arraySizes.getDimSize(dim);
2200 assert(size > 0);
2201 return builder.makeUintConstant(size);
2202}
2203
John Kessenich103bef92016-02-08 21:38:15 -07002204// Wrap the builder's accessChainLoad to:
2205// - localize handling of RelaxedPrecision
2206// - use the SPIR-V inferred type instead of another conversion of the glslang type
2207// (avoids unnecessary work and possible type punning for structures)
2208// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002209spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2210{
John Kessenich103bef92016-02-08 21:38:15 -07002211 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2212 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2213
2214 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002215 if (type.getBasicType() == glslang::EbtBool) {
2216 if (builder.isScalarType(nominalTypeId)) {
2217 // Conversion for bool
2218 spv::Id boolType = builder.makeBoolType();
2219 if (nominalTypeId != boolType)
2220 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2221 } else if (builder.isVectorType(nominalTypeId)) {
2222 // Conversion for bvec
2223 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2224 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2225 if (nominalTypeId != bvecType)
2226 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2227 }
2228 }
John Kessenich103bef92016-02-08 21:38:15 -07002229
2230 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002231}
2232
Rex Xu27253232016-02-23 17:51:09 +08002233// Wrap the builder's accessChainStore to:
2234// - do conversion of concrete to abstract type
2235void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2236{
2237 // Need to convert to abstract types when necessary
2238 if (type.getBasicType() == glslang::EbtBool) {
2239 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2240
2241 if (builder.isScalarType(nominalTypeId)) {
2242 // Conversion for bool
2243 spv::Id boolType = builder.makeBoolType();
2244 if (nominalTypeId != boolType) {
2245 spv::Id zero = builder.makeUintConstant(0);
2246 spv::Id one = builder.makeUintConstant(1);
2247 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2248 }
2249 } else if (builder.isVectorType(nominalTypeId)) {
2250 // Conversion for bvec
2251 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2252 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2253 if (nominalTypeId != bvecType) {
2254 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2255 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2256 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2257 }
2258 }
2259 }
2260
2261 builder.accessChainStore(rvalue);
2262}
2263
John Kessenichf85e8062015-12-19 13:57:10 -07002264// Decide whether or not this type should be
2265// decorated with offsets and strides, and if so
2266// whether std140 or std430 rules should be applied.
2267glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002268{
John Kessenichf85e8062015-12-19 13:57:10 -07002269 // has to be a block
2270 if (type.getBasicType() != glslang::EbtBlock)
2271 return glslang::ElpNone;
2272
2273 // has to be a uniform or buffer block
2274 if (type.getQualifier().storage != glslang::EvqUniform &&
2275 type.getQualifier().storage != glslang::EvqBuffer)
2276 return glslang::ElpNone;
2277
2278 // return the layout to use
2279 switch (type.getQualifier().layoutPacking) {
2280 case glslang::ElpStd140:
2281 case glslang::ElpStd430:
2282 return type.getQualifier().layoutPacking;
2283 default:
2284 return glslang::ElpNone;
2285 }
John Kessenich31ed4832015-09-09 17:51:38 -06002286}
2287
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002288// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002289int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002290{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002291 int size;
John Kessenich49987892015-12-29 17:11:44 -07002292 int stride;
2293 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002294
2295 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002296}
2297
John Kessenich49987892015-12-29 17:11:44 -07002298// 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 -07002299// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002300int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002301{
John Kessenich49987892015-12-29 17:11:44 -07002302 glslang::TType elementType;
2303 elementType.shallowCopy(matrixType);
2304 elementType.clearArraySizes();
2305
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002306 int size;
John Kessenich49987892015-12-29 17:11:44 -07002307 int stride;
2308 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2309
2310 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002311}
2312
John Kessenich5e4b1242015-08-06 22:53:06 -06002313// Given a member type of a struct, realign the current offset for it, and compute
2314// the next (not yet aligned) offset for the next member, which will get aligned
2315// on the next call.
2316// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2317// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2318// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002319void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002320 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002321{
2322 // this will get a positive value when deemed necessary
2323 nextOffset = -1;
2324
John Kessenich5e4b1242015-08-06 22:53:06 -06002325 // override anything in currentOffset with user-set offset
2326 if (memberType.getQualifier().hasOffset())
2327 currentOffset = memberType.getQualifier().layoutOffset;
2328
2329 // It could be that current linker usage in glslang updated all the layoutOffset,
2330 // in which case the following code does not matter. But, that's not quite right
2331 // once cross-compilation unit GLSL validation is done, as the original user
2332 // settings are needed in layoutOffset, and then the following will come into play.
2333
John Kessenichf85e8062015-12-19 13:57:10 -07002334 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002335 if (! memberType.getQualifier().hasOffset())
2336 currentOffset = -1;
2337
2338 return;
2339 }
2340
John Kessenichf85e8062015-12-19 13:57:10 -07002341 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002342 if (currentOffset < 0)
2343 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002344
John Kessenich5e4b1242015-08-06 22:53:06 -06002345 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2346 // but possibly not yet correctly aligned.
2347
2348 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002349 int dummyStride;
2350 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002351 glslang::RoundToPow2(currentOffset, memberAlignment);
2352 nextOffset = currentOffset + memberSize;
2353}
2354
David Netoa901ffe2016-06-08 14:11:40 +01002355void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002356{
David Netoa901ffe2016-06-08 14:11:40 +01002357 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2358 switch (glslangBuiltIn)
2359 {
2360 case glslang::EbvClipDistance:
2361 case glslang::EbvCullDistance:
2362 case glslang::EbvPointSize:
2363 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2364 // Alternately, we could just call this for any glslang built-in, since the
2365 // capability already guards against duplicates.
2366 TranslateBuiltInDecoration(glslangBuiltIn, false);
2367 break;
2368 default:
2369 // Capabilities were already generated when the struct was declared.
2370 break;
2371 }
John Kessenichebb50532016-05-16 19:22:05 -06002372}
2373
John Kessenich140f3df2015-06-26 16:58:36 -06002374bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2375{
John Kessenich4d65ee32016-03-12 18:17:47 -07002376 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002377 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002378 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002379}
2380
2381// Make all the functions, skeletally, without actually visiting their bodies.
2382void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2383{
2384 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2385 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2386 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2387 continue;
2388
2389 // We're on a user function. Set up the basic interface for the function now,
2390 // so that it's available to call.
2391 // Translating the body will happen later.
2392 //
qining25262b32016-05-06 17:25:16 -04002393 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002394 // function. What it is an address of varies:
2395 //
2396 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2397 // so that write needs to be to a copy, hence the address of a copy works.
2398 //
2399 // - "const in" parameters can just be the r-value, as no writes need occur.
2400 //
2401 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2402 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2403
2404 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002405 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002406 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2407
2408 for (int p = 0; p < (int)parameters.size(); ++p) {
2409 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2410 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002411 if (paramType.isOpaque())
2412 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2413 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002414 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2415 else
2416 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002417 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002418 paramTypes.push_back(typeId);
2419 }
2420
2421 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002422 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2423 convertGlslangToSpvType(glslFunction->getType()),
2424 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002425
2426 // Track function to emit/call later
2427 functionMap[glslFunction->getName().c_str()] = function;
2428
2429 // Set the parameter id's
2430 for (int p = 0; p < (int)parameters.size(); ++p) {
2431 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2432 // give a name too
2433 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2434 }
2435 }
2436}
2437
2438// Process all the initializers, while skipping the functions and link objects
2439void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2440{
2441 builder.setBuildPoint(shaderEntry->getLastBlock());
2442 for (int i = 0; i < (int)initializers.size(); ++i) {
2443 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2444 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2445
2446 // We're on a top-level node that's not a function. Treat as an initializer, whose
2447 // code goes into the beginning of main.
2448 initializer->traverse(this);
2449 }
2450 }
2451}
2452
2453// Process all the functions, while skipping initializers.
2454void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2455{
2456 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2457 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2458 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2459 node->traverse(this);
2460 }
2461}
2462
2463void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2464{
qining25262b32016-05-06 17:25:16 -04002465 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002466 // that called makeFunctions().
2467 spv::Function* function = functionMap[node->getName().c_str()];
2468 spv::Block* functionBlock = function->getEntryBlock();
2469 builder.setBuildPoint(functionBlock);
2470}
2471
Rex Xu04db3f52015-09-16 11:44:02 +08002472void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002473{
Rex Xufc618912015-09-09 16:42:49 +08002474 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002475
2476 glslang::TSampler sampler = {};
2477 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002478 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002479 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2480 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2481 }
2482
John Kessenich140f3df2015-06-26 16:58:36 -06002483 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2484 builder.clearAccessChain();
2485 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002486
2487 // Special case l-value operands
2488 bool lvalue = false;
2489 switch (node.getOp()) {
2490 case glslang::EOpImageAtomicAdd:
2491 case glslang::EOpImageAtomicMin:
2492 case glslang::EOpImageAtomicMax:
2493 case glslang::EOpImageAtomicAnd:
2494 case glslang::EOpImageAtomicOr:
2495 case glslang::EOpImageAtomicXor:
2496 case glslang::EOpImageAtomicExchange:
2497 case glslang::EOpImageAtomicCompSwap:
2498 if (i == 0)
2499 lvalue = true;
2500 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002501 case glslang::EOpSparseImageLoad:
2502 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2503 lvalue = true;
2504 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002505 case glslang::EOpSparseTexture:
2506 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2507 lvalue = true;
2508 break;
2509 case glslang::EOpSparseTextureClamp:
2510 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2511 lvalue = true;
2512 break;
2513 case glslang::EOpSparseTextureLod:
2514 case glslang::EOpSparseTextureOffset:
2515 if (i == 3)
2516 lvalue = true;
2517 break;
2518 case glslang::EOpSparseTextureFetch:
2519 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2520 lvalue = true;
2521 break;
2522 case glslang::EOpSparseTextureFetchOffset:
2523 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2524 lvalue = true;
2525 break;
2526 case glslang::EOpSparseTextureLodOffset:
2527 case glslang::EOpSparseTextureGrad:
2528 case glslang::EOpSparseTextureOffsetClamp:
2529 if (i == 4)
2530 lvalue = true;
2531 break;
2532 case glslang::EOpSparseTextureGradOffset:
2533 case glslang::EOpSparseTextureGradClamp:
2534 if (i == 5)
2535 lvalue = true;
2536 break;
2537 case glslang::EOpSparseTextureGradOffsetClamp:
2538 if (i == 6)
2539 lvalue = true;
2540 break;
2541 case glslang::EOpSparseTextureGather:
2542 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2543 lvalue = true;
2544 break;
2545 case glslang::EOpSparseTextureGatherOffset:
2546 case glslang::EOpSparseTextureGatherOffsets:
2547 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2548 lvalue = true;
2549 break;
Rex Xufc618912015-09-09 16:42:49 +08002550 default:
2551 break;
2552 }
2553
Rex Xu6b86d492015-09-16 17:48:22 +08002554 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002555 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002556 else
John Kessenich32cfd492016-02-02 12:37:46 -07002557 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002558 }
2559}
2560
John Kessenichfc51d282015-08-19 13:34:18 -06002561void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002562{
John Kessenichfc51d282015-08-19 13:34:18 -06002563 builder.clearAccessChain();
2564 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002565 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002566}
John Kessenich140f3df2015-06-26 16:58:36 -06002567
John Kessenichfc51d282015-08-19 13:34:18 -06002568spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2569{
Rex Xufc618912015-09-09 16:42:49 +08002570 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002571 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002572 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002573 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002574
John Kessenichfc51d282015-08-19 13:34:18 -06002575 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002576 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2577 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2578 std::vector<spv::Id> arguments;
2579 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002580 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002581 else
2582 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002583 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002584
2585 spv::Builder::TextureParameters params = { };
2586 params.sampler = arguments[0];
2587
Rex Xu04db3f52015-09-16 11:44:02 +08002588 glslang::TCrackedTextureOp cracked;
2589 node->crackTexture(sampler, cracked);
2590
John Kessenichfc51d282015-08-19 13:34:18 -06002591 // Check for queries
2592 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002593 // a sampled image needs to have the image extracted first
2594 if (builder.isSampledImage(params.sampler))
2595 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002596 switch (node->getOp()) {
2597 case glslang::EOpImageQuerySize:
2598 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002599 if (arguments.size() > 1) {
2600 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002601 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002602 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002603 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002604 case glslang::EOpImageQuerySamples:
2605 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002606 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002607 case glslang::EOpTextureQueryLod:
2608 params.coords = arguments[1];
2609 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2610 case glslang::EOpTextureQueryLevels:
2611 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002612 case glslang::EOpSparseTexelsResident:
2613 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002614 default:
2615 assert(0);
2616 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002617 }
John Kessenich140f3df2015-06-26 16:58:36 -06002618 }
2619
Rex Xufc618912015-09-09 16:42:49 +08002620 // Check for image functions other than queries
2621 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002622 std::vector<spv::Id> operands;
2623 auto opIt = arguments.begin();
2624 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002625
2626 // Handle subpass operations
2627 // TODO: GLSL should change to have the "MS" only on the type rather than the
2628 // built-in function.
2629 if (cracked.subpass) {
2630 // add on the (0,0) coordinate
2631 spv::Id zero = builder.makeIntConstant(0);
2632 std::vector<spv::Id> comps;
2633 comps.push_back(zero);
2634 comps.push_back(zero);
2635 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2636 if (sampler.ms) {
2637 operands.push_back(spv::ImageOperandsSampleMask);
2638 operands.push_back(*(opIt++));
2639 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002640 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002641 }
2642
John Kessenich56bab042015-09-16 10:54:31 -06002643 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002644 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002645 if (sampler.ms) {
2646 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002647 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002648 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002649 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2650 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002651 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002652 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002653 if (sampler.ms) {
2654 operands.push_back(*(opIt + 1));
2655 operands.push_back(spv::ImageOperandsSampleMask);
2656 operands.push_back(*opIt);
2657 } else
2658 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002659 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002660 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2661 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002662 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002663 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2664 builder.addCapability(spv::CapabilitySparseResidency);
2665 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2666 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2667
2668 if (sampler.ms) {
2669 operands.push_back(spv::ImageOperandsSampleMask);
2670 operands.push_back(*opIt++);
2671 }
2672
2673 // Create the return type that was a special structure
2674 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002675 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002676 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2677 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2678
2679 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2680
2681 // Decode the return type
2682 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2683 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002684 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002685 // Process image atomic operations
2686
2687 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2688 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002689 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002690
John Kessenich8c8505c2016-07-26 12:50:38 -06002691 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002692 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002693
2694 std::vector<spv::Id> operands;
2695 operands.push_back(pointer);
2696 for (; opIt != arguments.end(); ++opIt)
2697 operands.push_back(*opIt);
2698
John Kessenich8c8505c2016-07-26 12:50:38 -06002699 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002700 }
2701 }
2702
2703 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002704 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002705 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2706
John Kessenichfc51d282015-08-19 13:34:18 -06002707 // check for bias argument
2708 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002709 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002710 int nonBiasArgCount = 2;
2711 if (cracked.offset)
2712 ++nonBiasArgCount;
2713 if (cracked.grad)
2714 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002715 if (cracked.lodClamp)
2716 ++nonBiasArgCount;
2717 if (sparse)
2718 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002719
2720 if ((int)arguments.size() > nonBiasArgCount)
2721 bias = true;
2722 }
2723
John Kessenicha5c33d62016-06-02 23:45:21 -06002724 // See if the sampler param should really be just the SPV image part
2725 if (cracked.fetch) {
2726 // a fetch needs to have the image extracted first
2727 if (builder.isSampledImage(params.sampler))
2728 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2729 }
2730
John Kessenichfc51d282015-08-19 13:34:18 -06002731 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002732
John Kessenichfc51d282015-08-19 13:34:18 -06002733 params.coords = arguments[1];
2734 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002735 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002736
2737 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002738 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002739 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002740 ++extraArgs;
2741 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002742 params.Dref = arguments[2];
2743 ++extraArgs;
2744 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002745 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002746 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002747 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002748 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002749 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002750 dRefComp = builder.getNumComponents(params.coords) - 1;
2751 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002752 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2753 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002754
2755 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002756 if (cracked.lod) {
2757 params.lod = arguments[2];
2758 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002759 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2760 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2761 noImplicitLod = true;
2762 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002763
2764 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002765 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002766 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002767 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002768 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002769
2770 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002771 if (cracked.grad) {
2772 params.gradX = arguments[2 + extraArgs];
2773 params.gradY = arguments[3 + extraArgs];
2774 extraArgs += 2;
2775 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002776
2777 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002778 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002779 params.offset = arguments[2 + extraArgs];
2780 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002781 } else if (cracked.offsets) {
2782 params.offsets = arguments[2 + extraArgs];
2783 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002784 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002785
2786 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002787 if (cracked.lodClamp) {
2788 params.lodClamp = arguments[2 + extraArgs];
2789 ++extraArgs;
2790 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002791
2792 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002793 if (sparse) {
2794 params.texelOut = arguments[2 + extraArgs];
2795 ++extraArgs;
2796 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002797
2798 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002799 if (bias) {
2800 params.bias = arguments[2 + extraArgs];
2801 ++extraArgs;
2802 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002803
2804 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002805 if (cracked.gather && ! sampler.shadow) {
2806 // default component is 0, if missing, otherwise an argument
2807 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002808 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002809 ++extraArgs;
2810 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002811 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002812 }
2813 }
John Kessenichfc51d282015-08-19 13:34:18 -06002814
John Kessenich65336482016-06-16 14:06:26 -06002815 // projective component (might not to move)
2816 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2817 // are divided by the last component of P."
2818 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2819 // unused components will appear after all used components."
2820 if (cracked.proj) {
2821 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2822 int projTargetComp;
2823 switch (sampler.dim) {
2824 case glslang::Esd1D: projTargetComp = 1; break;
2825 case glslang::Esd2D: projTargetComp = 2; break;
2826 case glslang::EsdRect: projTargetComp = 2; break;
2827 default: projTargetComp = projSourceComp; break;
2828 }
2829 // copy the projective coordinate if we have to
2830 if (projTargetComp != projSourceComp) {
2831 spv::Id projComp = builder.createCompositeExtract(params.coords,
2832 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2833 projSourceComp);
2834 params.coords = builder.createCompositeInsert(projComp, params.coords,
2835 builder.getTypeId(params.coords), projTargetComp);
2836 }
2837 }
2838
John Kessenich8c8505c2016-07-26 12:50:38 -06002839 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002840}
2841
2842spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2843{
2844 // Grab the function's pointer from the previously created function
2845 spv::Function* function = functionMap[node->getName().c_str()];
2846 if (! function)
2847 return 0;
2848
2849 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2850 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2851
2852 // See comments in makeFunctions() for details about the semantics for parameter passing.
2853 //
2854 // These imply we need a four step process:
2855 // 1. Evaluate the arguments
2856 // 2. Allocate and make copies of in, out, and inout arguments
2857 // 3. Make the call
2858 // 4. Copy back the results
2859
2860 // 1. Evaluate the arguments
2861 std::vector<spv::Builder::AccessChain> lValues;
2862 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002863 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002864 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002865 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002866 // build l-value
2867 builder.clearAccessChain();
2868 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002869 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002870 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002871 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002872 // save l-value
2873 lValues.push_back(builder.getAccessChain());
2874 } else {
2875 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002876 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002877 }
2878 }
2879
2880 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2881 // copy the original into that space.
2882 //
2883 // Also, build up the list of actual arguments to pass in for the call
2884 int lValueCount = 0;
2885 int rValueCount = 0;
2886 std::vector<spv::Id> spvArgs;
2887 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002888 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002889 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002890 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002891 builder.setAccessChain(lValues[lValueCount]);
2892 arg = builder.accessChainGetLValue();
2893 ++lValueCount;
2894 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002895 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002896 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2897 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2898 // need to copy the input into output space
2899 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002900 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002901 builder.createStore(copy, arg);
2902 }
2903 ++lValueCount;
2904 } else {
2905 arg = rValues[rValueCount];
2906 ++rValueCount;
2907 }
2908 spvArgs.push_back(arg);
2909 }
2910
2911 // 3. Make the call.
2912 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002913 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002914
2915 // 4. Copy back out an "out" arguments.
2916 lValueCount = 0;
2917 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2918 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2919 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2920 spv::Id copy = builder.createLoad(spvArgs[a]);
2921 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002922 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002923 }
2924 ++lValueCount;
2925 }
2926 }
2927
2928 return result;
2929}
2930
2931// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002932spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2933 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002934 spv::Id typeId, spv::Id left, spv::Id right,
2935 glslang::TBasicType typeProxy, bool reduceComparison)
2936{
Rex Xu8ff43de2016-04-22 16:51:45 +08002937 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002938 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002939 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002940
2941 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002942 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002943 bool comparison = false;
2944
2945 switch (op) {
2946 case glslang::EOpAdd:
2947 case glslang::EOpAddAssign:
2948 if (isFloat)
2949 binOp = spv::OpFAdd;
2950 else
2951 binOp = spv::OpIAdd;
2952 break;
2953 case glslang::EOpSub:
2954 case glslang::EOpSubAssign:
2955 if (isFloat)
2956 binOp = spv::OpFSub;
2957 else
2958 binOp = spv::OpISub;
2959 break;
2960 case glslang::EOpMul:
2961 case glslang::EOpMulAssign:
2962 if (isFloat)
2963 binOp = spv::OpFMul;
2964 else
2965 binOp = spv::OpIMul;
2966 break;
2967 case glslang::EOpVectorTimesScalar:
2968 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002969 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002970 if (builder.isVector(right))
2971 std::swap(left, right);
2972 assert(builder.isScalar(right));
2973 needMatchingVectors = false;
2974 binOp = spv::OpVectorTimesScalar;
2975 } else
2976 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002977 break;
2978 case glslang::EOpVectorTimesMatrix:
2979 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002980 binOp = spv::OpVectorTimesMatrix;
2981 break;
2982 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002983 binOp = spv::OpMatrixTimesVector;
2984 break;
2985 case glslang::EOpMatrixTimesScalar:
2986 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002987 binOp = spv::OpMatrixTimesScalar;
2988 break;
2989 case glslang::EOpMatrixTimesMatrix:
2990 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002991 binOp = spv::OpMatrixTimesMatrix;
2992 break;
2993 case glslang::EOpOuterProduct:
2994 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002995 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002996 break;
2997
2998 case glslang::EOpDiv:
2999 case glslang::EOpDivAssign:
3000 if (isFloat)
3001 binOp = spv::OpFDiv;
3002 else if (isUnsigned)
3003 binOp = spv::OpUDiv;
3004 else
3005 binOp = spv::OpSDiv;
3006 break;
3007 case glslang::EOpMod:
3008 case glslang::EOpModAssign:
3009 if (isFloat)
3010 binOp = spv::OpFMod;
3011 else if (isUnsigned)
3012 binOp = spv::OpUMod;
3013 else
3014 binOp = spv::OpSMod;
3015 break;
3016 case glslang::EOpRightShift:
3017 case glslang::EOpRightShiftAssign:
3018 if (isUnsigned)
3019 binOp = spv::OpShiftRightLogical;
3020 else
3021 binOp = spv::OpShiftRightArithmetic;
3022 break;
3023 case glslang::EOpLeftShift:
3024 case glslang::EOpLeftShiftAssign:
3025 binOp = spv::OpShiftLeftLogical;
3026 break;
3027 case glslang::EOpAnd:
3028 case glslang::EOpAndAssign:
3029 binOp = spv::OpBitwiseAnd;
3030 break;
3031 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003032 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003033 binOp = spv::OpLogicalAnd;
3034 break;
3035 case glslang::EOpInclusiveOr:
3036 case glslang::EOpInclusiveOrAssign:
3037 binOp = spv::OpBitwiseOr;
3038 break;
3039 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003040 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003041 binOp = spv::OpLogicalOr;
3042 break;
3043 case glslang::EOpExclusiveOr:
3044 case glslang::EOpExclusiveOrAssign:
3045 binOp = spv::OpBitwiseXor;
3046 break;
3047 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003048 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003049 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003050 break;
3051
3052 case glslang::EOpLessThan:
3053 case glslang::EOpGreaterThan:
3054 case glslang::EOpLessThanEqual:
3055 case glslang::EOpGreaterThanEqual:
3056 case glslang::EOpEqual:
3057 case glslang::EOpNotEqual:
3058 case glslang::EOpVectorEqual:
3059 case glslang::EOpVectorNotEqual:
3060 comparison = true;
3061 break;
3062 default:
3063 break;
3064 }
3065
John Kessenich7c1aa102015-10-15 13:29:11 -06003066 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003067 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003068 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003069 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003070 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003071
3072 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003073 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003074 builder.promoteScalar(precision, left, right);
3075
qining25262b32016-05-06 17:25:16 -04003076 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3077 addDecoration(result, noContraction);
3078 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003079 }
3080
3081 if (! comparison)
3082 return 0;
3083
John Kessenich7c1aa102015-10-15 13:29:11 -06003084 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003085
John Kessenich4583b612016-08-07 19:14:22 -06003086 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3087 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003088 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003089
3090 switch (op) {
3091 case glslang::EOpLessThan:
3092 if (isFloat)
3093 binOp = spv::OpFOrdLessThan;
3094 else if (isUnsigned)
3095 binOp = spv::OpULessThan;
3096 else
3097 binOp = spv::OpSLessThan;
3098 break;
3099 case glslang::EOpGreaterThan:
3100 if (isFloat)
3101 binOp = spv::OpFOrdGreaterThan;
3102 else if (isUnsigned)
3103 binOp = spv::OpUGreaterThan;
3104 else
3105 binOp = spv::OpSGreaterThan;
3106 break;
3107 case glslang::EOpLessThanEqual:
3108 if (isFloat)
3109 binOp = spv::OpFOrdLessThanEqual;
3110 else if (isUnsigned)
3111 binOp = spv::OpULessThanEqual;
3112 else
3113 binOp = spv::OpSLessThanEqual;
3114 break;
3115 case glslang::EOpGreaterThanEqual:
3116 if (isFloat)
3117 binOp = spv::OpFOrdGreaterThanEqual;
3118 else if (isUnsigned)
3119 binOp = spv::OpUGreaterThanEqual;
3120 else
3121 binOp = spv::OpSGreaterThanEqual;
3122 break;
3123 case glslang::EOpEqual:
3124 case glslang::EOpVectorEqual:
3125 if (isFloat)
3126 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003127 else if (isBool)
3128 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003129 else
3130 binOp = spv::OpIEqual;
3131 break;
3132 case glslang::EOpNotEqual:
3133 case glslang::EOpVectorNotEqual:
3134 if (isFloat)
3135 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003136 else if (isBool)
3137 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003138 else
3139 binOp = spv::OpINotEqual;
3140 break;
3141 default:
3142 break;
3143 }
3144
qining25262b32016-05-06 17:25:16 -04003145 if (binOp != spv::OpNop) {
3146 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3147 addDecoration(result, noContraction);
3148 return builder.setPrecision(result, precision);
3149 }
John Kessenich140f3df2015-06-26 16:58:36 -06003150
3151 return 0;
3152}
3153
John Kessenich04bb8a02015-12-12 12:28:14 -07003154//
3155// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3156// These can be any of:
3157//
3158// matrix * scalar
3159// scalar * matrix
3160// matrix * matrix linear algebraic
3161// matrix * vector
3162// vector * matrix
3163// matrix * matrix componentwise
3164// matrix op matrix op in {+, -, /}
3165// matrix op scalar op in {+, -, /}
3166// scalar op matrix op in {+, -, /}
3167//
qining25262b32016-05-06 17:25:16 -04003168spv::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 -07003169{
3170 bool firstClass = true;
3171
3172 // First, handle first-class matrix operations (* and matrix/scalar)
3173 switch (op) {
3174 case spv::OpFDiv:
3175 if (builder.isMatrix(left) && builder.isScalar(right)) {
3176 // turn matrix / scalar into a multiply...
3177 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3178 op = spv::OpMatrixTimesScalar;
3179 } else
3180 firstClass = false;
3181 break;
3182 case spv::OpMatrixTimesScalar:
3183 if (builder.isMatrix(right))
3184 std::swap(left, right);
3185 assert(builder.isScalar(right));
3186 break;
3187 case spv::OpVectorTimesMatrix:
3188 assert(builder.isVector(left));
3189 assert(builder.isMatrix(right));
3190 break;
3191 case spv::OpMatrixTimesVector:
3192 assert(builder.isMatrix(left));
3193 assert(builder.isVector(right));
3194 break;
3195 case spv::OpMatrixTimesMatrix:
3196 assert(builder.isMatrix(left));
3197 assert(builder.isMatrix(right));
3198 break;
3199 default:
3200 firstClass = false;
3201 break;
3202 }
3203
qining25262b32016-05-06 17:25:16 -04003204 if (firstClass) {
3205 spv::Id result = builder.createBinOp(op, typeId, left, right);
3206 addDecoration(result, noContraction);
3207 return builder.setPrecision(result, precision);
3208 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003209
LoopDawg592860c2016-06-09 08:57:35 -06003210 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003211 // The result type of all of them is the same type as the (a) matrix operand.
3212 // The algorithm is to:
3213 // - break the matrix(es) into vectors
3214 // - smear any scalar to a vector
3215 // - do vector operations
3216 // - make a matrix out the vector results
3217 switch (op) {
3218 case spv::OpFAdd:
3219 case spv::OpFSub:
3220 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003221 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003222 case spv::OpFMul:
3223 {
3224 // one time set up...
3225 bool leftMat = builder.isMatrix(left);
3226 bool rightMat = builder.isMatrix(right);
3227 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3228 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3229 spv::Id scalarType = builder.getScalarTypeId(typeId);
3230 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3231 std::vector<spv::Id> results;
3232 spv::Id smearVec = spv::NoResult;
3233 if (builder.isScalar(left))
3234 smearVec = builder.smearScalar(precision, left, vecType);
3235 else if (builder.isScalar(right))
3236 smearVec = builder.smearScalar(precision, right, vecType);
3237
3238 // do each vector op
3239 for (unsigned int c = 0; c < numCols; ++c) {
3240 std::vector<unsigned int> indexes;
3241 indexes.push_back(c);
3242 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3243 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003244 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3245 addDecoration(result, noContraction);
3246 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003247 }
3248
3249 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003250 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003251 }
3252 default:
3253 assert(0);
3254 return spv::NoResult;
3255 }
3256}
3257
qining25262b32016-05-06 17:25:16 -04003258spv::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 -06003259{
3260 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003261 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003262 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003263 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003264 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003265
3266 switch (op) {
3267 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003268 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003269 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003270 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003271 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003272 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003273 unaryOp = spv::OpSNegate;
3274 break;
3275
3276 case glslang::EOpLogicalNot:
3277 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003278 unaryOp = spv::OpLogicalNot;
3279 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003280 case glslang::EOpBitwiseNot:
3281 unaryOp = spv::OpNot;
3282 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003283
John Kessenich140f3df2015-06-26 16:58:36 -06003284 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003285 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003286 break;
3287 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003288 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003289 break;
3290 case glslang::EOpTranspose:
3291 unaryOp = spv::OpTranspose;
3292 break;
3293
3294 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003295 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003296 break;
3297 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003298 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003299 break;
3300 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003301 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003302 break;
3303 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003304 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003305 break;
3306 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003307 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003308 break;
3309 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003310 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003311 break;
3312 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
3318
3319 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003320 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003321 break;
3322 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003323 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 break;
3325 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003326 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003327 break;
3328 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003329 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003330 break;
3331 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003332 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003333 break;
3334 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003335 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003336 break;
3337
3338 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003339 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003340 break;
3341 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003342 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003343 break;
3344
3345 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003346 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003347 break;
3348 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003349 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003350 break;
3351 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003352 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003353 break;
3354 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003355 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003356 break;
3357 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003358 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003359 break;
3360 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003361 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003362 break;
3363
3364 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003365 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003366 break;
3367 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003369 break;
3370 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003371 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003372 break;
3373 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003374 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003375 break;
3376 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003377 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003378 break;
3379 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003380 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003381 break;
3382
3383 case glslang::EOpIsNan:
3384 unaryOp = spv::OpIsNan;
3385 break;
3386 case glslang::EOpIsInf:
3387 unaryOp = spv::OpIsInf;
3388 break;
LoopDawg592860c2016-06-09 08:57:35 -06003389 case glslang::EOpIsFinite:
3390 unaryOp = spv::OpIsFinite;
3391 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003392
Rex Xucbc426e2015-12-15 16:03:10 +08003393 case glslang::EOpFloatBitsToInt:
3394 case glslang::EOpFloatBitsToUint:
3395 case glslang::EOpIntBitsToFloat:
3396 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003397 case glslang::EOpDoubleBitsToInt64:
3398 case glslang::EOpDoubleBitsToUint64:
3399 case glslang::EOpInt64BitsToDouble:
3400 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003401 unaryOp = spv::OpBitcast;
3402 break;
3403
John Kessenich140f3df2015-06-26 16:58:36 -06003404 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003405 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003406 break;
3407 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003408 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003411 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003412 break;
3413 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003414 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003415 break;
3416 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003417 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 break;
3419 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003420 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003421 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003422 case glslang::EOpPackSnorm4x8:
3423 libCall = spv::GLSLstd450PackSnorm4x8;
3424 break;
3425 case glslang::EOpUnpackSnorm4x8:
3426 libCall = spv::GLSLstd450UnpackSnorm4x8;
3427 break;
3428 case glslang::EOpPackUnorm4x8:
3429 libCall = spv::GLSLstd450PackUnorm4x8;
3430 break;
3431 case glslang::EOpUnpackUnorm4x8:
3432 libCall = spv::GLSLstd450UnpackUnorm4x8;
3433 break;
3434 case glslang::EOpPackDouble2x32:
3435 libCall = spv::GLSLstd450PackDouble2x32;
3436 break;
3437 case glslang::EOpUnpackDouble2x32:
3438 libCall = spv::GLSLstd450UnpackDouble2x32;
3439 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003440
Rex Xu8ff43de2016-04-22 16:51:45 +08003441 case glslang::EOpPackInt2x32:
3442 case glslang::EOpUnpackInt2x32:
3443 case glslang::EOpPackUint2x32:
3444 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003445 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003446 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3447 break;
3448
John Kessenich140f3df2015-06-26 16:58:36 -06003449 case glslang::EOpDPdx:
3450 unaryOp = spv::OpDPdx;
3451 break;
3452 case glslang::EOpDPdy:
3453 unaryOp = spv::OpDPdy;
3454 break;
3455 case glslang::EOpFwidth:
3456 unaryOp = spv::OpFwidth;
3457 break;
3458 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003459 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003460 unaryOp = spv::OpDPdxFine;
3461 break;
3462 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003463 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003464 unaryOp = spv::OpDPdyFine;
3465 break;
3466 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003467 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003468 unaryOp = spv::OpFwidthFine;
3469 break;
3470 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003471 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003472 unaryOp = spv::OpDPdxCoarse;
3473 break;
3474 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003475 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003476 unaryOp = spv::OpDPdyCoarse;
3477 break;
3478 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003479 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003480 unaryOp = spv::OpFwidthCoarse;
3481 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003482 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003483 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003484 libCall = spv::GLSLstd450InterpolateAtCentroid;
3485 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003486 case glslang::EOpAny:
3487 unaryOp = spv::OpAny;
3488 break;
3489 case glslang::EOpAll:
3490 unaryOp = spv::OpAll;
3491 break;
3492
3493 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003494 if (isFloat)
3495 libCall = spv::GLSLstd450FAbs;
3496 else
3497 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003500 if (isFloat)
3501 libCall = spv::GLSLstd450FSign;
3502 else
3503 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003504 break;
3505
John Kessenichfc51d282015-08-19 13:34:18 -06003506 case glslang::EOpAtomicCounterIncrement:
3507 case glslang::EOpAtomicCounterDecrement:
3508 case glslang::EOpAtomicCounter:
3509 {
3510 // Handle all of the atomics in one place, in createAtomicOperation()
3511 std::vector<spv::Id> operands;
3512 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003513 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003514 }
3515
John Kessenichfc51d282015-08-19 13:34:18 -06003516 case glslang::EOpBitFieldReverse:
3517 unaryOp = spv::OpBitReverse;
3518 break;
3519 case glslang::EOpBitCount:
3520 unaryOp = spv::OpBitCount;
3521 break;
3522 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003523 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003524 break;
3525 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003526 if (isUnsigned)
3527 libCall = spv::GLSLstd450FindUMsb;
3528 else
3529 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003530 break;
3531
Rex Xu574ab042016-04-14 16:53:07 +08003532 case glslang::EOpBallot:
3533 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003534 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003535 libCall = spv::GLSLstd450Bad;
3536 break;
3537
Rex Xu338b1852016-05-05 20:38:33 +08003538 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003539 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003540 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003541#ifdef AMD_EXTENSIONS
3542 case glslang::EOpMinInvocations:
3543 case glslang::EOpMaxInvocations:
3544 case glslang::EOpAddInvocations:
3545 case glslang::EOpMinInvocationsNonUniform:
3546 case glslang::EOpMaxInvocationsNonUniform:
3547 case glslang::EOpAddInvocationsNonUniform:
3548#endif
3549 return createInvocationsOperation(op, typeId, operand, typeProxy);
3550
3551#ifdef AMD_EXTENSIONS
3552 case glslang::EOpMbcnt:
3553 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3554 libCall = spv::MbcntAMD;
3555 break;
3556
3557 case glslang::EOpCubeFaceIndex:
3558 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3559 libCall = spv::CubeFaceIndexAMD;
3560 break;
3561
3562 case glslang::EOpCubeFaceCoord:
3563 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3564 libCall = spv::CubeFaceCoordAMD;
3565 break;
3566#endif
Rex Xu338b1852016-05-05 20:38:33 +08003567
John Kessenich140f3df2015-06-26 16:58:36 -06003568 default:
3569 return 0;
3570 }
3571
3572 spv::Id id;
3573 if (libCall >= 0) {
3574 std::vector<spv::Id> args;
3575 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003576 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003577 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003578 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003579 }
John Kessenich140f3df2015-06-26 16:58:36 -06003580
qining25262b32016-05-06 17:25:16 -04003581 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003582 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003583}
3584
John Kessenich7a53f762016-01-20 11:19:27 -07003585// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003586spv::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 -07003587{
3588 // Handle unary operations vector by vector.
3589 // The result type is the same type as the original type.
3590 // The algorithm is to:
3591 // - break the matrix into vectors
3592 // - apply the operation to each vector
3593 // - make a matrix out the vector results
3594
3595 // get the types sorted out
3596 int numCols = builder.getNumColumns(operand);
3597 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003598 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3599 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003600 std::vector<spv::Id> results;
3601
3602 // do each vector op
3603 for (int c = 0; c < numCols; ++c) {
3604 std::vector<unsigned int> indexes;
3605 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003606 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3607 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3608 addDecoration(destVec, noContraction);
3609 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003610 }
3611
3612 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003613 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003614}
3615
Rex Xu73e3ce72016-04-27 18:48:17 +08003616spv::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 -06003617{
3618 spv::Op convOp = spv::OpNop;
3619 spv::Id zero = 0;
3620 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003621 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003622
3623 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3624
3625 switch (op) {
3626 case glslang::EOpConvIntToBool:
3627 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003628 case glslang::EOpConvInt64ToBool:
3629 case glslang::EOpConvUint64ToBool:
3630 zero = (op == glslang::EOpConvInt64ToBool ||
3631 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003632 zero = makeSmearedConstant(zero, vectorSize);
3633 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3634
3635 case glslang::EOpConvFloatToBool:
3636 zero = builder.makeFloatConstant(0.0F);
3637 zero = makeSmearedConstant(zero, vectorSize);
3638 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3639
3640 case glslang::EOpConvDoubleToBool:
3641 zero = builder.makeDoubleConstant(0.0);
3642 zero = makeSmearedConstant(zero, vectorSize);
3643 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3644
3645 case glslang::EOpConvBoolToFloat:
3646 convOp = spv::OpSelect;
3647 zero = builder.makeFloatConstant(0.0);
3648 one = builder.makeFloatConstant(1.0);
3649 break;
3650 case glslang::EOpConvBoolToDouble:
3651 convOp = spv::OpSelect;
3652 zero = builder.makeDoubleConstant(0.0);
3653 one = builder.makeDoubleConstant(1.0);
3654 break;
3655 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003656 case glslang::EOpConvBoolToInt64:
3657 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3658 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003659 convOp = spv::OpSelect;
3660 break;
3661 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003662 case glslang::EOpConvBoolToUint64:
3663 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3664 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003665 convOp = spv::OpSelect;
3666 break;
3667
3668 case glslang::EOpConvIntToFloat:
3669 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003670 case glslang::EOpConvInt64ToFloat:
3671 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003672 convOp = spv::OpConvertSToF;
3673 break;
3674
3675 case glslang::EOpConvUintToFloat:
3676 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003677 case glslang::EOpConvUint64ToFloat:
3678 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003679 convOp = spv::OpConvertUToF;
3680 break;
3681
3682 case glslang::EOpConvDoubleToFloat:
3683 case glslang::EOpConvFloatToDouble:
3684 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003685 if (builder.isMatrixType(destType))
3686 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688
3689 case glslang::EOpConvFloatToInt:
3690 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003691 case glslang::EOpConvFloatToInt64:
3692 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003693 convOp = spv::OpConvertFToS;
3694 break;
3695
3696 case glslang::EOpConvUintToInt:
3697 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003698 case glslang::EOpConvUint64ToInt64:
3699 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003700 if (builder.isInSpecConstCodeGenMode()) {
3701 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003702 zero = (op == glslang::EOpConvUintToInt64 ||
3703 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003704 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003705 // Use OpIAdd, instead of OpBitcast to do the conversion when
3706 // generating for OpSpecConstantOp instruction.
3707 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3708 }
3709 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003710 convOp = spv::OpBitcast;
3711 break;
3712
3713 case glslang::EOpConvFloatToUint:
3714 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003715 case glslang::EOpConvFloatToUint64:
3716 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003717 convOp = spv::OpConvertFToU;
3718 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003719
3720 case glslang::EOpConvIntToInt64:
3721 case glslang::EOpConvInt64ToInt:
3722 convOp = spv::OpSConvert;
3723 break;
3724
3725 case glslang::EOpConvUintToUint64:
3726 case glslang::EOpConvUint64ToUint:
3727 convOp = spv::OpUConvert;
3728 break;
3729
3730 case glslang::EOpConvIntToUint64:
3731 case glslang::EOpConvInt64ToUint:
3732 case glslang::EOpConvUint64ToInt:
3733 case glslang::EOpConvUintToInt64:
3734 // OpSConvert/OpUConvert + OpBitCast
3735 switch (op) {
3736 case glslang::EOpConvIntToUint64:
3737 convOp = spv::OpSConvert;
3738 type = builder.makeIntType(64);
3739 break;
3740 case glslang::EOpConvInt64ToUint:
3741 convOp = spv::OpSConvert;
3742 type = builder.makeIntType(32);
3743 break;
3744 case glslang::EOpConvUint64ToInt:
3745 convOp = spv::OpUConvert;
3746 type = builder.makeUintType(32);
3747 break;
3748 case glslang::EOpConvUintToInt64:
3749 convOp = spv::OpUConvert;
3750 type = builder.makeUintType(64);
3751 break;
3752 default:
3753 assert(0);
3754 break;
3755 }
3756
3757 if (vectorSize > 0)
3758 type = builder.makeVectorType(type, vectorSize);
3759
3760 operand = builder.createUnaryOp(convOp, type, operand);
3761
3762 if (builder.isInSpecConstCodeGenMode()) {
3763 // Build zero scalar or vector for OpIAdd.
3764 zero = (op == glslang::EOpConvIntToUint64 ||
3765 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3766 zero = makeSmearedConstant(zero, vectorSize);
3767 // Use OpIAdd, instead of OpBitcast to do the conversion when
3768 // generating for OpSpecConstantOp instruction.
3769 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3770 }
3771 // For normal run-time conversion instruction, use OpBitcast.
3772 convOp = spv::OpBitcast;
3773 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 default:
3775 break;
3776 }
3777
3778 spv::Id result = 0;
3779 if (convOp == spv::OpNop)
3780 return result;
3781
3782 if (convOp == spv::OpSelect) {
3783 zero = makeSmearedConstant(zero, vectorSize);
3784 one = makeSmearedConstant(one, vectorSize);
3785 result = builder.createTriOp(convOp, destType, operand, one, zero);
3786 } else
3787 result = builder.createUnaryOp(convOp, destType, operand);
3788
John Kessenich32cfd492016-02-02 12:37:46 -07003789 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003790}
3791
3792spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3793{
3794 if (vectorSize == 0)
3795 return constant;
3796
3797 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3798 std::vector<spv::Id> components;
3799 for (int c = 0; c < vectorSize; ++c)
3800 components.push_back(constant);
3801 return builder.makeCompositeConstant(vectorTypeId, components);
3802}
3803
John Kessenich426394d2015-07-23 10:22:48 -06003804// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003805spv::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 -06003806{
3807 spv::Op opCode = spv::OpNop;
3808
3809 switch (op) {
3810 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003811 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003812 opCode = spv::OpAtomicIAdd;
3813 break;
3814 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003815 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003816 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003817 break;
3818 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003819 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003820 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003821 break;
3822 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003823 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003824 opCode = spv::OpAtomicAnd;
3825 break;
3826 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003827 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003828 opCode = spv::OpAtomicOr;
3829 break;
3830 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003831 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003832 opCode = spv::OpAtomicXor;
3833 break;
3834 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003835 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003836 opCode = spv::OpAtomicExchange;
3837 break;
3838 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003839 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003840 opCode = spv::OpAtomicCompareExchange;
3841 break;
3842 case glslang::EOpAtomicCounterIncrement:
3843 opCode = spv::OpAtomicIIncrement;
3844 break;
3845 case glslang::EOpAtomicCounterDecrement:
3846 opCode = spv::OpAtomicIDecrement;
3847 break;
3848 case glslang::EOpAtomicCounter:
3849 opCode = spv::OpAtomicLoad;
3850 break;
3851 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003852 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003853 break;
3854 }
3855
3856 // Sort out the operands
3857 // - mapping from glslang -> SPV
3858 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003859 // - compare-exchange swaps the value and comparator
3860 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003861 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3862 auto opIt = operands.begin(); // walk the glslang operands
3863 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003864 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3865 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3866 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003867 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3868 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003869 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003870 spvAtomicOperands.push_back(*(opIt + 1));
3871 spvAtomicOperands.push_back(*opIt);
3872 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003873 }
John Kessenich426394d2015-07-23 10:22:48 -06003874
John Kessenich3e60a6f2015-09-14 22:45:16 -06003875 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003876 for (; opIt != operands.end(); ++opIt)
3877 spvAtomicOperands.push_back(*opIt);
3878
3879 return builder.createOp(opCode, typeId, spvAtomicOperands);
3880}
3881
John Kessenich91cef522016-05-05 16:45:40 -06003882// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003883spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003884{
Rex Xu9d93a232016-05-05 12:30:44 +08003885 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3886 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3887
John Kessenich91cef522016-05-05 16:45:40 -06003888 builder.addCapability(spv::CapabilityGroups);
3889
3890 std::vector<spv::Id> operands;
3891 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003892#ifdef AMD_EXTENSIONS
3893 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3894 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3895 operands.push_back(spv::GroupOperationReduce);
3896#endif
John Kessenich91cef522016-05-05 16:45:40 -06003897 operands.push_back(operand);
3898
3899 switch (op) {
3900 case glslang::EOpAnyInvocation:
3901 case glslang::EOpAllInvocations:
3902 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3903
3904 case glslang::EOpAllInvocationsEqual:
3905 {
3906 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3907 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3908
3909 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3910 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3911 }
Rex Xu9d93a232016-05-05 12:30:44 +08003912#ifdef AMD_EXTENSIONS
3913 case glslang::EOpMinInvocations:
3914 case glslang::EOpMaxInvocations:
3915 case glslang::EOpAddInvocations:
3916 {
3917 spv::Op spvOp = spv::OpNop;
3918 if (op == glslang::EOpMinInvocations) {
3919 if (isFloat)
3920 spvOp = spv::OpGroupFMin;
3921 else {
3922 if (isUnsigned)
3923 spvOp = spv::OpGroupUMin;
3924 else
3925 spvOp = spv::OpGroupSMin;
3926 }
3927 } else if (op == glslang::EOpMaxInvocations) {
3928 if (isFloat)
3929 spvOp = spv::OpGroupFMax;
3930 else {
3931 if (isUnsigned)
3932 spvOp = spv::OpGroupUMax;
3933 else
3934 spvOp = spv::OpGroupSMax;
3935 }
3936 } else {
3937 if (isFloat)
3938 spvOp = spv::OpGroupFAdd;
3939 else
3940 spvOp = spv::OpGroupIAdd;
3941 }
3942
3943 return builder.createOp(spvOp, typeId, operands);
3944 }
3945 case glslang::EOpMinInvocationsNonUniform:
3946 case glslang::EOpMaxInvocationsNonUniform:
3947 case glslang::EOpAddInvocationsNonUniform:
3948 {
3949 spv::Op spvOp = spv::OpNop;
3950 if (op == glslang::EOpMinInvocationsNonUniform) {
3951 if (isFloat)
3952 spvOp = spv::OpGroupFMinNonUniformAMD;
3953 else {
3954 if (isUnsigned)
3955 spvOp = spv::OpGroupUMinNonUniformAMD;
3956 else
3957 spvOp = spv::OpGroupSMinNonUniformAMD;
3958 }
3959 }
3960 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3961 if (isFloat)
3962 spvOp = spv::OpGroupFMaxNonUniformAMD;
3963 else {
3964 if (isUnsigned)
3965 spvOp = spv::OpGroupUMaxNonUniformAMD;
3966 else
3967 spvOp = spv::OpGroupSMaxNonUniformAMD;
3968 }
3969 }
3970 else {
3971 if (isFloat)
3972 spvOp = spv::OpGroupFAddNonUniformAMD;
3973 else
3974 spvOp = spv::OpGroupIAddNonUniformAMD;
3975 }
3976
3977 return builder.createOp(spvOp, typeId, operands);
3978 }
3979#endif
John Kessenich91cef522016-05-05 16:45:40 -06003980 default:
3981 logger->missingFunctionality("invocation operation");
3982 return spv::NoResult;
3983 }
3984}
3985
John Kessenich5e4b1242015-08-06 22:53:06 -06003986spv::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 -06003987{
Rex Xu8ff43de2016-04-22 16:51:45 +08003988 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003989 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3990
John Kessenich140f3df2015-06-26 16:58:36 -06003991 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003992 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003993 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003994 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003995 spv::Id typeId0 = 0;
3996 if (consumedOperands > 0)
3997 typeId0 = builder.getTypeId(operands[0]);
3998 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003999
4000 switch (op) {
4001 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004002 if (isFloat)
4003 libCall = spv::GLSLstd450FMin;
4004 else if (isUnsigned)
4005 libCall = spv::GLSLstd450UMin;
4006 else
4007 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004008 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004009 break;
4010 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004011 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 break;
4013 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 if (isFloat)
4015 libCall = spv::GLSLstd450FMax;
4016 else if (isUnsigned)
4017 libCall = spv::GLSLstd450UMax;
4018 else
4019 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004020 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004021 break;
4022 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004023 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004024 break;
4025 case glslang::EOpDot:
4026 opCode = spv::OpDot;
4027 break;
4028 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004029 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004030 break;
4031
4032 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004033 if (isFloat)
4034 libCall = spv::GLSLstd450FClamp;
4035 else if (isUnsigned)
4036 libCall = spv::GLSLstd450UClamp;
4037 else
4038 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004039 builder.promoteScalar(precision, operands.front(), operands[1]);
4040 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004041 break;
4042 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004043 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4044 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004045 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004046 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004047 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004048 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004049 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004050 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004051 break;
4052 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004053 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004054 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004055 break;
4056 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004057 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004058 builder.promoteScalar(precision, operands[0], operands[2]);
4059 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061
4062 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004063 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004064 break;
4065 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004066 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004067 break;
4068 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004069 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004070 break;
4071 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004072 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004073 break;
4074 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004076 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004077 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004078 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004079 libCall = spv::GLSLstd450InterpolateAtSample;
4080 break;
4081 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004082 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004083 libCall = spv::GLSLstd450InterpolateAtOffset;
4084 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004085 case glslang::EOpAddCarry:
4086 opCode = spv::OpIAddCarry;
4087 typeId = builder.makeStructResultType(typeId0, typeId0);
4088 consumedOperands = 2;
4089 break;
4090 case glslang::EOpSubBorrow:
4091 opCode = spv::OpISubBorrow;
4092 typeId = builder.makeStructResultType(typeId0, typeId0);
4093 consumedOperands = 2;
4094 break;
4095 case glslang::EOpUMulExtended:
4096 opCode = spv::OpUMulExtended;
4097 typeId = builder.makeStructResultType(typeId0, typeId0);
4098 consumedOperands = 2;
4099 break;
4100 case glslang::EOpIMulExtended:
4101 opCode = spv::OpSMulExtended;
4102 typeId = builder.makeStructResultType(typeId0, typeId0);
4103 consumedOperands = 2;
4104 break;
4105 case glslang::EOpBitfieldExtract:
4106 if (isUnsigned)
4107 opCode = spv::OpBitFieldUExtract;
4108 else
4109 opCode = spv::OpBitFieldSExtract;
4110 break;
4111 case glslang::EOpBitfieldInsert:
4112 opCode = spv::OpBitFieldInsert;
4113 break;
4114
4115 case glslang::EOpFma:
4116 libCall = spv::GLSLstd450Fma;
4117 break;
4118 case glslang::EOpFrexp:
4119 libCall = spv::GLSLstd450FrexpStruct;
4120 if (builder.getNumComponents(operands[0]) == 1)
4121 frexpIntType = builder.makeIntegerType(32, true);
4122 else
4123 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4124 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4125 consumedOperands = 1;
4126 break;
4127 case glslang::EOpLdexp:
4128 libCall = spv::GLSLstd450Ldexp;
4129 break;
4130
Rex Xu574ab042016-04-14 16:53:07 +08004131 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004132 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004133 libCall = spv::GLSLstd450Bad;
4134 break;
4135
Rex Xu9d93a232016-05-05 12:30:44 +08004136#ifdef AMD_EXTENSIONS
4137 case glslang::EOpSwizzleInvocations:
4138 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4139 libCall = spv::SwizzleInvocationsAMD;
4140 break;
4141 case glslang::EOpSwizzleInvocationsMasked:
4142 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4143 libCall = spv::SwizzleInvocationsMaskedAMD;
4144 break;
4145 case glslang::EOpWriteInvocation:
4146 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4147 libCall = spv::WriteInvocationAMD;
4148 break;
4149
4150 case glslang::EOpMin3:
4151 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4152 if (isFloat)
4153 libCall = spv::FMin3AMD;
4154 else {
4155 if (isUnsigned)
4156 libCall = spv::UMin3AMD;
4157 else
4158 libCall = spv::SMin3AMD;
4159 }
4160 break;
4161 case glslang::EOpMax3:
4162 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4163 if (isFloat)
4164 libCall = spv::FMax3AMD;
4165 else {
4166 if (isUnsigned)
4167 libCall = spv::UMax3AMD;
4168 else
4169 libCall = spv::SMax3AMD;
4170 }
4171 break;
4172 case glslang::EOpMid3:
4173 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4174 if (isFloat)
4175 libCall = spv::FMid3AMD;
4176 else {
4177 if (isUnsigned)
4178 libCall = spv::UMid3AMD;
4179 else
4180 libCall = spv::SMid3AMD;
4181 }
4182 break;
4183
4184 case glslang::EOpInterpolateAtVertex:
4185 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4186 libCall = spv::InterpolateAtVertexAMD;
4187 break;
4188#endif
4189
John Kessenich140f3df2015-06-26 16:58:36 -06004190 default:
4191 return 0;
4192 }
4193
4194 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004195 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004196 // Use an extended instruction from the standard library.
4197 // Construct the call arguments, without modifying the original operands vector.
4198 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4199 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004200 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004201 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004202 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004203 case 0:
4204 // should all be handled by visitAggregate and createNoArgOperation
4205 assert(0);
4206 return 0;
4207 case 1:
4208 // should all be handled by createUnaryOperation
4209 assert(0);
4210 return 0;
4211 case 2:
4212 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4213 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004214 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004215 // anything 3 or over doesn't have l-value operands, so all should be consumed
4216 assert(consumedOperands == operands.size());
4217 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004218 break;
4219 }
4220 }
4221
John Kessenich55e7d112015-11-15 21:33:39 -07004222 // Decode the return types that were structures
4223 switch (op) {
4224 case glslang::EOpAddCarry:
4225 case glslang::EOpSubBorrow:
4226 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4227 id = builder.createCompositeExtract(id, typeId0, 0);
4228 break;
4229 case glslang::EOpUMulExtended:
4230 case glslang::EOpIMulExtended:
4231 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4232 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4233 break;
4234 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004235 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004236 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4237 id = builder.createCompositeExtract(id, typeId0, 0);
4238 break;
4239 default:
4240 break;
4241 }
4242
John Kessenich32cfd492016-02-02 12:37:46 -07004243 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004244}
4245
Rex Xu9d93a232016-05-05 12:30:44 +08004246// Intrinsics with no arguments (or no return value, and no precision).
4247spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004248{
4249 // TODO: get the barrier operands correct
4250
4251 switch (op) {
4252 case glslang::EOpEmitVertex:
4253 builder.createNoResultOp(spv::OpEmitVertex);
4254 return 0;
4255 case glslang::EOpEndPrimitive:
4256 builder.createNoResultOp(spv::OpEndPrimitive);
4257 return 0;
4258 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004259 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004260 return 0;
4261 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004262 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004263 return 0;
4264 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004265 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004266 return 0;
4267 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004268 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004269 return 0;
4270 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004271 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004272 return 0;
4273 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004274 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004275 return 0;
4276 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004277 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004278 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004279 case glslang::EOpAllMemoryBarrierWithGroupSync:
4280 // Control barrier with non-"None" semantic is also a memory barrier.
4281 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4282 return 0;
4283 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4284 // Control barrier with non-"None" semantic is also a memory barrier.
4285 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4286 return 0;
4287 case glslang::EOpWorkgroupMemoryBarrier:
4288 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4289 return 0;
4290 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4291 // Control barrier with non-"None" semantic is also a memory barrier.
4292 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4293 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004294#ifdef AMD_EXTENSIONS
4295 case glslang::EOpTime:
4296 {
4297 std::vector<spv::Id> args; // Dummy arguments
4298 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4299 return builder.setPrecision(id, precision);
4300 }
4301#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004302 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004303 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004304 return 0;
4305 }
4306}
4307
4308spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4309{
John Kessenich2f273362015-07-18 22:34:27 -06004310 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004311 spv::Id id;
4312 if (symbolValues.end() != iter) {
4313 id = iter->second;
4314 return id;
4315 }
4316
4317 // it was not found, create it
4318 id = createSpvVariable(symbol);
4319 symbolValues[symbol->getId()] = id;
4320
Rex Xuc884b4a2016-06-29 15:03:44 +08004321 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004322 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004323 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004324 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004325 if (symbol->getType().getQualifier().hasSpecConstantId())
4326 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004327 if (symbol->getQualifier().hasIndex())
4328 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4329 if (symbol->getQualifier().hasComponent())
4330 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4331 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004332 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004333 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004334 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004335 if (symbol->getQualifier().hasXfbBuffer())
4336 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4337 if (symbol->getQualifier().hasXfbOffset())
4338 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4339 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004340 // atomic counters use this:
4341 if (symbol->getQualifier().hasOffset())
4342 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004343 }
4344
scygan2c864272016-05-18 18:09:17 +02004345 if (symbol->getQualifier().hasLocation())
4346 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004347 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004348 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004349 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004350 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004351 }
John Kessenich140f3df2015-06-26 16:58:36 -06004352 if (symbol->getQualifier().hasSet())
4353 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004354 else if (IsDescriptorResource(symbol->getType())) {
4355 // default to 0
4356 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4357 }
John Kessenich140f3df2015-06-26 16:58:36 -06004358 if (symbol->getQualifier().hasBinding())
4359 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004360 if (symbol->getQualifier().hasAttachment())
4361 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004362 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004363 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004364 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004365 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004366 if (symbol->getQualifier().hasXfbBuffer())
4367 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4368 }
4369
Rex Xu1da878f2016-02-21 20:59:01 +08004370 if (symbol->getType().isImage()) {
4371 std::vector<spv::Decoration> memory;
4372 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4373 for (unsigned int i = 0; i < memory.size(); ++i)
4374 addDecoration(id, memory[i]);
4375 }
4376
John Kessenich140f3df2015-06-26 16:58:36 -06004377 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004378 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004379 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004380 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004381
John Kessenich140f3df2015-06-26 16:58:36 -06004382 return id;
4383}
4384
John Kessenich55e7d112015-11-15 21:33:39 -07004385// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004386void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4387{
John Kessenich4016e382016-07-15 11:53:56 -06004388 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004389 builder.addDecoration(id, dec);
4390}
4391
John Kessenich55e7d112015-11-15 21:33:39 -07004392// If 'dec' is valid, add a one-operand decoration to an object
4393void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4394{
John Kessenich4016e382016-07-15 11:53:56 -06004395 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004396 builder.addDecoration(id, dec, value);
4397}
4398
4399// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004400void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4401{
John Kessenich4016e382016-07-15 11:53:56 -06004402 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004403 builder.addMemberDecoration(id, (unsigned)member, dec);
4404}
4405
John Kessenich92187592016-02-01 13:45:25 -07004406// If 'dec' is valid, add a one-operand decoration to a struct member
4407void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4408{
John Kessenich4016e382016-07-15 11:53:56 -06004409 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004410 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4411}
4412
John Kessenich55e7d112015-11-15 21:33:39 -07004413// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004414// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004415//
4416// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4417//
4418// Recursively walk the nodes. The nodes form a tree whose leaves are
4419// regular constants, which themselves are trees that createSpvConstant()
4420// recursively walks. So, this function walks the "top" of the tree:
4421// - emit specialization constant-building instructions for specConstant
4422// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004423spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004424{
John Kessenich7cc0e282016-03-20 00:46:02 -06004425 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004426
qining4f4bb812016-04-03 23:55:17 -04004427 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004428 if (! node.getQualifier().specConstant) {
4429 // hand off to the non-spec-constant path
4430 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4431 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004432 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004433 nextConst, false);
4434 }
4435
4436 // We now know we have a specialization constant to build
4437
John Kessenichd94c0032016-05-30 19:29:40 -06004438 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004439 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4440 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4441 std::vector<spv::Id> dimConstId;
4442 for (int dim = 0; dim < 3; ++dim) {
4443 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4444 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4445 if (specConst)
4446 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4447 }
4448 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4449 }
4450
4451 // An AST node labelled as specialization constant should be a symbol node.
4452 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4453 if (auto* sn = node.getAsSymbolNode()) {
4454 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004455 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4456 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4457 // will set the builder into spec constant op instruction generating mode.
4458 sub_tree->traverse(this);
4459 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004460 } else if (auto* const_union_array = &sn->getConstArray()){
4461 int nextConst = 0;
4462 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004463 }
4464 }
qining4f4bb812016-04-03 23:55:17 -04004465
4466 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4467 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004468 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004469 exit(1);
4470 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004471}
4472
John Kessenich140f3df2015-06-26 16:58:36 -06004473// Use 'consts' as the flattened glslang source of scalar constants to recursively
4474// build the aggregate SPIR-V constant.
4475//
4476// If there are not enough elements present in 'consts', 0 will be substituted;
4477// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4478//
qining08408382016-03-21 09:51:37 -04004479spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004480{
4481 // vector of constants for SPIR-V
4482 std::vector<spv::Id> spvConsts;
4483
4484 // Type is used for struct and array constants
4485 spv::Id typeId = convertGlslangToSpvType(glslangType);
4486
4487 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004488 glslang::TType elementType(glslangType, 0);
4489 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004490 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004491 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004492 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004493 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004494 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004495 } else if (glslangType.getStruct()) {
4496 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4497 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004498 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004499 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004500 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4501 bool zero = nextConst >= consts.size();
4502 switch (glslangType.getBasicType()) {
4503 case glslang::EbtInt:
4504 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4505 break;
4506 case glslang::EbtUint:
4507 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4508 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004509 case glslang::EbtInt64:
4510 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4511 break;
4512 case glslang::EbtUint64:
4513 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4514 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004515 case glslang::EbtFloat:
4516 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4517 break;
4518 case glslang::EbtDouble:
4519 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4520 break;
4521 case glslang::EbtBool:
4522 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4523 break;
4524 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004525 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004526 break;
4527 }
4528 ++nextConst;
4529 }
4530 } else {
4531 // we have a non-aggregate (scalar) constant
4532 bool zero = nextConst >= consts.size();
4533 spv::Id scalar = 0;
4534 switch (glslangType.getBasicType()) {
4535 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004536 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004537 break;
4538 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004539 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004540 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004541 case glslang::EbtInt64:
4542 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4543 break;
4544 case glslang::EbtUint64:
4545 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4546 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004547 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004548 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004549 break;
4550 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004551 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004552 break;
4553 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004554 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004555 break;
4556 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004557 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004558 break;
4559 }
4560 ++nextConst;
4561 return scalar;
4562 }
4563
4564 return builder.makeCompositeConstant(typeId, spvConsts);
4565}
4566
John Kessenich7c1aa102015-10-15 13:29:11 -06004567// Return true if the node is a constant or symbol whose reading has no
4568// non-trivial observable cost or effect.
4569bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4570{
4571 // don't know what this is
4572 if (node == nullptr)
4573 return false;
4574
4575 // a constant is safe
4576 if (node->getAsConstantUnion() != nullptr)
4577 return true;
4578
4579 // not a symbol means non-trivial
4580 if (node->getAsSymbolNode() == nullptr)
4581 return false;
4582
4583 // a symbol, depends on what's being read
4584 switch (node->getType().getQualifier().storage) {
4585 case glslang::EvqTemporary:
4586 case glslang::EvqGlobal:
4587 case glslang::EvqIn:
4588 case glslang::EvqInOut:
4589 case glslang::EvqConst:
4590 case glslang::EvqConstReadOnly:
4591 case glslang::EvqUniform:
4592 return true;
4593 default:
4594 return false;
4595 }
qining25262b32016-05-06 17:25:16 -04004596}
John Kessenich7c1aa102015-10-15 13:29:11 -06004597
4598// A node is trivial if it is a single operation with no side effects.
4599// Error on the side of saying non-trivial.
4600// Return true if trivial.
4601bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4602{
4603 if (node == nullptr)
4604 return false;
4605
4606 // symbols and constants are trivial
4607 if (isTrivialLeaf(node))
4608 return true;
4609
4610 // otherwise, it needs to be a simple operation or one or two leaf nodes
4611
4612 // not a simple operation
4613 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4614 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4615 if (binaryNode == nullptr && unaryNode == nullptr)
4616 return false;
4617
4618 // not on leaf nodes
4619 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4620 return false;
4621
4622 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4623 return false;
4624 }
4625
4626 switch (node->getAsOperator()->getOp()) {
4627 case glslang::EOpLogicalNot:
4628 case glslang::EOpConvIntToBool:
4629 case glslang::EOpConvUintToBool:
4630 case glslang::EOpConvFloatToBool:
4631 case glslang::EOpConvDoubleToBool:
4632 case glslang::EOpEqual:
4633 case glslang::EOpNotEqual:
4634 case glslang::EOpLessThan:
4635 case glslang::EOpGreaterThan:
4636 case glslang::EOpLessThanEqual:
4637 case glslang::EOpGreaterThanEqual:
4638 case glslang::EOpIndexDirect:
4639 case glslang::EOpIndexDirectStruct:
4640 case glslang::EOpLogicalXor:
4641 case glslang::EOpAny:
4642 case glslang::EOpAll:
4643 return true;
4644 default:
4645 return false;
4646 }
4647}
4648
4649// Emit short-circuiting code, where 'right' is never evaluated unless
4650// the left side is true (for &&) or false (for ||).
4651spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4652{
4653 spv::Id boolTypeId = builder.makeBoolType();
4654
4655 // emit left operand
4656 builder.clearAccessChain();
4657 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004658 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004659
4660 // Operands to accumulate OpPhi operands
4661 std::vector<spv::Id> phiOperands;
4662 // accumulate left operand's phi information
4663 phiOperands.push_back(leftId);
4664 phiOperands.push_back(builder.getBuildPoint()->getId());
4665
4666 // Make the two kinds of operation symmetric with a "!"
4667 // || => emit "if (! left) result = right"
4668 // && => emit "if ( left) result = right"
4669 //
4670 // TODO: this runtime "not" for || could be avoided by adding functionality
4671 // to 'builder' to have an "else" without an "then"
4672 if (op == glslang::EOpLogicalOr)
4673 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4674
4675 // make an "if" based on the left value
4676 spv::Builder::If ifBuilder(leftId, builder);
4677
4678 // emit right operand as the "then" part of the "if"
4679 builder.clearAccessChain();
4680 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004681 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004682
4683 // accumulate left operand's phi information
4684 phiOperands.push_back(rightId);
4685 phiOperands.push_back(builder.getBuildPoint()->getId());
4686
4687 // finish the "if"
4688 ifBuilder.makeEndIf();
4689
4690 // phi together the two results
4691 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4692}
4693
Rex Xu9d93a232016-05-05 12:30:44 +08004694// Return type Id of the imported set of extended instructions corresponds to the name.
4695// Import this set if it has not been imported yet.
4696spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4697{
4698 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4699 return extBuiltinMap[name];
4700 else {
4701 builder.addExtensions(name);
4702 spv::Id extBuiltins = builder.import(name);
4703 extBuiltinMap[name] = extBuiltins;
4704 return extBuiltins;
4705 }
4706}
4707
John Kessenich140f3df2015-06-26 16:58:36 -06004708}; // end anonymous namespace
4709
4710namespace glslang {
4711
John Kessenich68d78fd2015-07-12 19:28:10 -06004712void GetSpirvVersion(std::string& version)
4713{
John Kessenich9e55f632015-07-15 10:03:39 -06004714 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004715 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004716 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004717 version = buf;
4718}
4719
John Kessenich140f3df2015-06-26 16:58:36 -06004720// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004721void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004722{
4723 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004724 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004725 for (int i = 0; i < (int)spirv.size(); ++i) {
4726 unsigned int word = spirv[i];
4727 out.write((const char*)&word, 4);
4728 }
4729 out.close();
4730}
4731
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004732// Write SPIR-V out to a text file with 32-bit hexadecimal words
4733void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4734{
4735 std::ofstream out;
4736 out.open(baseName, std::ios::binary | std::ios::out);
4737 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4738 const int WORDS_PER_LINE = 8;
4739 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4740 out << "\t";
4741 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4742 const unsigned int word = spirv[i + j];
4743 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4744 if (i + j + 1 < (int)spirv.size()) {
4745 out << ",";
4746 }
4747 }
4748 out << std::endl;
4749 }
4750 out.close();
4751}
4752
John Kessenich140f3df2015-06-26 16:58:36 -06004753//
4754// Set up the glslang traversal
4755//
4756void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4757{
Lei Zhang17535f72016-05-04 15:55:59 -04004758 spv::SpvBuildLogger logger;
4759 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004760}
4761
Lei Zhang17535f72016-05-04 15:55:59 -04004762void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004763{
John Kessenich140f3df2015-06-26 16:58:36 -06004764 TIntermNode* root = intermediate.getTreeRoot();
4765
4766 if (root == 0)
4767 return;
4768
4769 glslang::GetThreadPoolAllocator().push();
4770
Lei Zhang17535f72016-05-04 15:55:59 -04004771 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004772
4773 root->traverse(&it);
4774
4775 it.dumpSpv(spirv);
4776
4777 glslang::GetThreadPoolAllocator().pop();
4778}
4779
4780}; // end namespace glslang