blob: 5993e1631c6ca5b285f5fe63d46cef8532875370 [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:
215 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 default:
217 return spv::SourceLanguageUnknown;
218 }
219}
220
221// Translate glslang language (stage) to SPIR-V execution model.
222spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
223{
224 switch (stage) {
225 case EShLangVertex: return spv::ExecutionModelVertex;
226 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
227 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
228 case EShLangGeometry: return spv::ExecutionModelGeometry;
229 case EShLangFragment: return spv::ExecutionModelFragment;
230 case EShLangCompute: return spv::ExecutionModelGLCompute;
231 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700232 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600233 return spv::ExecutionModelFragment;
234 }
235}
236
237// Translate glslang type to SPIR-V storage class.
238spv::StorageClass TranslateStorageClass(const glslang::TType& type)
239{
240 if (type.getQualifier().isPipeInput())
241 return spv::StorageClassInput;
242 else if (type.getQualifier().isPipeOutput())
243 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700244 else if (type.getBasicType() == glslang::EbtSampler)
245 return spv::StorageClassUniformConstant;
246 else if (type.getBasicType() == glslang::EbtAtomicUint)
247 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600248 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700249 if (type.getQualifier().layoutPushConstant)
250 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600251 if (type.getBasicType() == glslang::EbtBlock)
252 return spv::StorageClassUniform;
253 else
254 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600255 // 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 -0600256 } else {
257 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700258 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
259 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
261 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::StorageClassFunction;
265 }
266 }
267}
268
269// Translate glslang sampler type to SPIR-V dimensionality.
270spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
271{
272 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700273 case glslang::Esd1D: return spv::Dim1D;
274 case glslang::Esd2D: return spv::Dim2D;
275 case glslang::Esd3D: return spv::Dim3D;
276 case glslang::EsdCube: return spv::DimCube;
277 case glslang::EsdRect: return spv::DimRect;
278 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700279 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600280 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700281 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600282 return spv::Dim2D;
283 }
284}
285
John Kessenichf6640762016-08-01 19:44:00 -0600286// Translate glslang precision to SPIR-V precision decorations.
287spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600288{
John Kessenichf6640762016-08-01 19:44:00 -0600289 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700290 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600291 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 default:
293 return spv::NoPrecision;
294 }
295}
296
John Kessenichf6640762016-08-01 19:44:00 -0600297// Translate glslang type to SPIR-V precision decorations.
298spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
299{
300 return TranslatePrecisionDecoration(type.getQualifier().precision);
301}
302
John Kessenich140f3df2015-06-26 16:58:36 -0600303// Translate glslang type to SPIR-V block decorations.
304spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
305{
306 if (type.getBasicType() == glslang::EbtBlock) {
307 switch (type.getQualifier().storage) {
308 case glslang::EvqUniform: return spv::DecorationBlock;
309 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
310 case glslang::EvqVaryingIn: return spv::DecorationBlock;
311 case glslang::EvqVaryingOut: return spv::DecorationBlock;
312 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700313 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600314 break;
315 }
316 }
317
John Kessenich4016e382016-07-15 11:53:56 -0600318 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600319}
320
Rex Xu1da878f2016-02-21 20:59:01 +0800321// Translate glslang type to SPIR-V memory decorations.
322void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
323{
324 if (qualifier.coherent)
325 memory.push_back(spv::DecorationCoherent);
326 if (qualifier.volatil)
327 memory.push_back(spv::DecorationVolatile);
328 if (qualifier.restrict)
329 memory.push_back(spv::DecorationRestrict);
330 if (qualifier.readonly)
331 memory.push_back(spv::DecorationNonWritable);
332 if (qualifier.writeonly)
333 memory.push_back(spv::DecorationNonReadable);
334}
335
John Kessenich140f3df2015-06-26 16:58:36 -0600336// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700337spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600338{
339 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700340 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600341 case glslang::ElmRowMajor:
342 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700343 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700345 default:
346 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600347 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600348 }
349 } else {
350 switch (type.getBasicType()) {
351 default:
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 break;
354 case glslang::EbtBlock:
355 switch (type.getQualifier().storage) {
356 case glslang::EvqUniform:
357 case glslang::EvqBuffer:
358 switch (type.getQualifier().layoutPacking) {
359 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 }
364 case glslang::EvqVaryingIn:
365 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700366 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600367 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600368 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700369 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600370 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600371 }
372 }
373 }
374}
375
376// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600377// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700378// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800379spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600380{
Rex Xubbceed72016-05-21 09:40:44 +0800381 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700382 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800384 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700385 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700386 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800388#ifdef AMD_EXTENSIONS
389 else if (qualifier.explicitInterp)
390 return spv::DecorationExplicitInterpAMD;
391#endif
Rex Xubbceed72016-05-21 09:40:44 +0800392 else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394}
395
396// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600397// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800398// should be applied.
399spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
400{
401 if (qualifier.patch)
402 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700403 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600404 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700405 else if (qualifier.sample) {
406 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600407 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700408 } else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410}
411
John Kessenich92187592016-02-01 13:45:25 -0700412// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700413spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600414{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationInvariant;
417 else
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600419}
420
qining9220dbb2016-05-04 17:34:38 -0400421// If glslang type is noContraction, return SPIR-V NoContraction decoration.
422spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
423{
424 if (qualifier.noContraction)
425 return spv::DecorationNoContraction;
426 else
John Kessenich4016e382016-07-15 11:53:56 -0600427 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400428}
429
David Netoa901ffe2016-06-08 14:11:40 +0100430// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
431// associated capabilities when required. For some built-in variables, a capability
432// is generated only when using the variable in an executable instruction, but not when
433// just declaring a struct member variable with it. This is true for PointSize,
434// ClipDistance, and CullDistance.
435spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600436{
437 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700438 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600439 // Defer adding the capability until the built-in is actually used.
440 if (! memberDeclaration) {
441 switch (glslangIntermediate->getStage()) {
442 case EShLangGeometry:
443 builder.addCapability(spv::CapabilityGeometryPointSize);
444 break;
445 case EShLangTessControl:
446 case EShLangTessEvaluation:
447 builder.addCapability(spv::CapabilityTessellationPointSize);
448 break;
449 default:
450 break;
451 }
John Kessenich92187592016-02-01 13:45:25 -0700452 }
453 return spv::BuiltInPointSize;
454
John Kessenichebb50532016-05-16 19:22:05 -0600455 // These *Distance capabilities logically belong here, but if the member is declared and
456 // then never used, consumers of SPIR-V prefer the capability not be declared.
457 // They are now generated when used, rather than here when declared.
458 // Potentially, the specification should be more clear what the minimum
459 // use needed is to trigger the capability.
460 //
John Kessenich92187592016-02-01 13:45:25 -0700461 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100462 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600463 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700464 return spv::BuiltInClipDistance;
465
466 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100467 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600468 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700469 return spv::BuiltInCullDistance;
470
471 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500472 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700473 return spv::BuiltInViewportIndex;
474
John Kessenich5e801132016-02-15 11:09:46 -0700475 case glslang::EbvSampleId:
476 builder.addCapability(spv::CapabilitySampleRateShading);
477 return spv::BuiltInSampleId;
478
479 case glslang::EbvSamplePosition:
480 builder.addCapability(spv::CapabilitySampleRateShading);
481 return spv::BuiltInSamplePosition;
482
483 case glslang::EbvSampleMask:
484 builder.addCapability(spv::CapabilitySampleRateShading);
485 return spv::BuiltInSampleMask;
486
John Kessenich78a45572016-07-08 14:05:15 -0600487 case glslang::EbvLayer:
488 builder.addCapability(spv::CapabilityGeometry);
489 return spv::BuiltInLayer;
490
John Kessenich140f3df2015-06-26 16:58:36 -0600491 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600492 case glslang::EbvVertexId: return spv::BuiltInVertexId;
493 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700494 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
495 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600496 case glslang::EbvBaseVertex:
497 case glslang::EbvBaseInstance:
498 case glslang::EbvDrawId:
499 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600500 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600501 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600502 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
503 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600504 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
505 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
506 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
507 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
508 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
509 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
510 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600511 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
512 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
513 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
514 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
515 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
516 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
517 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
518 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800519 case glslang::EbvSubGroupSize:
520 case glslang::EbvSubGroupInvocation:
521 case glslang::EbvSubGroupEqMask:
522 case glslang::EbvSubGroupGeMask:
523 case glslang::EbvSubGroupGtMask:
524 case glslang::EbvSubGroupLeMask:
525 case glslang::EbvSubGroupLtMask:
526 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600527 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600528 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800529#ifdef AMD_EXTENSIONS
530 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
531 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
532 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
533 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
534 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
535 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
536 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
537#endif
John Kessenich4016e382016-07-15 11:53:56 -0600538 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600539 }
540}
541
Rex Xufc618912015-09-09 16:42:49 +0800542// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700543spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800544{
545 assert(type.getBasicType() == glslang::EbtSampler);
546
John Kessenich5d0fa972016-02-15 11:57:00 -0700547 // Check for capabilities
548 switch (type.getQualifier().layoutFormat) {
549 case glslang::ElfRg32f:
550 case glslang::ElfRg16f:
551 case glslang::ElfR11fG11fB10f:
552 case glslang::ElfR16f:
553 case glslang::ElfRgba16:
554 case glslang::ElfRgb10A2:
555 case glslang::ElfRg16:
556 case glslang::ElfRg8:
557 case glslang::ElfR16:
558 case glslang::ElfR8:
559 case glslang::ElfRgba16Snorm:
560 case glslang::ElfRg16Snorm:
561 case glslang::ElfRg8Snorm:
562 case glslang::ElfR16Snorm:
563 case glslang::ElfR8Snorm:
564
565 case glslang::ElfRg32i:
566 case glslang::ElfRg16i:
567 case glslang::ElfRg8i:
568 case glslang::ElfR16i:
569 case glslang::ElfR8i:
570
571 case glslang::ElfRgb10a2ui:
572 case glslang::ElfRg32ui:
573 case glslang::ElfRg16ui:
574 case glslang::ElfRg8ui:
575 case glslang::ElfR16ui:
576 case glslang::ElfR8ui:
577 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
578 break;
579
580 default:
581 break;
582 }
583
584 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800585 switch (type.getQualifier().layoutFormat) {
586 case glslang::ElfNone: return spv::ImageFormatUnknown;
587 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
588 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
589 case glslang::ElfR32f: return spv::ImageFormatR32f;
590 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
591 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
592 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
593 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
594 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
595 case glslang::ElfR16f: return spv::ImageFormatR16f;
596 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
597 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
598 case glslang::ElfRg16: return spv::ImageFormatRg16;
599 case glslang::ElfRg8: return spv::ImageFormatRg8;
600 case glslang::ElfR16: return spv::ImageFormatR16;
601 case glslang::ElfR8: return spv::ImageFormatR8;
602 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
603 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
604 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
605 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
606 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
607 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
608 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
609 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
610 case glslang::ElfR32i: return spv::ImageFormatR32i;
611 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
612 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
613 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
614 case glslang::ElfR16i: return spv::ImageFormatR16i;
615 case glslang::ElfR8i: return spv::ImageFormatR8i;
616 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
617 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
618 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
619 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
620 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
621 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
622 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
623 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
624 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
625 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600626 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800627 }
628}
629
qining25262b32016-05-06 17:25:16 -0400630// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700631// descriptor set.
632bool IsDescriptorResource(const glslang::TType& type)
633{
John Kessenichf7497e22016-03-08 21:36:22 -0700634 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700635 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700636 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700637
638 // non block...
639 // basically samplerXXX/subpass/sampler/texture are all included
640 // if they are the global-scope-class, not the function parameter
641 // (or local, if they ever exist) class.
642 if (type.getBasicType() == glslang::EbtSampler)
643 return type.getQualifier().isUniformOrBuffer();
644
645 // None of the above.
646 return false;
647}
648
John Kesseniche0b6cad2015-12-24 10:30:13 -0700649void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
650{
651 if (child.layoutMatrix == glslang::ElmNone)
652 child.layoutMatrix = parent.layoutMatrix;
653
654 if (parent.invariant)
655 child.invariant = true;
656 if (parent.nopersp)
657 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800658#ifdef AMD_EXTENSIONS
659 if (parent.explicitInterp)
660 child.explicitInterp = true;
661#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700662 if (parent.flat)
663 child.flat = true;
664 if (parent.centroid)
665 child.centroid = true;
666 if (parent.patch)
667 child.patch = true;
668 if (parent.sample)
669 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800670 if (parent.coherent)
671 child.coherent = true;
672 if (parent.volatil)
673 child.volatil = true;
674 if (parent.restrict)
675 child.restrict = true;
676 if (parent.readonly)
677 child.readonly = true;
678 if (parent.writeonly)
679 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700680}
681
682bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
683{
John Kessenich7b9fa252016-01-21 18:56:57 -0700684 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700685 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600686 // - 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 -0700687 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600688 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700689}
690
John Kessenich140f3df2015-06-26 16:58:36 -0600691//
692// Implement the TGlslangToSpvTraverser class.
693//
694
Lei Zhang17535f72016-05-04 15:55:59 -0400695TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
696 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
697 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600698 inMain(false), mainTerminated(false), linkageOnly(false),
699 glslangIntermediate(glslangIntermediate)
700{
701 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
702
703 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700704 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600705 stdBuiltins = builder.import("GLSL.std.450");
706 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700707 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
708 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600709
710 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600711 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
712 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600713 builder.addSourceExtension(it->c_str());
714
715 // Add the top-level modes for this shader.
716
John Kessenich92187592016-02-01 13:45:25 -0700717 if (glslangIntermediate->getXfbMode()) {
718 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600719 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700720 }
John Kessenich140f3df2015-06-26 16:58:36 -0600721
722 unsigned int mode;
723 switch (glslangIntermediate->getStage()) {
724 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600725 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600726 break;
727
728 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600729 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600730 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
731 break;
732
733 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600734 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600735 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700736 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
737 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
738 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600739 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600740 }
John Kessenich4016e382016-07-15 11:53:56 -0600741 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600742 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
743
John Kesseniche6903322015-10-13 16:29:02 -0600744 switch (glslangIntermediate->getVertexSpacing()) {
745 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
746 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
747 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600748 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600749 }
John Kessenich4016e382016-07-15 11:53:56 -0600750 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600751 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
752
753 switch (glslangIntermediate->getVertexOrder()) {
754 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
755 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600756 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600757 }
John Kessenich4016e382016-07-15 11:53:56 -0600758 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600759 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
760
761 if (glslangIntermediate->getPointMode())
762 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600763 break;
764
765 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600766 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600767 switch (glslangIntermediate->getInputPrimitive()) {
768 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
769 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
770 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700771 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600772 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600773 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600774 }
John Kessenich4016e382016-07-15 11:53:56 -0600775 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600776 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600777
John Kessenich140f3df2015-06-26 16:58:36 -0600778 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
779
780 switch (glslangIntermediate->getOutputPrimitive()) {
781 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
782 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
783 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600784 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600785 }
John Kessenich4016e382016-07-15 11:53:56 -0600786 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600787 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
788 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
789 break;
790
791 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600792 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600793 if (glslangIntermediate->getPixelCenterInteger())
794 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600795
John Kessenich140f3df2015-06-26 16:58:36 -0600796 if (glslangIntermediate->getOriginUpperLeft())
797 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600798 else
799 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600800
801 if (glslangIntermediate->getEarlyFragmentTests())
802 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
803
804 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600805 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
806 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600807 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600808 }
John Kessenich4016e382016-07-15 11:53:56 -0600809 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600810 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
811
812 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
813 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600814 break;
815
816 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600817 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600818 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
819 glslangIntermediate->getLocalSize(1),
820 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600821 break;
822
823 default:
824 break;
825 }
826
827}
828
John Kessenich7ba63412015-12-20 17:37:07 -0700829// Finish everything and dump
830void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
831{
832 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100833 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
834 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700835
qiningda397332016-03-09 19:54:03 -0500836 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700837 builder.dump(out);
838}
839
John Kessenich140f3df2015-06-26 16:58:36 -0600840TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
841{
842 if (! mainTerminated) {
843 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
844 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600845 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600846 }
847}
848
849//
850// Implement the traversal functions.
851//
852// Return true from interior nodes to have the external traversal
853// continue on to children. Return false if children were
854// already processed.
855//
856
857//
qining25262b32016-05-06 17:25:16 -0400858// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600859// - uniform/input reads
860// - output writes
861// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
862// - something simple that degenerates into the last bullet
863//
864void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
865{
qining75d1d802016-04-06 14:42:01 -0400866 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
867 if (symbol->getType().getQualifier().isSpecConstant())
868 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
869
John Kessenich140f3df2015-06-26 16:58:36 -0600870 // getSymbolId() will set up all the IO decorations on the first call.
871 // Formal function parameters were mapped during makeFunctions().
872 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700873
874 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
875 if (builder.isPointer(id)) {
876 spv::StorageClass sc = builder.getStorageClass(id);
877 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
878 iOSet.insert(id);
879 }
880
881 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700882 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600883 // Prepare to generate code for the access
884
885 // L-value chains will be computed left to right. We're on the symbol now,
886 // which is the left-most part of the access chain, so now is "clear" time,
887 // followed by setting the base.
888 builder.clearAccessChain();
889
890 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700891 // except for
892 // A) "const in" arguments to a function, which are an intermediate object.
893 // See comments in handleUserFunctionCall().
894 // B) Specialization constants (normal constant don't even come in as a variable),
895 // These are also pure R-values.
896 glslang::TQualifier qualifier = symbol->getQualifier();
897 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
898 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600899 builder.setAccessChainRValue(id);
900 else
901 builder.setAccessChainLValue(id);
902 }
903}
904
905bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
906{
qining40887662016-04-03 22:20:42 -0400907 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
908 if (node->getType().getQualifier().isSpecConstant())
909 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
910
John Kessenich140f3df2015-06-26 16:58:36 -0600911 // First, handle special cases
912 switch (node->getOp()) {
913 case glslang::EOpAssign:
914 case glslang::EOpAddAssign:
915 case glslang::EOpSubAssign:
916 case glslang::EOpMulAssign:
917 case glslang::EOpVectorTimesMatrixAssign:
918 case glslang::EOpVectorTimesScalarAssign:
919 case glslang::EOpMatrixTimesScalarAssign:
920 case glslang::EOpMatrixTimesMatrixAssign:
921 case glslang::EOpDivAssign:
922 case glslang::EOpModAssign:
923 case glslang::EOpAndAssign:
924 case glslang::EOpInclusiveOrAssign:
925 case glslang::EOpExclusiveOrAssign:
926 case glslang::EOpLeftShiftAssign:
927 case glslang::EOpRightShiftAssign:
928 // A bin-op assign "a += b" means the same thing as "a = a + b"
929 // where a is evaluated before b. For a simple assignment, GLSL
930 // says to evaluate the left before the right. So, always, left
931 // node then right node.
932 {
933 // get the left l-value, save it away
934 builder.clearAccessChain();
935 node->getLeft()->traverse(this);
936 spv::Builder::AccessChain lValue = builder.getAccessChain();
937
938 // evaluate the right
939 builder.clearAccessChain();
940 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700941 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600942
943 if (node->getOp() != glslang::EOpAssign) {
944 // the left is also an r-value
945 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700946 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600947
948 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600949 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400950 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600951 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
952 node->getType().getBasicType());
953
954 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700955 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600956 }
957
958 // store the result
959 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800960 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600961
962 // assignments are expressions having an rValue after they are evaluated...
963 builder.clearAccessChain();
964 builder.setAccessChainRValue(rValue);
965 }
966 return false;
967 case glslang::EOpIndexDirect:
968 case glslang::EOpIndexDirectStruct:
969 {
970 // Get the left part of the access chain.
971 node->getLeft()->traverse(this);
972
973 // Add the next element in the chain
974
David Netoa901ffe2016-06-08 14:11:40 +0100975 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600976 if (! node->getLeft()->getType().isArray() &&
977 node->getLeft()->getType().isVector() &&
978 node->getOp() == glslang::EOpIndexDirect) {
979 // This is essentially a hard-coded vector swizzle of size 1,
980 // so short circuit the access-chain stuff with a swizzle.
981 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100982 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600983 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600984 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100985 int spvIndex = glslangIndex;
986 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
987 node->getOp() == glslang::EOpIndexDirectStruct)
988 {
989 // This may be, e.g., an anonymous block-member selection, which generally need
990 // index remapping due to hidden members in anonymous blocks.
991 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
992 assert(remapper.size() > 0);
993 spvIndex = remapper[glslangIndex];
994 }
John Kessenichebb50532016-05-16 19:22:05 -0600995
David Netoa901ffe2016-06-08 14:11:40 +0100996 // normal case for indexing array or structure or block
997 builder.accessChainPush(builder.makeIntConstant(spvIndex));
998
999 // Add capabilities here for accessing PointSize and clip/cull distance.
1000 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001001 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001002 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001003 }
1004 }
1005 return false;
1006 case glslang::EOpIndexIndirect:
1007 {
1008 // Structure or array or vector indirection.
1009 // Will use native SPIR-V access-chain for struct and array indirection;
1010 // matrices are arrays of vectors, so will also work for a matrix.
1011 // Will use the access chain's 'component' for variable index into a vector.
1012
1013 // This adapter is building access chains left to right.
1014 // Set up the access chain to the left.
1015 node->getLeft()->traverse(this);
1016
1017 // save it so that computing the right side doesn't trash it
1018 spv::Builder::AccessChain partial = builder.getAccessChain();
1019
1020 // compute the next index in the chain
1021 builder.clearAccessChain();
1022 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001023 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001024
1025 // restore the saved access chain
1026 builder.setAccessChain(partial);
1027
1028 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001029 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001030 else
John Kessenichfa668da2015-09-13 14:46:30 -06001031 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001032 }
1033 return false;
1034 case glslang::EOpVectorSwizzle:
1035 {
1036 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001037 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001038 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001039 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001040 }
1041 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001042 case glslang::EOpLogicalOr:
1043 case glslang::EOpLogicalAnd:
1044 {
1045
1046 // These may require short circuiting, but can sometimes be done as straight
1047 // binary operations. The right operand must be short circuited if it has
1048 // side effects, and should probably be if it is complex.
1049 if (isTrivial(node->getRight()->getAsTyped()))
1050 break; // handle below as a normal binary operation
1051 // otherwise, we need to do dynamic short circuiting on the right operand
1052 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1053 builder.clearAccessChain();
1054 builder.setAccessChainRValue(result);
1055 }
1056 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001057 default:
1058 break;
1059 }
1060
1061 // Assume generic binary op...
1062
John Kessenich32cfd492016-02-02 12:37:46 -07001063 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.clearAccessChain();
1065 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001066 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001067
John Kessenich32cfd492016-02-02 12:37:46 -07001068 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001069 builder.clearAccessChain();
1070 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001071 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001072
John Kessenich32cfd492016-02-02 12:37:46 -07001073 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001074 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001075 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001076 convertGlslangToSpvType(node->getType()), left, right,
1077 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001078
John Kessenich50e57562015-12-21 21:21:11 -07001079 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001080 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001081 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001082 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001083 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001084 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001085 return false;
1086 }
John Kessenich140f3df2015-06-26 16:58:36 -06001087}
1088
1089bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1090{
qining40887662016-04-03 22:20:42 -04001091 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1092 if (node->getType().getQualifier().isSpecConstant())
1093 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1094
John Kessenichfc51d282015-08-19 13:34:18 -06001095 spv::Id result = spv::NoResult;
1096
1097 // try texturing first
1098 result = createImageTextureFunctionCall(node);
1099 if (result != spv::NoResult) {
1100 builder.clearAccessChain();
1101 builder.setAccessChainRValue(result);
1102
1103 return false; // done with this node
1104 }
1105
1106 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001107
1108 if (node->getOp() == glslang::EOpArrayLength) {
1109 // Quite special; won't want to evaluate the operand.
1110
1111 // Normal .length() would have been constant folded by the front-end.
1112 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001113 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001114 assert(node->getOperand()->getType().isRuntimeSizedArray());
1115 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1116 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001117 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1118 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001119
1120 builder.clearAccessChain();
1121 builder.setAccessChainRValue(length);
1122
1123 return false;
1124 }
1125
John Kessenichfc51d282015-08-19 13:34:18 -06001126 // Start by evaluating the operand
1127
John Kessenich8c8505c2016-07-26 12:50:38 -06001128 // Does it need a swizzle inversion? If so, evaluation is inverted;
1129 // operate first on the swizzle base, then apply the swizzle.
1130 spv::Id invertedType = spv::NoType;
1131 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1132 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1133 invertedType = getInvertedSwizzleType(*node->getOperand());
1134
John Kessenich140f3df2015-06-26 16:58:36 -06001135 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001136 if (invertedType != spv::NoType)
1137 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1138 else
1139 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001140
Rex Xufc618912015-09-09 16:42:49 +08001141 spv::Id operand = spv::NoResult;
1142
1143 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1144 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001145 node->getOp() == glslang::EOpAtomicCounter ||
1146 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001147 operand = builder.accessChainGetLValue(); // Special case l-value operands
1148 else
John Kessenich32cfd492016-02-02 12:37:46 -07001149 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001150
John Kessenichf6640762016-08-01 19:44:00 -06001151 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001152 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001153
1154 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001155 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001156 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001157
1158 // if not, then possibly an operation
1159 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001160 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001161
1162 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001163 if (invertedType)
1164 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1165
John Kessenich140f3df2015-06-26 16:58:36 -06001166 builder.clearAccessChain();
1167 builder.setAccessChainRValue(result);
1168
1169 return false; // done with this node
1170 }
1171
1172 // it must be a special case, check...
1173 switch (node->getOp()) {
1174 case glslang::EOpPostIncrement:
1175 case glslang::EOpPostDecrement:
1176 case glslang::EOpPreIncrement:
1177 case glslang::EOpPreDecrement:
1178 {
1179 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001180 spv::Id one = 0;
1181 if (node->getBasicType() == glslang::EbtFloat)
1182 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001183 else if (node->getBasicType() == glslang::EbtDouble)
1184 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001185 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1186 one = builder.makeInt64Constant(1);
1187 else
1188 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001189 glslang::TOperator op;
1190 if (node->getOp() == glslang::EOpPreIncrement ||
1191 node->getOp() == glslang::EOpPostIncrement)
1192 op = glslang::EOpAdd;
1193 else
1194 op = glslang::EOpSub;
1195
John Kessenichf6640762016-08-01 19:44:00 -06001196 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001197 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001198 convertGlslangToSpvType(node->getType()), operand, one,
1199 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001200 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001201
1202 // The result of operation is always stored, but conditionally the
1203 // consumed result. The consumed result is always an r-value.
1204 builder.accessChainStore(result);
1205 builder.clearAccessChain();
1206 if (node->getOp() == glslang::EOpPreIncrement ||
1207 node->getOp() == glslang::EOpPreDecrement)
1208 builder.setAccessChainRValue(result);
1209 else
1210 builder.setAccessChainRValue(operand);
1211 }
1212
1213 return false;
1214
1215 case glslang::EOpEmitStreamVertex:
1216 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1217 return false;
1218 case glslang::EOpEndStreamPrimitive:
1219 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1220 return false;
1221
1222 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001223 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001224 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001225 }
John Kessenich140f3df2015-06-26 16:58:36 -06001226}
1227
1228bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1229{
qining27e04a02016-04-14 16:40:20 -04001230 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1231 if (node->getType().getQualifier().isSpecConstant())
1232 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1233
John Kessenichfc51d282015-08-19 13:34:18 -06001234 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001235 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1236 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001237
1238 // try texturing
1239 result = createImageTextureFunctionCall(node);
1240 if (result != spv::NoResult) {
1241 builder.clearAccessChain();
1242 builder.setAccessChainRValue(result);
1243
1244 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001245 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001246 // "imageStore" is a special case, which has no result
1247 return false;
1248 }
John Kessenichfc51d282015-08-19 13:34:18 -06001249
John Kessenich140f3df2015-06-26 16:58:36 -06001250 glslang::TOperator binOp = glslang::EOpNull;
1251 bool reduceComparison = true;
1252 bool isMatrix = false;
1253 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001254 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001255
1256 assert(node->getOp());
1257
John Kessenichf6640762016-08-01 19:44:00 -06001258 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001259
1260 switch (node->getOp()) {
1261 case glslang::EOpSequence:
1262 {
1263 if (preVisit)
1264 ++sequenceDepth;
1265 else
1266 --sequenceDepth;
1267
1268 if (sequenceDepth == 1) {
1269 // If this is the parent node of all the functions, we want to see them
1270 // early, so all call points have actual SPIR-V functions to reference.
1271 // In all cases, still let the traverser visit the children for us.
1272 makeFunctions(node->getAsAggregate()->getSequence());
1273
1274 // Also, we want all globals initializers to go into the entry of main(), before
1275 // anything else gets there, so visit out of order, doing them all now.
1276 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1277
1278 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1279 // so do them manually.
1280 visitFunctions(node->getAsAggregate()->getSequence());
1281
1282 return false;
1283 }
1284
1285 return true;
1286 }
1287 case glslang::EOpLinkerObjects:
1288 {
1289 if (visit == glslang::EvPreVisit)
1290 linkageOnly = true;
1291 else
1292 linkageOnly = false;
1293
1294 return true;
1295 }
1296 case glslang::EOpComma:
1297 {
1298 // processing from left to right naturally leaves the right-most
1299 // lying around in the access chain
1300 glslang::TIntermSequence& glslangOperands = node->getSequence();
1301 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1302 glslangOperands[i]->traverse(this);
1303
1304 return false;
1305 }
1306 case glslang::EOpFunction:
1307 if (visit == glslang::EvPreVisit) {
1308 if (isShaderEntrypoint(node)) {
1309 inMain = true;
1310 builder.setBuildPoint(shaderEntry->getLastBlock());
1311 } else {
1312 handleFunctionEntry(node);
1313 }
1314 } else {
1315 if (inMain)
1316 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001317 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001318 inMain = false;
1319 }
1320
1321 return true;
1322 case glslang::EOpParameters:
1323 // Parameters will have been consumed by EOpFunction processing, but not
1324 // the body, so we still visited the function node's children, making this
1325 // child redundant.
1326 return false;
1327 case glslang::EOpFunctionCall:
1328 {
1329 if (node->isUserDefined())
1330 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001331 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1332 if (result) {
1333 builder.clearAccessChain();
1334 builder.setAccessChainRValue(result);
1335 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001336 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 return false;
1339 }
1340 case glslang::EOpConstructMat2x2:
1341 case glslang::EOpConstructMat2x3:
1342 case glslang::EOpConstructMat2x4:
1343 case glslang::EOpConstructMat3x2:
1344 case glslang::EOpConstructMat3x3:
1345 case glslang::EOpConstructMat3x4:
1346 case glslang::EOpConstructMat4x2:
1347 case glslang::EOpConstructMat4x3:
1348 case glslang::EOpConstructMat4x4:
1349 case glslang::EOpConstructDMat2x2:
1350 case glslang::EOpConstructDMat2x3:
1351 case glslang::EOpConstructDMat2x4:
1352 case glslang::EOpConstructDMat3x2:
1353 case glslang::EOpConstructDMat3x3:
1354 case glslang::EOpConstructDMat3x4:
1355 case glslang::EOpConstructDMat4x2:
1356 case glslang::EOpConstructDMat4x3:
1357 case glslang::EOpConstructDMat4x4:
1358 isMatrix = true;
1359 // fall through
1360 case glslang::EOpConstructFloat:
1361 case glslang::EOpConstructVec2:
1362 case glslang::EOpConstructVec3:
1363 case glslang::EOpConstructVec4:
1364 case glslang::EOpConstructDouble:
1365 case glslang::EOpConstructDVec2:
1366 case glslang::EOpConstructDVec3:
1367 case glslang::EOpConstructDVec4:
1368 case glslang::EOpConstructBool:
1369 case glslang::EOpConstructBVec2:
1370 case glslang::EOpConstructBVec3:
1371 case glslang::EOpConstructBVec4:
1372 case glslang::EOpConstructInt:
1373 case glslang::EOpConstructIVec2:
1374 case glslang::EOpConstructIVec3:
1375 case glslang::EOpConstructIVec4:
1376 case glslang::EOpConstructUint:
1377 case glslang::EOpConstructUVec2:
1378 case glslang::EOpConstructUVec3:
1379 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001380 case glslang::EOpConstructInt64:
1381 case glslang::EOpConstructI64Vec2:
1382 case glslang::EOpConstructI64Vec3:
1383 case glslang::EOpConstructI64Vec4:
1384 case glslang::EOpConstructUint64:
1385 case glslang::EOpConstructU64Vec2:
1386 case glslang::EOpConstructU64Vec3:
1387 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001388 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001389 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001390 {
1391 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001392 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001393 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001394 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001395 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001396 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001397 std::vector<spv::Id> constituents;
1398 for (int c = 0; c < (int)arguments.size(); ++c)
1399 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001400 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001401 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001402 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001403 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001404 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001405
1406 builder.clearAccessChain();
1407 builder.setAccessChainRValue(constructed);
1408
1409 return false;
1410 }
1411
1412 // These six are component-wise compares with component-wise results.
1413 // Forward on to createBinaryOperation(), requesting a vector result.
1414 case glslang::EOpLessThan:
1415 case glslang::EOpGreaterThan:
1416 case glslang::EOpLessThanEqual:
1417 case glslang::EOpGreaterThanEqual:
1418 case glslang::EOpVectorEqual:
1419 case glslang::EOpVectorNotEqual:
1420 {
1421 // Map the operation to a binary
1422 binOp = node->getOp();
1423 reduceComparison = false;
1424 switch (node->getOp()) {
1425 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1426 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1427 default: binOp = node->getOp(); break;
1428 }
1429
1430 break;
1431 }
1432 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001433 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001434 binOp = glslang::EOpMul;
1435 break;
1436 case glslang::EOpOuterProduct:
1437 // two vectors multiplied to make a matrix
1438 binOp = glslang::EOpOuterProduct;
1439 break;
1440 case glslang::EOpDot:
1441 {
qining25262b32016-05-06 17:25:16 -04001442 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001443 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001444 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001445 binOp = glslang::EOpMul;
1446 break;
1447 }
1448 case glslang::EOpMod:
1449 // when an aggregate, this is the floating-point mod built-in function,
1450 // which can be emitted by the one in createBinaryOperation()
1451 binOp = glslang::EOpMod;
1452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001453 case glslang::EOpEmitVertex:
1454 case glslang::EOpEndPrimitive:
1455 case glslang::EOpBarrier:
1456 case glslang::EOpMemoryBarrier:
1457 case glslang::EOpMemoryBarrierAtomicCounter:
1458 case glslang::EOpMemoryBarrierBuffer:
1459 case glslang::EOpMemoryBarrierImage:
1460 case glslang::EOpMemoryBarrierShared:
1461 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001462 case glslang::EOpAllMemoryBarrierWithGroupSync:
1463 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1464 case glslang::EOpWorkgroupMemoryBarrier:
1465 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001466 noReturnValue = true;
1467 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1468 break;
1469
John Kessenich426394d2015-07-23 10:22:48 -06001470 case glslang::EOpAtomicAdd:
1471 case glslang::EOpAtomicMin:
1472 case glslang::EOpAtomicMax:
1473 case glslang::EOpAtomicAnd:
1474 case glslang::EOpAtomicOr:
1475 case glslang::EOpAtomicXor:
1476 case glslang::EOpAtomicExchange:
1477 case glslang::EOpAtomicCompSwap:
1478 atomic = true;
1479 break;
1480
John Kessenich140f3df2015-06-26 16:58:36 -06001481 default:
1482 break;
1483 }
1484
1485 //
1486 // See if it maps to a regular operation.
1487 //
John Kessenich140f3df2015-06-26 16:58:36 -06001488 if (binOp != glslang::EOpNull) {
1489 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1490 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1491 assert(left && right);
1492
1493 builder.clearAccessChain();
1494 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001495 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001496
1497 builder.clearAccessChain();
1498 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001499 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001500
qining25262b32016-05-06 17:25:16 -04001501 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001502 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001503 left->getType().getBasicType(), reduceComparison);
1504
1505 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001506 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001507 builder.clearAccessChain();
1508 builder.setAccessChainRValue(result);
1509
1510 return false;
1511 }
1512
John Kessenich426394d2015-07-23 10:22:48 -06001513 //
1514 // Create the list of operands.
1515 //
John Kessenich140f3df2015-06-26 16:58:36 -06001516 glslang::TIntermSequence& glslangOperands = node->getSequence();
1517 std::vector<spv::Id> operands;
1518 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001519 // special case l-value operands; there are just a few
1520 bool lvalue = false;
1521 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001522 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001523 case glslang::EOpModf:
1524 if (arg == 1)
1525 lvalue = true;
1526 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001527 case glslang::EOpInterpolateAtSample:
1528 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001529#ifdef AMD_EXTENSIONS
1530 case glslang::EOpInterpolateAtVertex:
1531#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001532 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001533 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001534
1535 // Does it need a swizzle inversion? If so, evaluation is inverted;
1536 // operate first on the swizzle base, then apply the swizzle.
1537 if (glslangOperands[0]->getAsOperator() &&
1538 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1539 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1540 }
Rex Xu7a26c172015-12-08 17:12:09 +08001541 break;
Rex Xud4782c12015-09-06 16:30:11 +08001542 case glslang::EOpAtomicAdd:
1543 case glslang::EOpAtomicMin:
1544 case glslang::EOpAtomicMax:
1545 case glslang::EOpAtomicAnd:
1546 case glslang::EOpAtomicOr:
1547 case glslang::EOpAtomicXor:
1548 case glslang::EOpAtomicExchange:
1549 case glslang::EOpAtomicCompSwap:
1550 if (arg == 0)
1551 lvalue = true;
1552 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001553 case glslang::EOpAddCarry:
1554 case glslang::EOpSubBorrow:
1555 if (arg == 2)
1556 lvalue = true;
1557 break;
1558 case glslang::EOpUMulExtended:
1559 case glslang::EOpIMulExtended:
1560 if (arg >= 2)
1561 lvalue = true;
1562 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001563 default:
1564 break;
1565 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001566 builder.clearAccessChain();
1567 if (invertedType != spv::NoType && arg == 0)
1568 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1569 else
1570 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001571 if (lvalue)
1572 operands.push_back(builder.accessChainGetLValue());
1573 else
John Kessenich32cfd492016-02-02 12:37:46 -07001574 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001575 }
John Kessenich426394d2015-07-23 10:22:48 -06001576
1577 if (atomic) {
1578 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001579 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001580 } else {
1581 // Pass through to generic operations.
1582 switch (glslangOperands.size()) {
1583 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001584 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001585 break;
1586 case 1:
qining25262b32016-05-06 17:25:16 -04001587 result = createUnaryOperation(
1588 node->getOp(), precision,
1589 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001590 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001591 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001592 break;
1593 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001594 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001595 break;
1596 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001597 if (invertedType)
1598 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001599 }
1600
1601 if (noReturnValue)
1602 return false;
1603
1604 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001605 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001606 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001607 } else {
1608 builder.clearAccessChain();
1609 builder.setAccessChainRValue(result);
1610 return false;
1611 }
1612}
1613
1614bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1615{
1616 // This path handles both if-then-else and ?:
1617 // The if-then-else has a node type of void, while
1618 // ?: has a non-void node type
1619 spv::Id result = 0;
1620 if (node->getBasicType() != glslang::EbtVoid) {
1621 // don't handle this as just on-the-fly temporaries, because there will be two names
1622 // and better to leave SSA to later passes
1623 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1624 }
1625
1626 // emit the condition before doing anything with selection
1627 node->getCondition()->traverse(this);
1628
1629 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001630 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001631
1632 if (node->getTrueBlock()) {
1633 // emit the "then" statement
1634 node->getTrueBlock()->traverse(this);
1635 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001636 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001637 }
1638
1639 if (node->getFalseBlock()) {
1640 ifBuilder.makeBeginElse();
1641 // emit the "else" statement
1642 node->getFalseBlock()->traverse(this);
1643 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001644 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001645 }
1646
1647 ifBuilder.makeEndIf();
1648
1649 if (result) {
1650 // GLSL only has r-values as the result of a :?, but
1651 // if we have an l-value, that can be more efficient if it will
1652 // become the base of a complex r-value expression, because the
1653 // next layer copies r-values into memory to use the access-chain mechanism
1654 builder.clearAccessChain();
1655 builder.setAccessChainLValue(result);
1656 }
1657
1658 return false;
1659}
1660
1661bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1662{
1663 // emit and get the condition before doing anything with switch
1664 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001665 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001666
1667 // browse the children to sort out code segments
1668 int defaultSegment = -1;
1669 std::vector<TIntermNode*> codeSegments;
1670 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1671 std::vector<int> caseValues;
1672 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1673 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1674 TIntermNode* child = *c;
1675 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001676 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001677 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001678 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001679 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1680 } else
1681 codeSegments.push_back(child);
1682 }
1683
qining25262b32016-05-06 17:25:16 -04001684 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001685 // statements between the last case and the end of the switch statement
1686 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1687 (int)codeSegments.size() == defaultSegment)
1688 codeSegments.push_back(nullptr);
1689
1690 // make the switch statement
1691 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001692 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001693
1694 // emit all the code in the segments
1695 breakForLoop.push(false);
1696 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1697 builder.nextSwitchSegment(segmentBlocks, s);
1698 if (codeSegments[s])
1699 codeSegments[s]->traverse(this);
1700 else
1701 builder.addSwitchBreak();
1702 }
1703 breakForLoop.pop();
1704
1705 builder.endSwitch(segmentBlocks);
1706
1707 return false;
1708}
1709
1710void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1711{
1712 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001713 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001714
1715 builder.clearAccessChain();
1716 builder.setAccessChainRValue(constant);
1717}
1718
1719bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1720{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001721 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001722 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001723 // Spec requires back edges to target header blocks, and every header block
1724 // must dominate its merge block. Make a header block first to ensure these
1725 // conditions are met. By definition, it will contain OpLoopMerge, followed
1726 // by a block-ending branch. But we don't want to put any other body/test
1727 // instructions in it, since the body/test may have arbitrary instructions,
1728 // including merges of its own.
1729 builder.setBuildPoint(&blocks.head);
1730 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001731 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001732 spv::Block& test = builder.makeNewBlock();
1733 builder.createBranch(&test);
1734
1735 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001736 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001737 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001738 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001739 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1740
1741 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001742 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001743 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001744 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001745 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001746 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001747
1748 builder.setBuildPoint(&blocks.continue_target);
1749 if (node->getTerminal())
1750 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001751 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001752 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001753 builder.createBranch(&blocks.body);
1754
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001755 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001756 builder.setBuildPoint(&blocks.body);
1757 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001758 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001759 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001760 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001761
1762 builder.setBuildPoint(&blocks.continue_target);
1763 if (node->getTerminal())
1764 node->getTerminal()->traverse(this);
1765 if (node->getTest()) {
1766 node->getTest()->traverse(this);
1767 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001768 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001769 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001770 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001771 // TODO: unless there was a break/return/discard instruction
1772 // somewhere in the body, this is an infinite loop, so we should
1773 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001774 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001775 }
John Kessenich140f3df2015-06-26 16:58:36 -06001776 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001777 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001778 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001779 return false;
1780}
1781
1782bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1783{
1784 if (node->getExpression())
1785 node->getExpression()->traverse(this);
1786
1787 switch (node->getFlowOp()) {
1788 case glslang::EOpKill:
1789 builder.makeDiscard();
1790 break;
1791 case glslang::EOpBreak:
1792 if (breakForLoop.top())
1793 builder.createLoopExit();
1794 else
1795 builder.addSwitchBreak();
1796 break;
1797 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001798 builder.createLoopContinue();
1799 break;
1800 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001801 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001802 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001803 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001804 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001805
1806 builder.clearAccessChain();
1807 break;
1808
1809 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001810 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001811 break;
1812 }
1813
1814 return false;
1815}
1816
1817spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1818{
qining25262b32016-05-06 17:25:16 -04001819 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001820 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001821 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001822 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001823 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001824 }
1825
1826 // Now, handle actual variables
1827 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1828 spv::Id spvType = convertGlslangToSpvType(node->getType());
1829
1830 const char* name = node->getName().c_str();
1831 if (glslang::IsAnonymous(name))
1832 name = "";
1833
1834 return builder.createVariable(storageClass, spvType, name);
1835}
1836
1837// Return type Id of the sampled type.
1838spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1839{
1840 switch (sampler.type) {
1841 case glslang::EbtFloat: return builder.makeFloatType(32);
1842 case glslang::EbtInt: return builder.makeIntType(32);
1843 case glslang::EbtUint: return builder.makeUintType(32);
1844 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001845 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001846 return builder.makeFloatType(32);
1847 }
1848}
1849
John Kessenich8c8505c2016-07-26 12:50:38 -06001850// If node is a swizzle operation, return the type that should be used if
1851// the swizzle base is first consumed by another operation, before the swizzle
1852// is applied.
1853spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1854{
1855 if (node.getAsOperator() &&
1856 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1857 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1858 else
1859 return spv::NoType;
1860}
1861
1862// When inverting a swizzle with a parent op, this function
1863// will apply the swizzle operation to a completed parent operation.
1864spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1865{
1866 std::vector<unsigned> swizzle;
1867 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1868 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1869}
1870
1871
1872// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1873void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1874{
1875 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1876 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1877 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1878}
1879
John Kessenich3ac051e2015-12-20 11:29:16 -07001880// Convert from a glslang type to an SPV type, by calling into a
1881// recursive version of this function. This establishes the inherited
1882// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001883spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1884{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001885 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001886}
1887
1888// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001889// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001890// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001891spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001892{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001894
1895 switch (type.getBasicType()) {
1896 case glslang::EbtVoid:
1897 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001898 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001899 break;
1900 case glslang::EbtFloat:
1901 spvType = builder.makeFloatType(32);
1902 break;
1903 case glslang::EbtDouble:
1904 spvType = builder.makeFloatType(64);
1905 break;
1906 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001907 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1908 // a 32-bit int where non-0 means true.
1909 if (explicitLayout != glslang::ElpNone)
1910 spvType = builder.makeUintType(32);
1911 else
1912 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001913 break;
1914 case glslang::EbtInt:
1915 spvType = builder.makeIntType(32);
1916 break;
1917 case glslang::EbtUint:
1918 spvType = builder.makeUintType(32);
1919 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001920 case glslang::EbtInt64:
1921 builder.addCapability(spv::CapabilityInt64);
1922 spvType = builder.makeIntType(64);
1923 break;
1924 case glslang::EbtUint64:
1925 builder.addCapability(spv::CapabilityInt64);
1926 spvType = builder.makeUintType(64);
1927 break;
John Kessenich426394d2015-07-23 10:22:48 -06001928 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001929 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001930 spvType = builder.makeUintType(32);
1931 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001932 case glslang::EbtSampler:
1933 {
1934 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001935 if (sampler.sampler) {
1936 // pure sampler
1937 spvType = builder.makeSamplerType();
1938 } else {
1939 // an image is present, make its type
1940 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1941 sampler.image ? 2 : 1, TranslateImageFormat(type));
1942 if (sampler.combined) {
1943 // already has both image and sampler, make the combined type
1944 spvType = builder.makeSampledImageType(spvType);
1945 }
John Kessenich55e7d112015-11-15 21:33:39 -07001946 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001947 }
John Kessenich140f3df2015-06-26 16:58:36 -06001948 break;
1949 case glslang::EbtStruct:
1950 case glslang::EbtBlock:
1951 {
1952 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001953 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001954
1955 // Try to share structs for different layouts, but not yet for other
1956 // kinds of qualification (primarily not yet including interpolant qualification).
1957 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001958 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001959 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001960 break;
1961
1962 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001963 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001964 memberRemapper[glslangMembers].resize(glslangMembers->size());
1965 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001966 }
1967 break;
1968 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001969 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001970 break;
1971 }
1972
1973 if (type.isMatrix())
1974 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1975 else {
1976 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1977 if (type.getVectorSize() > 1)
1978 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1979 }
1980
1981 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001982 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1983
John Kessenichc9a80832015-09-12 12:17:44 -06001984 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001985 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001986 // We need to decorate array strides for types needing explicit layout, except blocks.
1987 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001988 // Use a dummy glslang type for querying internal strides of
1989 // arrays of arrays, but using just a one-dimensional array.
1990 glslang::TType simpleArrayType(type, 0); // deference type of the array
1991 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1992 simpleArrayType.getArraySizes().dereference();
1993
1994 // Will compute the higher-order strides here, rather than making a whole
1995 // pile of types and doing repetitive recursion on their contents.
1996 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1997 }
John Kessenichf8842e52016-01-04 19:22:56 -07001998
1999 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002000 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002001 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002002 if (stride > 0)
2003 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002004 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002005 }
2006 } else {
2007 // single-dimensional array, and don't yet have stride
2008
John Kessenichf8842e52016-01-04 19:22:56 -07002009 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002010 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2011 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002012 }
John Kessenich31ed4832015-09-09 17:51:38 -06002013
John Kessenichc9a80832015-09-12 12:17:44 -06002014 // Do the outer dimension, which might not be known for a runtime-sized array
2015 if (type.isRuntimeSizedArray()) {
2016 spvType = builder.makeRuntimeArray(spvType);
2017 } else {
2018 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002019 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002020 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002021 if (stride > 0)
2022 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002023 }
2024
2025 return spvType;
2026}
2027
John Kessenich6090df02016-06-30 21:18:02 -06002028
2029// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2030// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2031// Mutually recursive with convertGlslangToSpvType().
2032spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2033 const glslang::TTypeList* glslangMembers,
2034 glslang::TLayoutPacking explicitLayout,
2035 const glslang::TQualifier& qualifier)
2036{
2037 // Create a vector of struct types for SPIR-V to consume
2038 std::vector<spv::Id> spvMembers;
2039 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2040 int locationOffset = 0; // for use across struct members, when they are called recursively
2041 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2042 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2043 if (glslangMember.hiddenMember()) {
2044 ++memberDelta;
2045 if (type.getBasicType() == glslang::EbtBlock)
2046 memberRemapper[glslangMembers][i] = -1;
2047 } else {
2048 if (type.getBasicType() == glslang::EbtBlock)
2049 memberRemapper[glslangMembers][i] = i - memberDelta;
2050 // modify just this child's view of the qualifier
2051 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2052 InheritQualifiers(memberQualifier, qualifier);
2053
2054 // manually inherit location; it's more complex
2055 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2056 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2057 if (qualifier.hasLocation())
2058 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2059
2060 // recurse
2061 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2062 }
2063 }
2064
2065 // Make the SPIR-V type
2066 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
2067 if (! HasNonLayoutQualifiers(qualifier))
2068 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2069
2070 // Decorate it
2071 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2072
2073 return spvType;
2074}
2075
2076void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2077 const glslang::TTypeList* glslangMembers,
2078 glslang::TLayoutPacking explicitLayout,
2079 const glslang::TQualifier& qualifier,
2080 spv::Id spvType)
2081{
2082 // Name and decorate the non-hidden members
2083 int offset = -1;
2084 int locationOffset = 0; // for use within the members of this struct
2085 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2086 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2087 int member = i;
2088 if (type.getBasicType() == glslang::EbtBlock)
2089 member = memberRemapper[glslangMembers][i];
2090
2091 // modify just this child's view of the qualifier
2092 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2093 InheritQualifiers(memberQualifier, qualifier);
2094
2095 // using -1 above to indicate a hidden member
2096 if (member >= 0) {
2097 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2098 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2099 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2100 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2101 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2102 if (type.getBasicType() == glslang::EbtBlock) {
2103 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2104 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2105 }
2106 }
2107 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2108
2109 if (qualifier.storage == glslang::EvqBuffer) {
2110 std::vector<spv::Decoration> memory;
2111 TranslateMemoryDecoration(memberQualifier, memory);
2112 for (unsigned int i = 0; i < memory.size(); ++i)
2113 addMemberDecoration(spvType, member, memory[i]);
2114 }
2115
John Kessenich2f47bc92016-06-30 21:47:35 -06002116 // Compute location decoration; tricky based on whether inheritance is at play and
2117 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002118 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2119 // probably move to the linker stage of the front end proper, and just have the
2120 // answer sitting already distributed throughout the individual member locations.
2121 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002122 // Ignore member locations if the container is an array, as that's
2123 // ill-specified and decisions have been made to not allow this anyway.
2124 // The object itself must have a location, and that comes out from decorating the object,
2125 // not the type (this code decorates types).
2126 if (! type.isArray()) {
2127 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2128 // struct members should not have explicit locations
2129 assert(type.getBasicType() != glslang::EbtStruct);
2130 location = memberQualifier.layoutLocation;
2131 } else if (type.getBasicType() != glslang::EbtBlock) {
2132 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2133 // The members, and their nested types, must not themselves have Location decorations.
2134 } else if (qualifier.hasLocation()) // inheritance
2135 location = qualifier.layoutLocation + locationOffset;
2136 }
John Kessenich6090df02016-06-30 21:18:02 -06002137 if (location >= 0)
2138 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2139
John Kessenich2f47bc92016-06-30 21:47:35 -06002140 if (qualifier.hasLocation()) // track for upcoming inheritance
2141 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2142
John Kessenich6090df02016-06-30 21:18:02 -06002143 // component, XFB, others
2144 if (glslangMember.getQualifier().hasComponent())
2145 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2146 if (glslangMember.getQualifier().hasXfbOffset())
2147 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2148 else if (explicitLayout != glslang::ElpNone) {
2149 // figure out what to do with offset, which is accumulating
2150 int nextOffset;
2151 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2152 if (offset >= 0)
2153 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2154 offset = nextOffset;
2155 }
2156
2157 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2158 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2159
2160 // built-in variable decorations
2161 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002162 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002163 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2164 }
2165 }
2166
2167 // Decorate the structure
2168 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2169 addDecoration(spvType, TranslateBlockDecoration(type));
2170 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2171 builder.addCapability(spv::CapabilityGeometryStreams);
2172 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2173 }
2174 if (glslangIntermediate->getXfbMode()) {
2175 builder.addCapability(spv::CapabilityTransformFeedback);
2176 if (type.getQualifier().hasXfbStride())
2177 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2178 if (type.getQualifier().hasXfbBuffer())
2179 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2180 }
2181}
2182
John Kessenich6c292d32016-02-15 20:58:50 -07002183// Turn the expression forming the array size into an id.
2184// This is not quite trivial, because of specialization constants.
2185// Sometimes, a raw constant is turned into an Id, and sometimes
2186// a specialization constant expression is.
2187spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2188{
2189 // First, see if this is sized with a node, meaning a specialization constant:
2190 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2191 if (specNode != nullptr) {
2192 builder.clearAccessChain();
2193 specNode->traverse(this);
2194 return accessChainLoad(specNode->getAsTyped()->getType());
2195 }
qining25262b32016-05-06 17:25:16 -04002196
John Kessenich6c292d32016-02-15 20:58:50 -07002197 // Otherwise, need a compile-time (front end) size, get it:
2198 int size = arraySizes.getDimSize(dim);
2199 assert(size > 0);
2200 return builder.makeUintConstant(size);
2201}
2202
John Kessenich103bef92016-02-08 21:38:15 -07002203// Wrap the builder's accessChainLoad to:
2204// - localize handling of RelaxedPrecision
2205// - use the SPIR-V inferred type instead of another conversion of the glslang type
2206// (avoids unnecessary work and possible type punning for structures)
2207// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002208spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2209{
John Kessenich103bef92016-02-08 21:38:15 -07002210 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2211 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2212
2213 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002214 if (type.getBasicType() == glslang::EbtBool) {
2215 if (builder.isScalarType(nominalTypeId)) {
2216 // Conversion for bool
2217 spv::Id boolType = builder.makeBoolType();
2218 if (nominalTypeId != boolType)
2219 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2220 } else if (builder.isVectorType(nominalTypeId)) {
2221 // Conversion for bvec
2222 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2223 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2224 if (nominalTypeId != bvecType)
2225 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2226 }
2227 }
John Kessenich103bef92016-02-08 21:38:15 -07002228
2229 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002230}
2231
Rex Xu27253232016-02-23 17:51:09 +08002232// Wrap the builder's accessChainStore to:
2233// - do conversion of concrete to abstract type
2234void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2235{
2236 // Need to convert to abstract types when necessary
2237 if (type.getBasicType() == glslang::EbtBool) {
2238 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2239
2240 if (builder.isScalarType(nominalTypeId)) {
2241 // Conversion for bool
2242 spv::Id boolType = builder.makeBoolType();
2243 if (nominalTypeId != boolType) {
2244 spv::Id zero = builder.makeUintConstant(0);
2245 spv::Id one = builder.makeUintConstant(1);
2246 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2247 }
2248 } else if (builder.isVectorType(nominalTypeId)) {
2249 // Conversion for bvec
2250 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2251 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2252 if (nominalTypeId != bvecType) {
2253 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2254 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2255 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2256 }
2257 }
2258 }
2259
2260 builder.accessChainStore(rvalue);
2261}
2262
John Kessenichf85e8062015-12-19 13:57:10 -07002263// Decide whether or not this type should be
2264// decorated with offsets and strides, and if so
2265// whether std140 or std430 rules should be applied.
2266glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002267{
John Kessenichf85e8062015-12-19 13:57:10 -07002268 // has to be a block
2269 if (type.getBasicType() != glslang::EbtBlock)
2270 return glslang::ElpNone;
2271
2272 // has to be a uniform or buffer block
2273 if (type.getQualifier().storage != glslang::EvqUniform &&
2274 type.getQualifier().storage != glslang::EvqBuffer)
2275 return glslang::ElpNone;
2276
2277 // return the layout to use
2278 switch (type.getQualifier().layoutPacking) {
2279 case glslang::ElpStd140:
2280 case glslang::ElpStd430:
2281 return type.getQualifier().layoutPacking;
2282 default:
2283 return glslang::ElpNone;
2284 }
John Kessenich31ed4832015-09-09 17:51:38 -06002285}
2286
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002287// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002288int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002289{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002290 int size;
John Kessenich49987892015-12-29 17:11:44 -07002291 int stride;
2292 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002293
2294 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002295}
2296
John Kessenich49987892015-12-29 17:11:44 -07002297// 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 -07002298// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002299int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002300{
John Kessenich49987892015-12-29 17:11:44 -07002301 glslang::TType elementType;
2302 elementType.shallowCopy(matrixType);
2303 elementType.clearArraySizes();
2304
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002305 int size;
John Kessenich49987892015-12-29 17:11:44 -07002306 int stride;
2307 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2308
2309 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002310}
2311
John Kessenich5e4b1242015-08-06 22:53:06 -06002312// Given a member type of a struct, realign the current offset for it, and compute
2313// the next (not yet aligned) offset for the next member, which will get aligned
2314// on the next call.
2315// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2316// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2317// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002318void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002319 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002320{
2321 // this will get a positive value when deemed necessary
2322 nextOffset = -1;
2323
John Kessenich5e4b1242015-08-06 22:53:06 -06002324 // override anything in currentOffset with user-set offset
2325 if (memberType.getQualifier().hasOffset())
2326 currentOffset = memberType.getQualifier().layoutOffset;
2327
2328 // It could be that current linker usage in glslang updated all the layoutOffset,
2329 // in which case the following code does not matter. But, that's not quite right
2330 // once cross-compilation unit GLSL validation is done, as the original user
2331 // settings are needed in layoutOffset, and then the following will come into play.
2332
John Kessenichf85e8062015-12-19 13:57:10 -07002333 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002334 if (! memberType.getQualifier().hasOffset())
2335 currentOffset = -1;
2336
2337 return;
2338 }
2339
John Kessenichf85e8062015-12-19 13:57:10 -07002340 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002341 if (currentOffset < 0)
2342 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002343
John Kessenich5e4b1242015-08-06 22:53:06 -06002344 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2345 // but possibly not yet correctly aligned.
2346
2347 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002348 int dummyStride;
2349 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002350 glslang::RoundToPow2(currentOffset, memberAlignment);
2351 nextOffset = currentOffset + memberSize;
2352}
2353
David Netoa901ffe2016-06-08 14:11:40 +01002354void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002355{
David Netoa901ffe2016-06-08 14:11:40 +01002356 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2357 switch (glslangBuiltIn)
2358 {
2359 case glslang::EbvClipDistance:
2360 case glslang::EbvCullDistance:
2361 case glslang::EbvPointSize:
2362 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2363 // Alternately, we could just call this for any glslang built-in, since the
2364 // capability already guards against duplicates.
2365 TranslateBuiltInDecoration(glslangBuiltIn, false);
2366 break;
2367 default:
2368 // Capabilities were already generated when the struct was declared.
2369 break;
2370 }
John Kessenichebb50532016-05-16 19:22:05 -06002371}
2372
John Kessenich140f3df2015-06-26 16:58:36 -06002373bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2374{
John Kessenich4d65ee32016-03-12 18:17:47 -07002375 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002376 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002377 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002378}
2379
2380// Make all the functions, skeletally, without actually visiting their bodies.
2381void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2382{
2383 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2384 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2385 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2386 continue;
2387
2388 // We're on a user function. Set up the basic interface for the function now,
2389 // so that it's available to call.
2390 // Translating the body will happen later.
2391 //
qining25262b32016-05-06 17:25:16 -04002392 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002393 // function. What it is an address of varies:
2394 //
2395 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2396 // so that write needs to be to a copy, hence the address of a copy works.
2397 //
2398 // - "const in" parameters can just be the r-value, as no writes need occur.
2399 //
2400 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2401 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2402
2403 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002404 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002405 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2406
2407 for (int p = 0; p < (int)parameters.size(); ++p) {
2408 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2409 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002410 if (paramType.isOpaque())
2411 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2412 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002413 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2414 else
2415 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002416 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002417 paramTypes.push_back(typeId);
2418 }
2419
2420 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002421 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2422 convertGlslangToSpvType(glslFunction->getType()),
2423 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002424
2425 // Track function to emit/call later
2426 functionMap[glslFunction->getName().c_str()] = function;
2427
2428 // Set the parameter id's
2429 for (int p = 0; p < (int)parameters.size(); ++p) {
2430 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2431 // give a name too
2432 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2433 }
2434 }
2435}
2436
2437// Process all the initializers, while skipping the functions and link objects
2438void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2439{
2440 builder.setBuildPoint(shaderEntry->getLastBlock());
2441 for (int i = 0; i < (int)initializers.size(); ++i) {
2442 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2443 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2444
2445 // We're on a top-level node that's not a function. Treat as an initializer, whose
2446 // code goes into the beginning of main.
2447 initializer->traverse(this);
2448 }
2449 }
2450}
2451
2452// Process all the functions, while skipping initializers.
2453void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2454{
2455 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2456 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2457 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2458 node->traverse(this);
2459 }
2460}
2461
2462void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2463{
qining25262b32016-05-06 17:25:16 -04002464 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002465 // that called makeFunctions().
2466 spv::Function* function = functionMap[node->getName().c_str()];
2467 spv::Block* functionBlock = function->getEntryBlock();
2468 builder.setBuildPoint(functionBlock);
2469}
2470
Rex Xu04db3f52015-09-16 11:44:02 +08002471void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002472{
Rex Xufc618912015-09-09 16:42:49 +08002473 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002474
2475 glslang::TSampler sampler = {};
2476 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002477 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002478 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2479 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2480 }
2481
John Kessenich140f3df2015-06-26 16:58:36 -06002482 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2483 builder.clearAccessChain();
2484 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002485
2486 // Special case l-value operands
2487 bool lvalue = false;
2488 switch (node.getOp()) {
2489 case glslang::EOpImageAtomicAdd:
2490 case glslang::EOpImageAtomicMin:
2491 case glslang::EOpImageAtomicMax:
2492 case glslang::EOpImageAtomicAnd:
2493 case glslang::EOpImageAtomicOr:
2494 case glslang::EOpImageAtomicXor:
2495 case glslang::EOpImageAtomicExchange:
2496 case glslang::EOpImageAtomicCompSwap:
2497 if (i == 0)
2498 lvalue = true;
2499 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002500 case glslang::EOpSparseImageLoad:
2501 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2502 lvalue = true;
2503 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002504 case glslang::EOpSparseTexture:
2505 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2506 lvalue = true;
2507 break;
2508 case glslang::EOpSparseTextureClamp:
2509 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2510 lvalue = true;
2511 break;
2512 case glslang::EOpSparseTextureLod:
2513 case glslang::EOpSparseTextureOffset:
2514 if (i == 3)
2515 lvalue = true;
2516 break;
2517 case glslang::EOpSparseTextureFetch:
2518 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2519 lvalue = true;
2520 break;
2521 case glslang::EOpSparseTextureFetchOffset:
2522 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2523 lvalue = true;
2524 break;
2525 case glslang::EOpSparseTextureLodOffset:
2526 case glslang::EOpSparseTextureGrad:
2527 case glslang::EOpSparseTextureOffsetClamp:
2528 if (i == 4)
2529 lvalue = true;
2530 break;
2531 case glslang::EOpSparseTextureGradOffset:
2532 case glslang::EOpSparseTextureGradClamp:
2533 if (i == 5)
2534 lvalue = true;
2535 break;
2536 case glslang::EOpSparseTextureGradOffsetClamp:
2537 if (i == 6)
2538 lvalue = true;
2539 break;
2540 case glslang::EOpSparseTextureGather:
2541 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2542 lvalue = true;
2543 break;
2544 case glslang::EOpSparseTextureGatherOffset:
2545 case glslang::EOpSparseTextureGatherOffsets:
2546 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2547 lvalue = true;
2548 break;
Rex Xufc618912015-09-09 16:42:49 +08002549 default:
2550 break;
2551 }
2552
Rex Xu6b86d492015-09-16 17:48:22 +08002553 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002554 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002555 else
John Kessenich32cfd492016-02-02 12:37:46 -07002556 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002557 }
2558}
2559
John Kessenichfc51d282015-08-19 13:34:18 -06002560void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002561{
John Kessenichfc51d282015-08-19 13:34:18 -06002562 builder.clearAccessChain();
2563 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002564 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002565}
John Kessenich140f3df2015-06-26 16:58:36 -06002566
John Kessenichfc51d282015-08-19 13:34:18 -06002567spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2568{
Rex Xufc618912015-09-09 16:42:49 +08002569 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002570 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002571 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002572 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002573
John Kessenichfc51d282015-08-19 13:34:18 -06002574 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002575 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2576 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2577 std::vector<spv::Id> arguments;
2578 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002579 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002580 else
2581 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002582 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002583
2584 spv::Builder::TextureParameters params = { };
2585 params.sampler = arguments[0];
2586
Rex Xu04db3f52015-09-16 11:44:02 +08002587 glslang::TCrackedTextureOp cracked;
2588 node->crackTexture(sampler, cracked);
2589
John Kessenichfc51d282015-08-19 13:34:18 -06002590 // Check for queries
2591 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002592 // a sampled image needs to have the image extracted first
2593 if (builder.isSampledImage(params.sampler))
2594 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002595 switch (node->getOp()) {
2596 case glslang::EOpImageQuerySize:
2597 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002598 if (arguments.size() > 1) {
2599 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002600 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002601 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002602 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002603 case glslang::EOpImageQuerySamples:
2604 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002605 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002606 case glslang::EOpTextureQueryLod:
2607 params.coords = arguments[1];
2608 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2609 case glslang::EOpTextureQueryLevels:
2610 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002611 case glslang::EOpSparseTexelsResident:
2612 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002613 default:
2614 assert(0);
2615 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002616 }
John Kessenich140f3df2015-06-26 16:58:36 -06002617 }
2618
Rex Xufc618912015-09-09 16:42:49 +08002619 // Check for image functions other than queries
2620 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002621 std::vector<spv::Id> operands;
2622 auto opIt = arguments.begin();
2623 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002624
2625 // Handle subpass operations
2626 // TODO: GLSL should change to have the "MS" only on the type rather than the
2627 // built-in function.
2628 if (cracked.subpass) {
2629 // add on the (0,0) coordinate
2630 spv::Id zero = builder.makeIntConstant(0);
2631 std::vector<spv::Id> comps;
2632 comps.push_back(zero);
2633 comps.push_back(zero);
2634 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2635 if (sampler.ms) {
2636 operands.push_back(spv::ImageOperandsSampleMask);
2637 operands.push_back(*(opIt++));
2638 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002639 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002640 }
2641
John Kessenich56bab042015-09-16 10:54:31 -06002642 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002643 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002644 if (sampler.ms) {
2645 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002646 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002647 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002648 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2649 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002650 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002651 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002652 if (sampler.ms) {
2653 operands.push_back(*(opIt + 1));
2654 operands.push_back(spv::ImageOperandsSampleMask);
2655 operands.push_back(*opIt);
2656 } else
2657 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002658 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002659 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2660 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002661 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002662 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2663 builder.addCapability(spv::CapabilitySparseResidency);
2664 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2665 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2666
2667 if (sampler.ms) {
2668 operands.push_back(spv::ImageOperandsSampleMask);
2669 operands.push_back(*opIt++);
2670 }
2671
2672 // Create the return type that was a special structure
2673 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002674 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002675 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2676 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2677
2678 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2679
2680 // Decode the return type
2681 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2682 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002683 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002684 // Process image atomic operations
2685
2686 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2687 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002688 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002689
John Kessenich8c8505c2016-07-26 12:50:38 -06002690 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002691 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002692
2693 std::vector<spv::Id> operands;
2694 operands.push_back(pointer);
2695 for (; opIt != arguments.end(); ++opIt)
2696 operands.push_back(*opIt);
2697
John Kessenich8c8505c2016-07-26 12:50:38 -06002698 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002699 }
2700 }
2701
2702 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002703 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002704 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2705
John Kessenichfc51d282015-08-19 13:34:18 -06002706 // check for bias argument
2707 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002708 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002709 int nonBiasArgCount = 2;
2710 if (cracked.offset)
2711 ++nonBiasArgCount;
2712 if (cracked.grad)
2713 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002714 if (cracked.lodClamp)
2715 ++nonBiasArgCount;
2716 if (sparse)
2717 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002718
2719 if ((int)arguments.size() > nonBiasArgCount)
2720 bias = true;
2721 }
2722
John Kessenicha5c33d62016-06-02 23:45:21 -06002723 // See if the sampler param should really be just the SPV image part
2724 if (cracked.fetch) {
2725 // a fetch needs to have the image extracted first
2726 if (builder.isSampledImage(params.sampler))
2727 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2728 }
2729
John Kessenichfc51d282015-08-19 13:34:18 -06002730 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002731
John Kessenichfc51d282015-08-19 13:34:18 -06002732 params.coords = arguments[1];
2733 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002734 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002735
2736 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002737 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002738 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002739 ++extraArgs;
2740 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002741 params.Dref = arguments[2];
2742 ++extraArgs;
2743 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002744 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002745 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002746 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002747 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002748 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002749 dRefComp = builder.getNumComponents(params.coords) - 1;
2750 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002751 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2752 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002753
2754 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002755 if (cracked.lod) {
2756 params.lod = arguments[2];
2757 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002758 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2759 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2760 noImplicitLod = true;
2761 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002762
2763 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002764 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002765 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002766 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002767 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002768
2769 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002770 if (cracked.grad) {
2771 params.gradX = arguments[2 + extraArgs];
2772 params.gradY = arguments[3 + extraArgs];
2773 extraArgs += 2;
2774 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002775
2776 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002777 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002778 params.offset = arguments[2 + extraArgs];
2779 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002780 } else if (cracked.offsets) {
2781 params.offsets = arguments[2 + extraArgs];
2782 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002783 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002784
2785 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002786 if (cracked.lodClamp) {
2787 params.lodClamp = arguments[2 + extraArgs];
2788 ++extraArgs;
2789 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002790
2791 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002792 if (sparse) {
2793 params.texelOut = arguments[2 + extraArgs];
2794 ++extraArgs;
2795 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002796
2797 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002798 if (bias) {
2799 params.bias = arguments[2 + extraArgs];
2800 ++extraArgs;
2801 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002802
2803 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002804 if (cracked.gather && ! sampler.shadow) {
2805 // default component is 0, if missing, otherwise an argument
2806 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002807 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002808 ++extraArgs;
2809 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002810 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002811 }
2812 }
John Kessenichfc51d282015-08-19 13:34:18 -06002813
John Kessenich65336482016-06-16 14:06:26 -06002814 // projective component (might not to move)
2815 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2816 // are divided by the last component of P."
2817 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2818 // unused components will appear after all used components."
2819 if (cracked.proj) {
2820 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2821 int projTargetComp;
2822 switch (sampler.dim) {
2823 case glslang::Esd1D: projTargetComp = 1; break;
2824 case glslang::Esd2D: projTargetComp = 2; break;
2825 case glslang::EsdRect: projTargetComp = 2; break;
2826 default: projTargetComp = projSourceComp; break;
2827 }
2828 // copy the projective coordinate if we have to
2829 if (projTargetComp != projSourceComp) {
2830 spv::Id projComp = builder.createCompositeExtract(params.coords,
2831 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2832 projSourceComp);
2833 params.coords = builder.createCompositeInsert(projComp, params.coords,
2834 builder.getTypeId(params.coords), projTargetComp);
2835 }
2836 }
2837
John Kessenich8c8505c2016-07-26 12:50:38 -06002838 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002839}
2840
2841spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2842{
2843 // Grab the function's pointer from the previously created function
2844 spv::Function* function = functionMap[node->getName().c_str()];
2845 if (! function)
2846 return 0;
2847
2848 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2849 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2850
2851 // See comments in makeFunctions() for details about the semantics for parameter passing.
2852 //
2853 // These imply we need a four step process:
2854 // 1. Evaluate the arguments
2855 // 2. Allocate and make copies of in, out, and inout arguments
2856 // 3. Make the call
2857 // 4. Copy back the results
2858
2859 // 1. Evaluate the arguments
2860 std::vector<spv::Builder::AccessChain> lValues;
2861 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002862 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002863 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002864 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002865 // build l-value
2866 builder.clearAccessChain();
2867 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002868 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002869 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002870 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002871 // save l-value
2872 lValues.push_back(builder.getAccessChain());
2873 } else {
2874 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002875 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002876 }
2877 }
2878
2879 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2880 // copy the original into that space.
2881 //
2882 // Also, build up the list of actual arguments to pass in for the call
2883 int lValueCount = 0;
2884 int rValueCount = 0;
2885 std::vector<spv::Id> spvArgs;
2886 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002887 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002888 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002889 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002890 builder.setAccessChain(lValues[lValueCount]);
2891 arg = builder.accessChainGetLValue();
2892 ++lValueCount;
2893 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002894 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002895 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2896 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2897 // need to copy the input into output space
2898 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002899 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002900 builder.createStore(copy, arg);
2901 }
2902 ++lValueCount;
2903 } else {
2904 arg = rValues[rValueCount];
2905 ++rValueCount;
2906 }
2907 spvArgs.push_back(arg);
2908 }
2909
2910 // 3. Make the call.
2911 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002912 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002913
2914 // 4. Copy back out an "out" arguments.
2915 lValueCount = 0;
2916 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2917 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2918 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2919 spv::Id copy = builder.createLoad(spvArgs[a]);
2920 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002921 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002922 }
2923 ++lValueCount;
2924 }
2925 }
2926
2927 return result;
2928}
2929
2930// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002931spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2932 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002933 spv::Id typeId, spv::Id left, spv::Id right,
2934 glslang::TBasicType typeProxy, bool reduceComparison)
2935{
Rex Xu8ff43de2016-04-22 16:51:45 +08002936 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002938 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002939
2940 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002941 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002942 bool comparison = false;
2943
2944 switch (op) {
2945 case glslang::EOpAdd:
2946 case glslang::EOpAddAssign:
2947 if (isFloat)
2948 binOp = spv::OpFAdd;
2949 else
2950 binOp = spv::OpIAdd;
2951 break;
2952 case glslang::EOpSub:
2953 case glslang::EOpSubAssign:
2954 if (isFloat)
2955 binOp = spv::OpFSub;
2956 else
2957 binOp = spv::OpISub;
2958 break;
2959 case glslang::EOpMul:
2960 case glslang::EOpMulAssign:
2961 if (isFloat)
2962 binOp = spv::OpFMul;
2963 else
2964 binOp = spv::OpIMul;
2965 break;
2966 case glslang::EOpVectorTimesScalar:
2967 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002968 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002969 if (builder.isVector(right))
2970 std::swap(left, right);
2971 assert(builder.isScalar(right));
2972 needMatchingVectors = false;
2973 binOp = spv::OpVectorTimesScalar;
2974 } else
2975 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 case glslang::EOpVectorTimesMatrix:
2978 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002979 binOp = spv::OpVectorTimesMatrix;
2980 break;
2981 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002982 binOp = spv::OpMatrixTimesVector;
2983 break;
2984 case glslang::EOpMatrixTimesScalar:
2985 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002986 binOp = spv::OpMatrixTimesScalar;
2987 break;
2988 case glslang::EOpMatrixTimesMatrix:
2989 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002990 binOp = spv::OpMatrixTimesMatrix;
2991 break;
2992 case glslang::EOpOuterProduct:
2993 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002994 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002995 break;
2996
2997 case glslang::EOpDiv:
2998 case glslang::EOpDivAssign:
2999 if (isFloat)
3000 binOp = spv::OpFDiv;
3001 else if (isUnsigned)
3002 binOp = spv::OpUDiv;
3003 else
3004 binOp = spv::OpSDiv;
3005 break;
3006 case glslang::EOpMod:
3007 case glslang::EOpModAssign:
3008 if (isFloat)
3009 binOp = spv::OpFMod;
3010 else if (isUnsigned)
3011 binOp = spv::OpUMod;
3012 else
3013 binOp = spv::OpSMod;
3014 break;
3015 case glslang::EOpRightShift:
3016 case glslang::EOpRightShiftAssign:
3017 if (isUnsigned)
3018 binOp = spv::OpShiftRightLogical;
3019 else
3020 binOp = spv::OpShiftRightArithmetic;
3021 break;
3022 case glslang::EOpLeftShift:
3023 case glslang::EOpLeftShiftAssign:
3024 binOp = spv::OpShiftLeftLogical;
3025 break;
3026 case glslang::EOpAnd:
3027 case glslang::EOpAndAssign:
3028 binOp = spv::OpBitwiseAnd;
3029 break;
3030 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003031 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 binOp = spv::OpLogicalAnd;
3033 break;
3034 case glslang::EOpInclusiveOr:
3035 case glslang::EOpInclusiveOrAssign:
3036 binOp = spv::OpBitwiseOr;
3037 break;
3038 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003039 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003040 binOp = spv::OpLogicalOr;
3041 break;
3042 case glslang::EOpExclusiveOr:
3043 case glslang::EOpExclusiveOrAssign:
3044 binOp = spv::OpBitwiseXor;
3045 break;
3046 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003047 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003048 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 break;
3050
3051 case glslang::EOpLessThan:
3052 case glslang::EOpGreaterThan:
3053 case glslang::EOpLessThanEqual:
3054 case glslang::EOpGreaterThanEqual:
3055 case glslang::EOpEqual:
3056 case glslang::EOpNotEqual:
3057 case glslang::EOpVectorEqual:
3058 case glslang::EOpVectorNotEqual:
3059 comparison = true;
3060 break;
3061 default:
3062 break;
3063 }
3064
John Kessenich7c1aa102015-10-15 13:29:11 -06003065 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003066 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003067 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003068 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003069 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003070
3071 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003072 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003073 builder.promoteScalar(precision, left, right);
3074
qining25262b32016-05-06 17:25:16 -04003075 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3076 addDecoration(result, noContraction);
3077 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003078 }
3079
3080 if (! comparison)
3081 return 0;
3082
John Kessenich7c1aa102015-10-15 13:29:11 -06003083 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003084
John Kessenich4583b612016-08-07 19:14:22 -06003085 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3086 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003087 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003088
3089 switch (op) {
3090 case glslang::EOpLessThan:
3091 if (isFloat)
3092 binOp = spv::OpFOrdLessThan;
3093 else if (isUnsigned)
3094 binOp = spv::OpULessThan;
3095 else
3096 binOp = spv::OpSLessThan;
3097 break;
3098 case glslang::EOpGreaterThan:
3099 if (isFloat)
3100 binOp = spv::OpFOrdGreaterThan;
3101 else if (isUnsigned)
3102 binOp = spv::OpUGreaterThan;
3103 else
3104 binOp = spv::OpSGreaterThan;
3105 break;
3106 case glslang::EOpLessThanEqual:
3107 if (isFloat)
3108 binOp = spv::OpFOrdLessThanEqual;
3109 else if (isUnsigned)
3110 binOp = spv::OpULessThanEqual;
3111 else
3112 binOp = spv::OpSLessThanEqual;
3113 break;
3114 case glslang::EOpGreaterThanEqual:
3115 if (isFloat)
3116 binOp = spv::OpFOrdGreaterThanEqual;
3117 else if (isUnsigned)
3118 binOp = spv::OpUGreaterThanEqual;
3119 else
3120 binOp = spv::OpSGreaterThanEqual;
3121 break;
3122 case glslang::EOpEqual:
3123 case glslang::EOpVectorEqual:
3124 if (isFloat)
3125 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003126 else if (isBool)
3127 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003128 else
3129 binOp = spv::OpIEqual;
3130 break;
3131 case glslang::EOpNotEqual:
3132 case glslang::EOpVectorNotEqual:
3133 if (isFloat)
3134 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003135 else if (isBool)
3136 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003137 else
3138 binOp = spv::OpINotEqual;
3139 break;
3140 default:
3141 break;
3142 }
3143
qining25262b32016-05-06 17:25:16 -04003144 if (binOp != spv::OpNop) {
3145 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3146 addDecoration(result, noContraction);
3147 return builder.setPrecision(result, precision);
3148 }
John Kessenich140f3df2015-06-26 16:58:36 -06003149
3150 return 0;
3151}
3152
John Kessenich04bb8a02015-12-12 12:28:14 -07003153//
3154// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3155// These can be any of:
3156//
3157// matrix * scalar
3158// scalar * matrix
3159// matrix * matrix linear algebraic
3160// matrix * vector
3161// vector * matrix
3162// matrix * matrix componentwise
3163// matrix op matrix op in {+, -, /}
3164// matrix op scalar op in {+, -, /}
3165// scalar op matrix op in {+, -, /}
3166//
qining25262b32016-05-06 17:25:16 -04003167spv::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 -07003168{
3169 bool firstClass = true;
3170
3171 // First, handle first-class matrix operations (* and matrix/scalar)
3172 switch (op) {
3173 case spv::OpFDiv:
3174 if (builder.isMatrix(left) && builder.isScalar(right)) {
3175 // turn matrix / scalar into a multiply...
3176 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3177 op = spv::OpMatrixTimesScalar;
3178 } else
3179 firstClass = false;
3180 break;
3181 case spv::OpMatrixTimesScalar:
3182 if (builder.isMatrix(right))
3183 std::swap(left, right);
3184 assert(builder.isScalar(right));
3185 break;
3186 case spv::OpVectorTimesMatrix:
3187 assert(builder.isVector(left));
3188 assert(builder.isMatrix(right));
3189 break;
3190 case spv::OpMatrixTimesVector:
3191 assert(builder.isMatrix(left));
3192 assert(builder.isVector(right));
3193 break;
3194 case spv::OpMatrixTimesMatrix:
3195 assert(builder.isMatrix(left));
3196 assert(builder.isMatrix(right));
3197 break;
3198 default:
3199 firstClass = false;
3200 break;
3201 }
3202
qining25262b32016-05-06 17:25:16 -04003203 if (firstClass) {
3204 spv::Id result = builder.createBinOp(op, typeId, left, right);
3205 addDecoration(result, noContraction);
3206 return builder.setPrecision(result, precision);
3207 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003208
LoopDawg592860c2016-06-09 08:57:35 -06003209 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003210 // The result type of all of them is the same type as the (a) matrix operand.
3211 // The algorithm is to:
3212 // - break the matrix(es) into vectors
3213 // - smear any scalar to a vector
3214 // - do vector operations
3215 // - make a matrix out the vector results
3216 switch (op) {
3217 case spv::OpFAdd:
3218 case spv::OpFSub:
3219 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003220 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003221 case spv::OpFMul:
3222 {
3223 // one time set up...
3224 bool leftMat = builder.isMatrix(left);
3225 bool rightMat = builder.isMatrix(right);
3226 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3227 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3228 spv::Id scalarType = builder.getScalarTypeId(typeId);
3229 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3230 std::vector<spv::Id> results;
3231 spv::Id smearVec = spv::NoResult;
3232 if (builder.isScalar(left))
3233 smearVec = builder.smearScalar(precision, left, vecType);
3234 else if (builder.isScalar(right))
3235 smearVec = builder.smearScalar(precision, right, vecType);
3236
3237 // do each vector op
3238 for (unsigned int c = 0; c < numCols; ++c) {
3239 std::vector<unsigned int> indexes;
3240 indexes.push_back(c);
3241 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3242 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003243 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3244 addDecoration(result, noContraction);
3245 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003246 }
3247
3248 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003249 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003250 }
3251 default:
3252 assert(0);
3253 return spv::NoResult;
3254 }
3255}
3256
qining25262b32016-05-06 17:25:16 -04003257spv::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 -06003258{
3259 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003260 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003261 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003262 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003263 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003264
3265 switch (op) {
3266 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003267 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003268 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003269 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003270 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003271 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003272 unaryOp = spv::OpSNegate;
3273 break;
3274
3275 case glslang::EOpLogicalNot:
3276 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003277 unaryOp = spv::OpLogicalNot;
3278 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003279 case glslang::EOpBitwiseNot:
3280 unaryOp = spv::OpNot;
3281 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003282
John Kessenich140f3df2015-06-26 16:58:36 -06003283 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003284 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003285 break;
3286 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003287 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003288 break;
3289 case glslang::EOpTranspose:
3290 unaryOp = spv::OpTranspose;
3291 break;
3292
3293 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003294 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003295 break;
3296 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003297 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003298 break;
3299 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003300 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003301 break;
3302 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003303 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003304 break;
3305 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003306 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003307 break;
3308 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003309 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003310 break;
3311 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003312 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003313 break;
3314 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003315 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003316 break;
3317
3318 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003319 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003322 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003323 break;
3324 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003325 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003326 break;
3327 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003328 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003329 break;
3330 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003331 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003332 break;
3333 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003334 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003335 break;
3336
3337 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003338 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003339 break;
3340 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003341 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003342 break;
3343
3344 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003345 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003346 break;
3347 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003348 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003349 break;
3350 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003351 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003354 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003355 break;
3356 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003357 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003358 break;
3359 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003360 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003361 break;
3362
3363 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003364 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003365 break;
3366 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003367 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003368 break;
3369 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003370 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003371 break;
3372 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003373 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003374 break;
3375 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003376 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003377 break;
3378 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003379 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003380 break;
3381
3382 case glslang::EOpIsNan:
3383 unaryOp = spv::OpIsNan;
3384 break;
3385 case glslang::EOpIsInf:
3386 unaryOp = spv::OpIsInf;
3387 break;
LoopDawg592860c2016-06-09 08:57:35 -06003388 case glslang::EOpIsFinite:
3389 unaryOp = spv::OpIsFinite;
3390 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003391
Rex Xucbc426e2015-12-15 16:03:10 +08003392 case glslang::EOpFloatBitsToInt:
3393 case glslang::EOpFloatBitsToUint:
3394 case glslang::EOpIntBitsToFloat:
3395 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003396 case glslang::EOpDoubleBitsToInt64:
3397 case glslang::EOpDoubleBitsToUint64:
3398 case glslang::EOpInt64BitsToDouble:
3399 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003400 unaryOp = spv::OpBitcast;
3401 break;
3402
John Kessenich140f3df2015-06-26 16:58:36 -06003403 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003404 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003405 break;
3406 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003407 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003408 break;
3409 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003410 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003411 break;
3412 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003413 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003414 break;
3415 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003416 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003417 break;
3418 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003419 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003420 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003421 case glslang::EOpPackSnorm4x8:
3422 libCall = spv::GLSLstd450PackSnorm4x8;
3423 break;
3424 case glslang::EOpUnpackSnorm4x8:
3425 libCall = spv::GLSLstd450UnpackSnorm4x8;
3426 break;
3427 case glslang::EOpPackUnorm4x8:
3428 libCall = spv::GLSLstd450PackUnorm4x8;
3429 break;
3430 case glslang::EOpUnpackUnorm4x8:
3431 libCall = spv::GLSLstd450UnpackUnorm4x8;
3432 break;
3433 case glslang::EOpPackDouble2x32:
3434 libCall = spv::GLSLstd450PackDouble2x32;
3435 break;
3436 case glslang::EOpUnpackDouble2x32:
3437 libCall = spv::GLSLstd450UnpackDouble2x32;
3438 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003439
Rex Xu8ff43de2016-04-22 16:51:45 +08003440 case glslang::EOpPackInt2x32:
3441 case glslang::EOpUnpackInt2x32:
3442 case glslang::EOpPackUint2x32:
3443 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003444 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003445 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3446 break;
3447
John Kessenich140f3df2015-06-26 16:58:36 -06003448 case glslang::EOpDPdx:
3449 unaryOp = spv::OpDPdx;
3450 break;
3451 case glslang::EOpDPdy:
3452 unaryOp = spv::OpDPdy;
3453 break;
3454 case glslang::EOpFwidth:
3455 unaryOp = spv::OpFwidth;
3456 break;
3457 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003458 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003459 unaryOp = spv::OpDPdxFine;
3460 break;
3461 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003462 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003463 unaryOp = spv::OpDPdyFine;
3464 break;
3465 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003466 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003467 unaryOp = spv::OpFwidthFine;
3468 break;
3469 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003470 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003471 unaryOp = spv::OpDPdxCoarse;
3472 break;
3473 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003474 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003475 unaryOp = spv::OpDPdyCoarse;
3476 break;
3477 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003478 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003479 unaryOp = spv::OpFwidthCoarse;
3480 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003481 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003482 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003483 libCall = spv::GLSLstd450InterpolateAtCentroid;
3484 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003485 case glslang::EOpAny:
3486 unaryOp = spv::OpAny;
3487 break;
3488 case glslang::EOpAll:
3489 unaryOp = spv::OpAll;
3490 break;
3491
3492 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003493 if (isFloat)
3494 libCall = spv::GLSLstd450FAbs;
3495 else
3496 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003497 break;
3498 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003499 if (isFloat)
3500 libCall = spv::GLSLstd450FSign;
3501 else
3502 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003503 break;
3504
John Kessenichfc51d282015-08-19 13:34:18 -06003505 case glslang::EOpAtomicCounterIncrement:
3506 case glslang::EOpAtomicCounterDecrement:
3507 case glslang::EOpAtomicCounter:
3508 {
3509 // Handle all of the atomics in one place, in createAtomicOperation()
3510 std::vector<spv::Id> operands;
3511 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003512 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003513 }
3514
John Kessenichfc51d282015-08-19 13:34:18 -06003515 case glslang::EOpBitFieldReverse:
3516 unaryOp = spv::OpBitReverse;
3517 break;
3518 case glslang::EOpBitCount:
3519 unaryOp = spv::OpBitCount;
3520 break;
3521 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003522 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003523 break;
3524 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003525 if (isUnsigned)
3526 libCall = spv::GLSLstd450FindUMsb;
3527 else
3528 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003529 break;
3530
Rex Xu574ab042016-04-14 16:53:07 +08003531 case glslang::EOpBallot:
3532 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003533 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003534 libCall = spv::GLSLstd450Bad;
3535 break;
3536
Rex Xu338b1852016-05-05 20:38:33 +08003537 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003538 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003539 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003540#ifdef AMD_EXTENSIONS
3541 case glslang::EOpMinInvocations:
3542 case glslang::EOpMaxInvocations:
3543 case glslang::EOpAddInvocations:
3544 case glslang::EOpMinInvocationsNonUniform:
3545 case glslang::EOpMaxInvocationsNonUniform:
3546 case glslang::EOpAddInvocationsNonUniform:
3547#endif
3548 return createInvocationsOperation(op, typeId, operand, typeProxy);
3549
3550#ifdef AMD_EXTENSIONS
3551 case glslang::EOpMbcnt:
3552 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3553 libCall = spv::MbcntAMD;
3554 break;
3555
3556 case glslang::EOpCubeFaceIndex:
3557 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3558 libCall = spv::CubeFaceIndexAMD;
3559 break;
3560
3561 case glslang::EOpCubeFaceCoord:
3562 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3563 libCall = spv::CubeFaceCoordAMD;
3564 break;
3565#endif
Rex Xu338b1852016-05-05 20:38:33 +08003566
John Kessenich140f3df2015-06-26 16:58:36 -06003567 default:
3568 return 0;
3569 }
3570
3571 spv::Id id;
3572 if (libCall >= 0) {
3573 std::vector<spv::Id> args;
3574 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003575 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003576 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003577 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003578 }
John Kessenich140f3df2015-06-26 16:58:36 -06003579
qining25262b32016-05-06 17:25:16 -04003580 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003581 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003582}
3583
John Kessenich7a53f762016-01-20 11:19:27 -07003584// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003585spv::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 -07003586{
3587 // Handle unary operations vector by vector.
3588 // The result type is the same type as the original type.
3589 // The algorithm is to:
3590 // - break the matrix into vectors
3591 // - apply the operation to each vector
3592 // - make a matrix out the vector results
3593
3594 // get the types sorted out
3595 int numCols = builder.getNumColumns(operand);
3596 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003597 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3598 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003599 std::vector<spv::Id> results;
3600
3601 // do each vector op
3602 for (int c = 0; c < numCols; ++c) {
3603 std::vector<unsigned int> indexes;
3604 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003605 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3606 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3607 addDecoration(destVec, noContraction);
3608 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003609 }
3610
3611 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003612 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003613}
3614
Rex Xu73e3ce72016-04-27 18:48:17 +08003615spv::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 -06003616{
3617 spv::Op convOp = spv::OpNop;
3618 spv::Id zero = 0;
3619 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003620 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003621
3622 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3623
3624 switch (op) {
3625 case glslang::EOpConvIntToBool:
3626 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003627 case glslang::EOpConvInt64ToBool:
3628 case glslang::EOpConvUint64ToBool:
3629 zero = (op == glslang::EOpConvInt64ToBool ||
3630 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003631 zero = makeSmearedConstant(zero, vectorSize);
3632 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3633
3634 case glslang::EOpConvFloatToBool:
3635 zero = builder.makeFloatConstant(0.0F);
3636 zero = makeSmearedConstant(zero, vectorSize);
3637 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3638
3639 case glslang::EOpConvDoubleToBool:
3640 zero = builder.makeDoubleConstant(0.0);
3641 zero = makeSmearedConstant(zero, vectorSize);
3642 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3643
3644 case glslang::EOpConvBoolToFloat:
3645 convOp = spv::OpSelect;
3646 zero = builder.makeFloatConstant(0.0);
3647 one = builder.makeFloatConstant(1.0);
3648 break;
3649 case glslang::EOpConvBoolToDouble:
3650 convOp = spv::OpSelect;
3651 zero = builder.makeDoubleConstant(0.0);
3652 one = builder.makeDoubleConstant(1.0);
3653 break;
3654 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003655 case glslang::EOpConvBoolToInt64:
3656 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3657 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003658 convOp = spv::OpSelect;
3659 break;
3660 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003661 case glslang::EOpConvBoolToUint64:
3662 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3663 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003664 convOp = spv::OpSelect;
3665 break;
3666
3667 case glslang::EOpConvIntToFloat:
3668 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003669 case glslang::EOpConvInt64ToFloat:
3670 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003671 convOp = spv::OpConvertSToF;
3672 break;
3673
3674 case glslang::EOpConvUintToFloat:
3675 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003676 case glslang::EOpConvUint64ToFloat:
3677 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003678 convOp = spv::OpConvertUToF;
3679 break;
3680
3681 case glslang::EOpConvDoubleToFloat:
3682 case glslang::EOpConvFloatToDouble:
3683 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003684 if (builder.isMatrixType(destType))
3685 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003686 break;
3687
3688 case glslang::EOpConvFloatToInt:
3689 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003690 case glslang::EOpConvFloatToInt64:
3691 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003692 convOp = spv::OpConvertFToS;
3693 break;
3694
3695 case glslang::EOpConvUintToInt:
3696 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003697 case glslang::EOpConvUint64ToInt64:
3698 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003699 if (builder.isInSpecConstCodeGenMode()) {
3700 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003701 zero = (op == glslang::EOpConvUintToInt64 ||
3702 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003703 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003704 // Use OpIAdd, instead of OpBitcast to do the conversion when
3705 // generating for OpSpecConstantOp instruction.
3706 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3707 }
3708 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003709 convOp = spv::OpBitcast;
3710 break;
3711
3712 case glslang::EOpConvFloatToUint:
3713 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003714 case glslang::EOpConvFloatToUint64:
3715 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003716 convOp = spv::OpConvertFToU;
3717 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003718
3719 case glslang::EOpConvIntToInt64:
3720 case glslang::EOpConvInt64ToInt:
3721 convOp = spv::OpSConvert;
3722 break;
3723
3724 case glslang::EOpConvUintToUint64:
3725 case glslang::EOpConvUint64ToUint:
3726 convOp = spv::OpUConvert;
3727 break;
3728
3729 case glslang::EOpConvIntToUint64:
3730 case glslang::EOpConvInt64ToUint:
3731 case glslang::EOpConvUint64ToInt:
3732 case glslang::EOpConvUintToInt64:
3733 // OpSConvert/OpUConvert + OpBitCast
3734 switch (op) {
3735 case glslang::EOpConvIntToUint64:
3736 convOp = spv::OpSConvert;
3737 type = builder.makeIntType(64);
3738 break;
3739 case glslang::EOpConvInt64ToUint:
3740 convOp = spv::OpSConvert;
3741 type = builder.makeIntType(32);
3742 break;
3743 case glslang::EOpConvUint64ToInt:
3744 convOp = spv::OpUConvert;
3745 type = builder.makeUintType(32);
3746 break;
3747 case glslang::EOpConvUintToInt64:
3748 convOp = spv::OpUConvert;
3749 type = builder.makeUintType(64);
3750 break;
3751 default:
3752 assert(0);
3753 break;
3754 }
3755
3756 if (vectorSize > 0)
3757 type = builder.makeVectorType(type, vectorSize);
3758
3759 operand = builder.createUnaryOp(convOp, type, operand);
3760
3761 if (builder.isInSpecConstCodeGenMode()) {
3762 // Build zero scalar or vector for OpIAdd.
3763 zero = (op == glslang::EOpConvIntToUint64 ||
3764 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3765 zero = makeSmearedConstant(zero, vectorSize);
3766 // Use OpIAdd, instead of OpBitcast to do the conversion when
3767 // generating for OpSpecConstantOp instruction.
3768 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3769 }
3770 // For normal run-time conversion instruction, use OpBitcast.
3771 convOp = spv::OpBitcast;
3772 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003773 default:
3774 break;
3775 }
3776
3777 spv::Id result = 0;
3778 if (convOp == spv::OpNop)
3779 return result;
3780
3781 if (convOp == spv::OpSelect) {
3782 zero = makeSmearedConstant(zero, vectorSize);
3783 one = makeSmearedConstant(one, vectorSize);
3784 result = builder.createTriOp(convOp, destType, operand, one, zero);
3785 } else
3786 result = builder.createUnaryOp(convOp, destType, operand);
3787
John Kessenich32cfd492016-02-02 12:37:46 -07003788 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003789}
3790
3791spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3792{
3793 if (vectorSize == 0)
3794 return constant;
3795
3796 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3797 std::vector<spv::Id> components;
3798 for (int c = 0; c < vectorSize; ++c)
3799 components.push_back(constant);
3800 return builder.makeCompositeConstant(vectorTypeId, components);
3801}
3802
John Kessenich426394d2015-07-23 10:22:48 -06003803// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003804spv::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 -06003805{
3806 spv::Op opCode = spv::OpNop;
3807
3808 switch (op) {
3809 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003810 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003811 opCode = spv::OpAtomicIAdd;
3812 break;
3813 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003814 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003815 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003816 break;
3817 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003818 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003819 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003820 break;
3821 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003822 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003823 opCode = spv::OpAtomicAnd;
3824 break;
3825 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003826 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003827 opCode = spv::OpAtomicOr;
3828 break;
3829 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003830 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003831 opCode = spv::OpAtomicXor;
3832 break;
3833 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003834 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003835 opCode = spv::OpAtomicExchange;
3836 break;
3837 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003838 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003839 opCode = spv::OpAtomicCompareExchange;
3840 break;
3841 case glslang::EOpAtomicCounterIncrement:
3842 opCode = spv::OpAtomicIIncrement;
3843 break;
3844 case glslang::EOpAtomicCounterDecrement:
3845 opCode = spv::OpAtomicIDecrement;
3846 break;
3847 case glslang::EOpAtomicCounter:
3848 opCode = spv::OpAtomicLoad;
3849 break;
3850 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003851 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003852 break;
3853 }
3854
3855 // Sort out the operands
3856 // - mapping from glslang -> SPV
3857 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003858 // - compare-exchange swaps the value and comparator
3859 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003860 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3861 auto opIt = operands.begin(); // walk the glslang operands
3862 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003863 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3864 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3865 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003866 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3867 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003868 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003869 spvAtomicOperands.push_back(*(opIt + 1));
3870 spvAtomicOperands.push_back(*opIt);
3871 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003872 }
John Kessenich426394d2015-07-23 10:22:48 -06003873
John Kessenich3e60a6f2015-09-14 22:45:16 -06003874 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003875 for (; opIt != operands.end(); ++opIt)
3876 spvAtomicOperands.push_back(*opIt);
3877
3878 return builder.createOp(opCode, typeId, spvAtomicOperands);
3879}
3880
John Kessenich91cef522016-05-05 16:45:40 -06003881// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003882spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003883{
Rex Xu9d93a232016-05-05 12:30:44 +08003884 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3885 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3886
John Kessenich91cef522016-05-05 16:45:40 -06003887 builder.addCapability(spv::CapabilityGroups);
3888
3889 std::vector<spv::Id> operands;
3890 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003891#ifdef AMD_EXTENSIONS
3892 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3893 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3894 operands.push_back(spv::GroupOperationReduce);
3895#endif
John Kessenich91cef522016-05-05 16:45:40 -06003896 operands.push_back(operand);
3897
3898 switch (op) {
3899 case glslang::EOpAnyInvocation:
3900 case glslang::EOpAllInvocations:
3901 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3902
3903 case glslang::EOpAllInvocationsEqual:
3904 {
3905 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3906 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3907
3908 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3909 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3910 }
Rex Xu9d93a232016-05-05 12:30:44 +08003911#ifdef AMD_EXTENSIONS
3912 case glslang::EOpMinInvocations:
3913 case glslang::EOpMaxInvocations:
3914 case glslang::EOpAddInvocations:
3915 {
3916 spv::Op spvOp = spv::OpNop;
3917 if (op == glslang::EOpMinInvocations) {
3918 if (isFloat)
3919 spvOp = spv::OpGroupFMin;
3920 else {
3921 if (isUnsigned)
3922 spvOp = spv::OpGroupUMin;
3923 else
3924 spvOp = spv::OpGroupSMin;
3925 }
3926 } else if (op == glslang::EOpMaxInvocations) {
3927 if (isFloat)
3928 spvOp = spv::OpGroupFMax;
3929 else {
3930 if (isUnsigned)
3931 spvOp = spv::OpGroupUMax;
3932 else
3933 spvOp = spv::OpGroupSMax;
3934 }
3935 } else {
3936 if (isFloat)
3937 spvOp = spv::OpGroupFAdd;
3938 else
3939 spvOp = spv::OpGroupIAdd;
3940 }
3941
3942 return builder.createOp(spvOp, typeId, operands);
3943 }
3944 case glslang::EOpMinInvocationsNonUniform:
3945 case glslang::EOpMaxInvocationsNonUniform:
3946 case glslang::EOpAddInvocationsNonUniform:
3947 {
3948 spv::Op spvOp = spv::OpNop;
3949 if (op == glslang::EOpMinInvocationsNonUniform) {
3950 if (isFloat)
3951 spvOp = spv::OpGroupFMinNonUniformAMD;
3952 else {
3953 if (isUnsigned)
3954 spvOp = spv::OpGroupUMinNonUniformAMD;
3955 else
3956 spvOp = spv::OpGroupSMinNonUniformAMD;
3957 }
3958 }
3959 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3960 if (isFloat)
3961 spvOp = spv::OpGroupFMaxNonUniformAMD;
3962 else {
3963 if (isUnsigned)
3964 spvOp = spv::OpGroupUMaxNonUniformAMD;
3965 else
3966 spvOp = spv::OpGroupSMaxNonUniformAMD;
3967 }
3968 }
3969 else {
3970 if (isFloat)
3971 spvOp = spv::OpGroupFAddNonUniformAMD;
3972 else
3973 spvOp = spv::OpGroupIAddNonUniformAMD;
3974 }
3975
3976 return builder.createOp(spvOp, typeId, operands);
3977 }
3978#endif
John Kessenich91cef522016-05-05 16:45:40 -06003979 default:
3980 logger->missingFunctionality("invocation operation");
3981 return spv::NoResult;
3982 }
3983}
3984
John Kessenich5e4b1242015-08-06 22:53:06 -06003985spv::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 -06003986{
Rex Xu8ff43de2016-04-22 16:51:45 +08003987 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003988 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3989
John Kessenich140f3df2015-06-26 16:58:36 -06003990 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003991 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003992 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003993 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003994 spv::Id typeId0 = 0;
3995 if (consumedOperands > 0)
3996 typeId0 = builder.getTypeId(operands[0]);
3997 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003998
3999 switch (op) {
4000 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004001 if (isFloat)
4002 libCall = spv::GLSLstd450FMin;
4003 else if (isUnsigned)
4004 libCall = spv::GLSLstd450UMin;
4005 else
4006 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004007 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004008 break;
4009 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004010 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004011 break;
4012 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004013 if (isFloat)
4014 libCall = spv::GLSLstd450FMax;
4015 else if (isUnsigned)
4016 libCall = spv::GLSLstd450UMax;
4017 else
4018 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004019 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004020 break;
4021 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004022 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004023 break;
4024 case glslang::EOpDot:
4025 opCode = spv::OpDot;
4026 break;
4027 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004028 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004029 break;
4030
4031 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004032 if (isFloat)
4033 libCall = spv::GLSLstd450FClamp;
4034 else if (isUnsigned)
4035 libCall = spv::GLSLstd450UClamp;
4036 else
4037 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004038 builder.promoteScalar(precision, operands.front(), operands[1]);
4039 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004040 break;
4041 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004042 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4043 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004044 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004045 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004046 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004047 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004048 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004049 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004052 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004053 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004054 break;
4055 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004057 builder.promoteScalar(precision, operands[0], operands[2]);
4058 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004059 break;
4060
4061 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004076 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004077 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004078 libCall = spv::GLSLstd450InterpolateAtSample;
4079 break;
4080 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004081 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004082 libCall = spv::GLSLstd450InterpolateAtOffset;
4083 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004084 case glslang::EOpAddCarry:
4085 opCode = spv::OpIAddCarry;
4086 typeId = builder.makeStructResultType(typeId0, typeId0);
4087 consumedOperands = 2;
4088 break;
4089 case glslang::EOpSubBorrow:
4090 opCode = spv::OpISubBorrow;
4091 typeId = builder.makeStructResultType(typeId0, typeId0);
4092 consumedOperands = 2;
4093 break;
4094 case glslang::EOpUMulExtended:
4095 opCode = spv::OpUMulExtended;
4096 typeId = builder.makeStructResultType(typeId0, typeId0);
4097 consumedOperands = 2;
4098 break;
4099 case glslang::EOpIMulExtended:
4100 opCode = spv::OpSMulExtended;
4101 typeId = builder.makeStructResultType(typeId0, typeId0);
4102 consumedOperands = 2;
4103 break;
4104 case glslang::EOpBitfieldExtract:
4105 if (isUnsigned)
4106 opCode = spv::OpBitFieldUExtract;
4107 else
4108 opCode = spv::OpBitFieldSExtract;
4109 break;
4110 case glslang::EOpBitfieldInsert:
4111 opCode = spv::OpBitFieldInsert;
4112 break;
4113
4114 case glslang::EOpFma:
4115 libCall = spv::GLSLstd450Fma;
4116 break;
4117 case glslang::EOpFrexp:
4118 libCall = spv::GLSLstd450FrexpStruct;
4119 if (builder.getNumComponents(operands[0]) == 1)
4120 frexpIntType = builder.makeIntegerType(32, true);
4121 else
4122 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4123 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4124 consumedOperands = 1;
4125 break;
4126 case glslang::EOpLdexp:
4127 libCall = spv::GLSLstd450Ldexp;
4128 break;
4129
Rex Xu574ab042016-04-14 16:53:07 +08004130 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004131 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004132 libCall = spv::GLSLstd450Bad;
4133 break;
4134
Rex Xu9d93a232016-05-05 12:30:44 +08004135#ifdef AMD_EXTENSIONS
4136 case glslang::EOpSwizzleInvocations:
4137 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4138 libCall = spv::SwizzleInvocationsAMD;
4139 break;
4140 case glslang::EOpSwizzleInvocationsMasked:
4141 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4142 libCall = spv::SwizzleInvocationsMaskedAMD;
4143 break;
4144 case glslang::EOpWriteInvocation:
4145 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4146 libCall = spv::WriteInvocationAMD;
4147 break;
4148
4149 case glslang::EOpMin3:
4150 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4151 if (isFloat)
4152 libCall = spv::FMin3AMD;
4153 else {
4154 if (isUnsigned)
4155 libCall = spv::UMin3AMD;
4156 else
4157 libCall = spv::SMin3AMD;
4158 }
4159 break;
4160 case glslang::EOpMax3:
4161 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4162 if (isFloat)
4163 libCall = spv::FMax3AMD;
4164 else {
4165 if (isUnsigned)
4166 libCall = spv::UMax3AMD;
4167 else
4168 libCall = spv::SMax3AMD;
4169 }
4170 break;
4171 case glslang::EOpMid3:
4172 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4173 if (isFloat)
4174 libCall = spv::FMid3AMD;
4175 else {
4176 if (isUnsigned)
4177 libCall = spv::UMid3AMD;
4178 else
4179 libCall = spv::SMid3AMD;
4180 }
4181 break;
4182
4183 case glslang::EOpInterpolateAtVertex:
4184 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4185 libCall = spv::InterpolateAtVertexAMD;
4186 break;
4187#endif
4188
John Kessenich140f3df2015-06-26 16:58:36 -06004189 default:
4190 return 0;
4191 }
4192
4193 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004194 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004195 // Use an extended instruction from the standard library.
4196 // Construct the call arguments, without modifying the original operands vector.
4197 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4198 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004199 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004200 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004201 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004202 case 0:
4203 // should all be handled by visitAggregate and createNoArgOperation
4204 assert(0);
4205 return 0;
4206 case 1:
4207 // should all be handled by createUnaryOperation
4208 assert(0);
4209 return 0;
4210 case 2:
4211 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4212 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004213 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004214 // anything 3 or over doesn't have l-value operands, so all should be consumed
4215 assert(consumedOperands == operands.size());
4216 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004217 break;
4218 }
4219 }
4220
John Kessenich55e7d112015-11-15 21:33:39 -07004221 // Decode the return types that were structures
4222 switch (op) {
4223 case glslang::EOpAddCarry:
4224 case glslang::EOpSubBorrow:
4225 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4226 id = builder.createCompositeExtract(id, typeId0, 0);
4227 break;
4228 case glslang::EOpUMulExtended:
4229 case glslang::EOpIMulExtended:
4230 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4231 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4232 break;
4233 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004234 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004235 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4236 id = builder.createCompositeExtract(id, typeId0, 0);
4237 break;
4238 default:
4239 break;
4240 }
4241
John Kessenich32cfd492016-02-02 12:37:46 -07004242 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004243}
4244
Rex Xu9d93a232016-05-05 12:30:44 +08004245// Intrinsics with no arguments (or no return value, and no precision).
4246spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004247{
4248 // TODO: get the barrier operands correct
4249
4250 switch (op) {
4251 case glslang::EOpEmitVertex:
4252 builder.createNoResultOp(spv::OpEmitVertex);
4253 return 0;
4254 case glslang::EOpEndPrimitive:
4255 builder.createNoResultOp(spv::OpEndPrimitive);
4256 return 0;
4257 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004258 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004259 return 0;
4260 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004261 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004262 return 0;
4263 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004264 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004265 return 0;
4266 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004267 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004268 return 0;
4269 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004270 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004271 return 0;
4272 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004273 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004274 return 0;
4275 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004276 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004277 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004278 case glslang::EOpAllMemoryBarrierWithGroupSync:
4279 // Control barrier with non-"None" semantic is also a memory barrier.
4280 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4281 return 0;
4282 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4283 // Control barrier with non-"None" semantic is also a memory barrier.
4284 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4285 return 0;
4286 case glslang::EOpWorkgroupMemoryBarrier:
4287 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4288 return 0;
4289 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4290 // Control barrier with non-"None" semantic is also a memory barrier.
4291 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4292 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004293#ifdef AMD_EXTENSIONS
4294 case glslang::EOpTime:
4295 {
4296 std::vector<spv::Id> args; // Dummy arguments
4297 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4298 return builder.setPrecision(id, precision);
4299 }
4300#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004301 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004302 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004303 return 0;
4304 }
4305}
4306
4307spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4308{
John Kessenich2f273362015-07-18 22:34:27 -06004309 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004310 spv::Id id;
4311 if (symbolValues.end() != iter) {
4312 id = iter->second;
4313 return id;
4314 }
4315
4316 // it was not found, create it
4317 id = createSpvVariable(symbol);
4318 symbolValues[symbol->getId()] = id;
4319
Rex Xuc884b4a2016-06-29 15:03:44 +08004320 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004321 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004322 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004323 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004324 if (symbol->getType().getQualifier().hasSpecConstantId())
4325 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004326 if (symbol->getQualifier().hasIndex())
4327 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4328 if (symbol->getQualifier().hasComponent())
4329 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4330 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004331 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004332 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004333 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004334 if (symbol->getQualifier().hasXfbBuffer())
4335 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4336 if (symbol->getQualifier().hasXfbOffset())
4337 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4338 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004339 // atomic counters use this:
4340 if (symbol->getQualifier().hasOffset())
4341 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004342 }
4343
scygan2c864272016-05-18 18:09:17 +02004344 if (symbol->getQualifier().hasLocation())
4345 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004346 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004347 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004348 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004349 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004350 }
John Kessenich140f3df2015-06-26 16:58:36 -06004351 if (symbol->getQualifier().hasSet())
4352 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004353 else if (IsDescriptorResource(symbol->getType())) {
4354 // default to 0
4355 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4356 }
John Kessenich140f3df2015-06-26 16:58:36 -06004357 if (symbol->getQualifier().hasBinding())
4358 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004359 if (symbol->getQualifier().hasAttachment())
4360 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004361 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004362 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004363 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004364 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004365 if (symbol->getQualifier().hasXfbBuffer())
4366 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4367 }
4368
Rex Xu1da878f2016-02-21 20:59:01 +08004369 if (symbol->getType().isImage()) {
4370 std::vector<spv::Decoration> memory;
4371 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4372 for (unsigned int i = 0; i < memory.size(); ++i)
4373 addDecoration(id, memory[i]);
4374 }
4375
John Kessenich140f3df2015-06-26 16:58:36 -06004376 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004377 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004378 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004379 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004380
John Kessenich140f3df2015-06-26 16:58:36 -06004381 return id;
4382}
4383
John Kessenich55e7d112015-11-15 21:33:39 -07004384// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004385void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4386{
John Kessenich4016e382016-07-15 11:53:56 -06004387 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004388 builder.addDecoration(id, dec);
4389}
4390
John Kessenich55e7d112015-11-15 21:33:39 -07004391// If 'dec' is valid, add a one-operand decoration to an object
4392void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4393{
John Kessenich4016e382016-07-15 11:53:56 -06004394 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004395 builder.addDecoration(id, dec, value);
4396}
4397
4398// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004399void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4400{
John Kessenich4016e382016-07-15 11:53:56 -06004401 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004402 builder.addMemberDecoration(id, (unsigned)member, dec);
4403}
4404
John Kessenich92187592016-02-01 13:45:25 -07004405// If 'dec' is valid, add a one-operand decoration to a struct member
4406void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4407{
John Kessenich4016e382016-07-15 11:53:56 -06004408 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004409 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4410}
4411
John Kessenich55e7d112015-11-15 21:33:39 -07004412// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004413// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004414//
4415// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4416//
4417// Recursively walk the nodes. The nodes form a tree whose leaves are
4418// regular constants, which themselves are trees that createSpvConstant()
4419// recursively walks. So, this function walks the "top" of the tree:
4420// - emit specialization constant-building instructions for specConstant
4421// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004422spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004423{
John Kessenich7cc0e282016-03-20 00:46:02 -06004424 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004425
qining4f4bb812016-04-03 23:55:17 -04004426 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004427 if (! node.getQualifier().specConstant) {
4428 // hand off to the non-spec-constant path
4429 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4430 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004431 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004432 nextConst, false);
4433 }
4434
4435 // We now know we have a specialization constant to build
4436
John Kessenichd94c0032016-05-30 19:29:40 -06004437 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004438 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4439 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4440 std::vector<spv::Id> dimConstId;
4441 for (int dim = 0; dim < 3; ++dim) {
4442 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4443 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4444 if (specConst)
4445 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4446 }
4447 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4448 }
4449
4450 // An AST node labelled as specialization constant should be a symbol node.
4451 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4452 if (auto* sn = node.getAsSymbolNode()) {
4453 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004454 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4455 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4456 // will set the builder into spec constant op instruction generating mode.
4457 sub_tree->traverse(this);
4458 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004459 } else if (auto* const_union_array = &sn->getConstArray()){
4460 int nextConst = 0;
4461 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004462 }
4463 }
qining4f4bb812016-04-03 23:55:17 -04004464
4465 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4466 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004467 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004468 exit(1);
4469 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004470}
4471
John Kessenich140f3df2015-06-26 16:58:36 -06004472// Use 'consts' as the flattened glslang source of scalar constants to recursively
4473// build the aggregate SPIR-V constant.
4474//
4475// If there are not enough elements present in 'consts', 0 will be substituted;
4476// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4477//
qining08408382016-03-21 09:51:37 -04004478spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004479{
4480 // vector of constants for SPIR-V
4481 std::vector<spv::Id> spvConsts;
4482
4483 // Type is used for struct and array constants
4484 spv::Id typeId = convertGlslangToSpvType(glslangType);
4485
4486 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004487 glslang::TType elementType(glslangType, 0);
4488 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004489 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004490 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004491 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004492 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004493 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004494 } else if (glslangType.getStruct()) {
4495 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4496 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004497 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004498 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004499 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4500 bool zero = nextConst >= consts.size();
4501 switch (glslangType.getBasicType()) {
4502 case glslang::EbtInt:
4503 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4504 break;
4505 case glslang::EbtUint:
4506 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4507 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004508 case glslang::EbtInt64:
4509 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4510 break;
4511 case glslang::EbtUint64:
4512 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4513 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004514 case glslang::EbtFloat:
4515 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4516 break;
4517 case glslang::EbtDouble:
4518 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4519 break;
4520 case glslang::EbtBool:
4521 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4522 break;
4523 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004524 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004525 break;
4526 }
4527 ++nextConst;
4528 }
4529 } else {
4530 // we have a non-aggregate (scalar) constant
4531 bool zero = nextConst >= consts.size();
4532 spv::Id scalar = 0;
4533 switch (glslangType.getBasicType()) {
4534 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004535 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004536 break;
4537 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004538 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004539 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004540 case glslang::EbtInt64:
4541 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4542 break;
4543 case glslang::EbtUint64:
4544 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4545 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004546 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004547 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004548 break;
4549 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004550 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004551 break;
4552 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004553 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004554 break;
4555 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004556 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004557 break;
4558 }
4559 ++nextConst;
4560 return scalar;
4561 }
4562
4563 return builder.makeCompositeConstant(typeId, spvConsts);
4564}
4565
John Kessenich7c1aa102015-10-15 13:29:11 -06004566// Return true if the node is a constant or symbol whose reading has no
4567// non-trivial observable cost or effect.
4568bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4569{
4570 // don't know what this is
4571 if (node == nullptr)
4572 return false;
4573
4574 // a constant is safe
4575 if (node->getAsConstantUnion() != nullptr)
4576 return true;
4577
4578 // not a symbol means non-trivial
4579 if (node->getAsSymbolNode() == nullptr)
4580 return false;
4581
4582 // a symbol, depends on what's being read
4583 switch (node->getType().getQualifier().storage) {
4584 case glslang::EvqTemporary:
4585 case glslang::EvqGlobal:
4586 case glslang::EvqIn:
4587 case glslang::EvqInOut:
4588 case glslang::EvqConst:
4589 case glslang::EvqConstReadOnly:
4590 case glslang::EvqUniform:
4591 return true;
4592 default:
4593 return false;
4594 }
qining25262b32016-05-06 17:25:16 -04004595}
John Kessenich7c1aa102015-10-15 13:29:11 -06004596
4597// A node is trivial if it is a single operation with no side effects.
4598// Error on the side of saying non-trivial.
4599// Return true if trivial.
4600bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4601{
4602 if (node == nullptr)
4603 return false;
4604
4605 // symbols and constants are trivial
4606 if (isTrivialLeaf(node))
4607 return true;
4608
4609 // otherwise, it needs to be a simple operation or one or two leaf nodes
4610
4611 // not a simple operation
4612 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4613 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4614 if (binaryNode == nullptr && unaryNode == nullptr)
4615 return false;
4616
4617 // not on leaf nodes
4618 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4619 return false;
4620
4621 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4622 return false;
4623 }
4624
4625 switch (node->getAsOperator()->getOp()) {
4626 case glslang::EOpLogicalNot:
4627 case glslang::EOpConvIntToBool:
4628 case glslang::EOpConvUintToBool:
4629 case glslang::EOpConvFloatToBool:
4630 case glslang::EOpConvDoubleToBool:
4631 case glslang::EOpEqual:
4632 case glslang::EOpNotEqual:
4633 case glslang::EOpLessThan:
4634 case glslang::EOpGreaterThan:
4635 case glslang::EOpLessThanEqual:
4636 case glslang::EOpGreaterThanEqual:
4637 case glslang::EOpIndexDirect:
4638 case glslang::EOpIndexDirectStruct:
4639 case glslang::EOpLogicalXor:
4640 case glslang::EOpAny:
4641 case glslang::EOpAll:
4642 return true;
4643 default:
4644 return false;
4645 }
4646}
4647
4648// Emit short-circuiting code, where 'right' is never evaluated unless
4649// the left side is true (for &&) or false (for ||).
4650spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4651{
4652 spv::Id boolTypeId = builder.makeBoolType();
4653
4654 // emit left operand
4655 builder.clearAccessChain();
4656 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004657 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004658
4659 // Operands to accumulate OpPhi operands
4660 std::vector<spv::Id> phiOperands;
4661 // accumulate left operand's phi information
4662 phiOperands.push_back(leftId);
4663 phiOperands.push_back(builder.getBuildPoint()->getId());
4664
4665 // Make the two kinds of operation symmetric with a "!"
4666 // || => emit "if (! left) result = right"
4667 // && => emit "if ( left) result = right"
4668 //
4669 // TODO: this runtime "not" for || could be avoided by adding functionality
4670 // to 'builder' to have an "else" without an "then"
4671 if (op == glslang::EOpLogicalOr)
4672 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4673
4674 // make an "if" based on the left value
4675 spv::Builder::If ifBuilder(leftId, builder);
4676
4677 // emit right operand as the "then" part of the "if"
4678 builder.clearAccessChain();
4679 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004680 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004681
4682 // accumulate left operand's phi information
4683 phiOperands.push_back(rightId);
4684 phiOperands.push_back(builder.getBuildPoint()->getId());
4685
4686 // finish the "if"
4687 ifBuilder.makeEndIf();
4688
4689 // phi together the two results
4690 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4691}
4692
Rex Xu9d93a232016-05-05 12:30:44 +08004693// Return type Id of the imported set of extended instructions corresponds to the name.
4694// Import this set if it has not been imported yet.
4695spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4696{
4697 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4698 return extBuiltinMap[name];
4699 else {
4700 builder.addExtensions(name);
4701 spv::Id extBuiltins = builder.import(name);
4702 extBuiltinMap[name] = extBuiltins;
4703 return extBuiltins;
4704 }
4705}
4706
John Kessenich140f3df2015-06-26 16:58:36 -06004707}; // end anonymous namespace
4708
4709namespace glslang {
4710
John Kessenich68d78fd2015-07-12 19:28:10 -06004711void GetSpirvVersion(std::string& version)
4712{
John Kessenich9e55f632015-07-15 10:03:39 -06004713 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004714 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004715 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004716 version = buf;
4717}
4718
John Kessenich140f3df2015-06-26 16:58:36 -06004719// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004720void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004721{
4722 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004723 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004724 for (int i = 0; i < (int)spirv.size(); ++i) {
4725 unsigned int word = spirv[i];
4726 out.write((const char*)&word, 4);
4727 }
4728 out.close();
4729}
4730
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004731// Write SPIR-V out to a text file with 32-bit hexadecimal words
4732void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4733{
4734 std::ofstream out;
4735 out.open(baseName, std::ios::binary | std::ios::out);
4736 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4737 const int WORDS_PER_LINE = 8;
4738 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4739 out << "\t";
4740 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4741 const unsigned int word = spirv[i + j];
4742 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4743 if (i + j + 1 < (int)spirv.size()) {
4744 out << ",";
4745 }
4746 }
4747 out << std::endl;
4748 }
4749 out.close();
4750}
4751
John Kessenich140f3df2015-06-26 16:58:36 -06004752//
4753// Set up the glslang traversal
4754//
4755void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4756{
Lei Zhang17535f72016-05-04 15:55:59 -04004757 spv::SpvBuildLogger logger;
4758 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004759}
4760
Lei Zhang17535f72016-05-04 15:55:59 -04004761void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004762{
John Kessenich140f3df2015-06-26 16:58:36 -06004763 TIntermNode* root = intermediate.getTreeRoot();
4764
4765 if (root == 0)
4766 return;
4767
4768 glslang::GetThreadPoolAllocator().push();
4769
Lei Zhang17535f72016-05-04 15:55:59 -04004770 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004771
4772 root->traverse(&it);
4773
4774 it.dumpSpv(spirv);
4775
4776 glslang::GetThreadPoolAllocator().pop();
4777}
4778
4779}; // end namespace glslang