blob: 26d2f4bc0d7666de306e79e259a9d1d5b724b44f [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
286// Translate glslang type to SPIR-V precision decorations.
287spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
288{
289 switch (type.getQualifier().precision) {
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
297// Translate glslang type to SPIR-V block decorations.
298spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
299{
300 if (type.getBasicType() == glslang::EbtBlock) {
301 switch (type.getQualifier().storage) {
302 case glslang::EvqUniform: return spv::DecorationBlock;
303 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
304 case glslang::EvqVaryingIn: return spv::DecorationBlock;
305 case glslang::EvqVaryingOut: return spv::DecorationBlock;
306 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600308 break;
309 }
310 }
311
John Kessenich4016e382016-07-15 11:53:56 -0600312 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600313}
314
Rex Xu1da878f2016-02-21 20:59:01 +0800315// Translate glslang type to SPIR-V memory decorations.
316void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
317{
318 if (qualifier.coherent)
319 memory.push_back(spv::DecorationCoherent);
320 if (qualifier.volatil)
321 memory.push_back(spv::DecorationVolatile);
322 if (qualifier.restrict)
323 memory.push_back(spv::DecorationRestrict);
324 if (qualifier.readonly)
325 memory.push_back(spv::DecorationNonWritable);
326 if (qualifier.writeonly)
327 memory.push_back(spv::DecorationNonReadable);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700331spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::ElmRowMajor:
336 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700339 default:
340 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 }
343 } else {
344 switch (type.getBasicType()) {
345 default:
John Kessenich4016e382016-07-15 11:53:56 -0600346 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 break;
348 case glslang::EbtBlock:
349 switch (type.getQualifier().storage) {
350 case glslang::EvqUniform:
351 case glslang::EvqBuffer:
352 switch (type.getQualifier().layoutPacking) {
353 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 case glslang::EvqVaryingIn:
359 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700360 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700363 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 }
366 }
367 }
368}
369
370// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600371// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700372// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800373spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
Rex Xubbceed72016-05-21 09:40:44 +0800375 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700376 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700379 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800382#ifdef AMD_EXTENSIONS
383 else if (qualifier.explicitInterp)
384 return spv::DecorationExplicitInterpAMD;
385#endif
Rex Xubbceed72016-05-21 09:40:44 +0800386 else
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388}
389
390// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600391// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800392// should be applied.
393spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
394{
395 if (qualifier.patch)
396 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700399 else if (qualifier.sample) {
400 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600401 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700402 } else
John Kessenich4016e382016-07-15 11:53:56 -0600403 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600404}
405
John Kessenich92187592016-02-01 13:45:25 -0700406// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600408{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600410 return spv::DecorationInvariant;
411 else
John Kessenich4016e382016-07-15 11:53:56 -0600412 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600413}
414
qining9220dbb2016-05-04 17:34:38 -0400415// If glslang type is noContraction, return SPIR-V NoContraction decoration.
416spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
417{
418 if (qualifier.noContraction)
419 return spv::DecorationNoContraction;
420 else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400422}
423
David Netoa901ffe2016-06-08 14:11:40 +0100424// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
425// associated capabilities when required. For some built-in variables, a capability
426// is generated only when using the variable in an executable instruction, but not when
427// just declaring a struct member variable with it. This is true for PointSize,
428// ClipDistance, and CullDistance.
429spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600430{
431 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700432 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600433 // Defer adding the capability until the built-in is actually used.
434 if (! memberDeclaration) {
435 switch (glslangIntermediate->getStage()) {
436 case EShLangGeometry:
437 builder.addCapability(spv::CapabilityGeometryPointSize);
438 break;
439 case EShLangTessControl:
440 case EShLangTessEvaluation:
441 builder.addCapability(spv::CapabilityTessellationPointSize);
442 break;
443 default:
444 break;
445 }
John Kessenich92187592016-02-01 13:45:25 -0700446 }
447 return spv::BuiltInPointSize;
448
John Kessenichebb50532016-05-16 19:22:05 -0600449 // These *Distance capabilities logically belong here, but if the member is declared and
450 // then never used, consumers of SPIR-V prefer the capability not be declared.
451 // They are now generated when used, rather than here when declared.
452 // Potentially, the specification should be more clear what the minimum
453 // use needed is to trigger the capability.
454 //
John Kessenich92187592016-02-01 13:45:25 -0700455 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100456 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600457 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700458 return spv::BuiltInClipDistance;
459
460 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100461 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600462 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700463 return spv::BuiltInCullDistance;
464
465 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500466 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700467 return spv::BuiltInViewportIndex;
468
John Kessenich5e801132016-02-15 11:09:46 -0700469 case glslang::EbvSampleId:
470 builder.addCapability(spv::CapabilitySampleRateShading);
471 return spv::BuiltInSampleId;
472
473 case glslang::EbvSamplePosition:
474 builder.addCapability(spv::CapabilitySampleRateShading);
475 return spv::BuiltInSamplePosition;
476
477 case glslang::EbvSampleMask:
478 builder.addCapability(spv::CapabilitySampleRateShading);
479 return spv::BuiltInSampleMask;
480
John Kessenich78a45572016-07-08 14:05:15 -0600481 case glslang::EbvLayer:
482 builder.addCapability(spv::CapabilityGeometry);
483 return spv::BuiltInLayer;
484
John Kessenich140f3df2015-06-26 16:58:36 -0600485 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600486 case glslang::EbvVertexId: return spv::BuiltInVertexId;
487 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700488 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
489 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600490 case glslang::EbvBaseVertex:
491 case glslang::EbvBaseInstance:
492 case glslang::EbvDrawId:
493 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600494 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600495 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
497 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
499 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
500 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
501 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
502 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
503 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
504 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600505 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
506 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
507 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
508 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
509 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
510 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
511 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
512 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800513 case glslang::EbvSubGroupSize:
514 case glslang::EbvSubGroupInvocation:
515 case glslang::EbvSubGroupEqMask:
516 case glslang::EbvSubGroupGeMask:
517 case glslang::EbvSubGroupGtMask:
518 case glslang::EbvSubGroupLeMask:
519 case glslang::EbvSubGroupLtMask:
520 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600521 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600522 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800523#ifdef AMD_EXTENSIONS
524 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
525 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
526 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
527 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
528 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
529 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
530 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
531#endif
John Kessenich4016e382016-07-15 11:53:56 -0600532 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600533 }
534}
535
Rex Xufc618912015-09-09 16:42:49 +0800536// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700537spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800538{
539 assert(type.getBasicType() == glslang::EbtSampler);
540
John Kessenich5d0fa972016-02-15 11:57:00 -0700541 // Check for capabilities
542 switch (type.getQualifier().layoutFormat) {
543 case glslang::ElfRg32f:
544 case glslang::ElfRg16f:
545 case glslang::ElfR11fG11fB10f:
546 case glslang::ElfR16f:
547 case glslang::ElfRgba16:
548 case glslang::ElfRgb10A2:
549 case glslang::ElfRg16:
550 case glslang::ElfRg8:
551 case glslang::ElfR16:
552 case glslang::ElfR8:
553 case glslang::ElfRgba16Snorm:
554 case glslang::ElfRg16Snorm:
555 case glslang::ElfRg8Snorm:
556 case glslang::ElfR16Snorm:
557 case glslang::ElfR8Snorm:
558
559 case glslang::ElfRg32i:
560 case glslang::ElfRg16i:
561 case glslang::ElfRg8i:
562 case glslang::ElfR16i:
563 case glslang::ElfR8i:
564
565 case glslang::ElfRgb10a2ui:
566 case glslang::ElfRg32ui:
567 case glslang::ElfRg16ui:
568 case glslang::ElfRg8ui:
569 case glslang::ElfR16ui:
570 case glslang::ElfR8ui:
571 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
572 break;
573
574 default:
575 break;
576 }
577
578 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800579 switch (type.getQualifier().layoutFormat) {
580 case glslang::ElfNone: return spv::ImageFormatUnknown;
581 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
582 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
583 case glslang::ElfR32f: return spv::ImageFormatR32f;
584 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
585 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
586 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
587 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
588 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
589 case glslang::ElfR16f: return spv::ImageFormatR16f;
590 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
591 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
592 case glslang::ElfRg16: return spv::ImageFormatRg16;
593 case glslang::ElfRg8: return spv::ImageFormatRg8;
594 case glslang::ElfR16: return spv::ImageFormatR16;
595 case glslang::ElfR8: return spv::ImageFormatR8;
596 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
597 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
598 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
599 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
600 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
601 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
602 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
603 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
604 case glslang::ElfR32i: return spv::ImageFormatR32i;
605 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
606 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
607 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
608 case glslang::ElfR16i: return spv::ImageFormatR16i;
609 case glslang::ElfR8i: return spv::ImageFormatR8i;
610 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
611 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
612 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
613 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
614 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
615 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
616 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
617 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
618 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
619 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600620 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800621 }
622}
623
qining25262b32016-05-06 17:25:16 -0400624// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700625// descriptor set.
626bool IsDescriptorResource(const glslang::TType& type)
627{
John Kessenichf7497e22016-03-08 21:36:22 -0700628 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700629 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700630 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700631
632 // non block...
633 // basically samplerXXX/subpass/sampler/texture are all included
634 // if they are the global-scope-class, not the function parameter
635 // (or local, if they ever exist) class.
636 if (type.getBasicType() == glslang::EbtSampler)
637 return type.getQualifier().isUniformOrBuffer();
638
639 // None of the above.
640 return false;
641}
642
John Kesseniche0b6cad2015-12-24 10:30:13 -0700643void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
644{
645 if (child.layoutMatrix == glslang::ElmNone)
646 child.layoutMatrix = parent.layoutMatrix;
647
648 if (parent.invariant)
649 child.invariant = true;
650 if (parent.nopersp)
651 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800652#ifdef AMD_EXTENSIONS
653 if (parent.explicitInterp)
654 child.explicitInterp = true;
655#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700656 if (parent.flat)
657 child.flat = true;
658 if (parent.centroid)
659 child.centroid = true;
660 if (parent.patch)
661 child.patch = true;
662 if (parent.sample)
663 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800664 if (parent.coherent)
665 child.coherent = true;
666 if (parent.volatil)
667 child.volatil = true;
668 if (parent.restrict)
669 child.restrict = true;
670 if (parent.readonly)
671 child.readonly = true;
672 if (parent.writeonly)
673 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700674}
675
676bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
677{
John Kessenich7b9fa252016-01-21 18:56:57 -0700678 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700679 // - struct members can inherit from a struct declaration
John Kessenich76d4dfc2016-06-16 12:43:23 -0600680 // - 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 -0700681 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich76d4dfc2016-06-16 12:43:23 -0600682 return qualifier.invariant || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700683}
684
John Kessenich140f3df2015-06-26 16:58:36 -0600685//
686// Implement the TGlslangToSpvTraverser class.
687//
688
Lei Zhang17535f72016-05-04 15:55:59 -0400689TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
690 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
691 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600692 inMain(false), mainTerminated(false), linkageOnly(false),
693 glslangIntermediate(glslangIntermediate)
694{
695 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
696
697 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700698 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600699 stdBuiltins = builder.import("GLSL.std.450");
700 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700701 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
702 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600703
704 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600705 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
706 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600707 builder.addSourceExtension(it->c_str());
708
709 // Add the top-level modes for this shader.
710
John Kessenich92187592016-02-01 13:45:25 -0700711 if (glslangIntermediate->getXfbMode()) {
712 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600713 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700714 }
John Kessenich140f3df2015-06-26 16:58:36 -0600715
716 unsigned int mode;
717 switch (glslangIntermediate->getStage()) {
718 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600719 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600720 break;
721
722 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600723 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600724 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
725 break;
726
727 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600728 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600729 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700730 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
731 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
732 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600733 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600734 }
John Kessenich4016e382016-07-15 11:53:56 -0600735 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600736 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
737
John Kesseniche6903322015-10-13 16:29:02 -0600738 switch (glslangIntermediate->getVertexSpacing()) {
739 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
740 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
741 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600742 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600743 }
John Kessenich4016e382016-07-15 11:53:56 -0600744 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600745 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
746
747 switch (glslangIntermediate->getVertexOrder()) {
748 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
749 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600750 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600751 }
John Kessenich4016e382016-07-15 11:53:56 -0600752 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600753 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
754
755 if (glslangIntermediate->getPointMode())
756 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600757 break;
758
759 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600760 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600761 switch (glslangIntermediate->getInputPrimitive()) {
762 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
763 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
764 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700765 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600766 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600767 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600768 }
John Kessenich4016e382016-07-15 11:53:56 -0600769 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600770 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600771
John Kessenich140f3df2015-06-26 16:58:36 -0600772 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
773
774 switch (glslangIntermediate->getOutputPrimitive()) {
775 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
776 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
777 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600778 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600779 }
John Kessenich4016e382016-07-15 11:53:56 -0600780 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600781 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
782 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
783 break;
784
785 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600786 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600787 if (glslangIntermediate->getPixelCenterInteger())
788 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600789
John Kessenich140f3df2015-06-26 16:58:36 -0600790 if (glslangIntermediate->getOriginUpperLeft())
791 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600792 else
793 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600794
795 if (glslangIntermediate->getEarlyFragmentTests())
796 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
797
798 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600799 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
800 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600801 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600802 }
John Kessenich4016e382016-07-15 11:53:56 -0600803 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600804 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
805
806 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
807 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600808 break;
809
810 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600811 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600812 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
813 glslangIntermediate->getLocalSize(1),
814 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600815 break;
816
817 default:
818 break;
819 }
820
821}
822
John Kessenich7ba63412015-12-20 17:37:07 -0700823// Finish everything and dump
824void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
825{
826 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100827 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
828 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700829
qiningda397332016-03-09 19:54:03 -0500830 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700831 builder.dump(out);
832}
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
835{
836 if (! mainTerminated) {
837 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
838 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600839 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600840 }
841}
842
843//
844// Implement the traversal functions.
845//
846// Return true from interior nodes to have the external traversal
847// continue on to children. Return false if children were
848// already processed.
849//
850
851//
qining25262b32016-05-06 17:25:16 -0400852// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600853// - uniform/input reads
854// - output writes
855// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
856// - something simple that degenerates into the last bullet
857//
858void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
859{
qining75d1d802016-04-06 14:42:01 -0400860 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
861 if (symbol->getType().getQualifier().isSpecConstant())
862 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
863
John Kessenich140f3df2015-06-26 16:58:36 -0600864 // getSymbolId() will set up all the IO decorations on the first call.
865 // Formal function parameters were mapped during makeFunctions().
866 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700867
868 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
869 if (builder.isPointer(id)) {
870 spv::StorageClass sc = builder.getStorageClass(id);
871 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
872 iOSet.insert(id);
873 }
874
875 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700876 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600877 // Prepare to generate code for the access
878
879 // L-value chains will be computed left to right. We're on the symbol now,
880 // which is the left-most part of the access chain, so now is "clear" time,
881 // followed by setting the base.
882 builder.clearAccessChain();
883
884 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700885 // except for
886 // A) "const in" arguments to a function, which are an intermediate object.
887 // See comments in handleUserFunctionCall().
888 // B) Specialization constants (normal constant don't even come in as a variable),
889 // These are also pure R-values.
890 glslang::TQualifier qualifier = symbol->getQualifier();
891 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
892 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600893 builder.setAccessChainRValue(id);
894 else
895 builder.setAccessChainLValue(id);
896 }
897}
898
899bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
900{
qining40887662016-04-03 22:20:42 -0400901 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
902 if (node->getType().getQualifier().isSpecConstant())
903 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
904
John Kessenich140f3df2015-06-26 16:58:36 -0600905 // First, handle special cases
906 switch (node->getOp()) {
907 case glslang::EOpAssign:
908 case glslang::EOpAddAssign:
909 case glslang::EOpSubAssign:
910 case glslang::EOpMulAssign:
911 case glslang::EOpVectorTimesMatrixAssign:
912 case glslang::EOpVectorTimesScalarAssign:
913 case glslang::EOpMatrixTimesScalarAssign:
914 case glslang::EOpMatrixTimesMatrixAssign:
915 case glslang::EOpDivAssign:
916 case glslang::EOpModAssign:
917 case glslang::EOpAndAssign:
918 case glslang::EOpInclusiveOrAssign:
919 case glslang::EOpExclusiveOrAssign:
920 case glslang::EOpLeftShiftAssign:
921 case glslang::EOpRightShiftAssign:
922 // A bin-op assign "a += b" means the same thing as "a = a + b"
923 // where a is evaluated before b. For a simple assignment, GLSL
924 // says to evaluate the left before the right. So, always, left
925 // node then right node.
926 {
927 // get the left l-value, save it away
928 builder.clearAccessChain();
929 node->getLeft()->traverse(this);
930 spv::Builder::AccessChain lValue = builder.getAccessChain();
931
932 // evaluate the right
933 builder.clearAccessChain();
934 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700935 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600936
937 if (node->getOp() != glslang::EOpAssign) {
938 // the left is also an r-value
939 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700940 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600941
942 // do the operation
qining25262b32016-05-06 17:25:16 -0400943 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
944 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600945 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
946 node->getType().getBasicType());
947
948 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700949 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600950 }
951
952 // store the result
953 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800954 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // assignments are expressions having an rValue after they are evaluated...
957 builder.clearAccessChain();
958 builder.setAccessChainRValue(rValue);
959 }
960 return false;
961 case glslang::EOpIndexDirect:
962 case glslang::EOpIndexDirectStruct:
963 {
964 // Get the left part of the access chain.
965 node->getLeft()->traverse(this);
966
967 // Add the next element in the chain
968
David Netoa901ffe2016-06-08 14:11:40 +0100969 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600970 if (! node->getLeft()->getType().isArray() &&
971 node->getLeft()->getType().isVector() &&
972 node->getOp() == glslang::EOpIndexDirect) {
973 // This is essentially a hard-coded vector swizzle of size 1,
974 // so short circuit the access-chain stuff with a swizzle.
975 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100976 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600977 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600978 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100979 int spvIndex = glslangIndex;
980 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
981 node->getOp() == glslang::EOpIndexDirectStruct)
982 {
983 // This may be, e.g., an anonymous block-member selection, which generally need
984 // index remapping due to hidden members in anonymous blocks.
985 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
986 assert(remapper.size() > 0);
987 spvIndex = remapper[glslangIndex];
988 }
John Kessenichebb50532016-05-16 19:22:05 -0600989
David Netoa901ffe2016-06-08 14:11:40 +0100990 // normal case for indexing array or structure or block
991 builder.accessChainPush(builder.makeIntConstant(spvIndex));
992
993 // Add capabilities here for accessing PointSize and clip/cull distance.
994 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -0600995 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +0100996 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -0600997 }
998 }
999 return false;
1000 case glslang::EOpIndexIndirect:
1001 {
1002 // Structure or array or vector indirection.
1003 // Will use native SPIR-V access-chain for struct and array indirection;
1004 // matrices are arrays of vectors, so will also work for a matrix.
1005 // Will use the access chain's 'component' for variable index into a vector.
1006
1007 // This adapter is building access chains left to right.
1008 // Set up the access chain to the left.
1009 node->getLeft()->traverse(this);
1010
1011 // save it so that computing the right side doesn't trash it
1012 spv::Builder::AccessChain partial = builder.getAccessChain();
1013
1014 // compute the next index in the chain
1015 builder.clearAccessChain();
1016 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001017 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001018
1019 // restore the saved access chain
1020 builder.setAccessChain(partial);
1021
1022 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001023 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001024 else
John Kessenichfa668da2015-09-13 14:46:30 -06001025 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001026 }
1027 return false;
1028 case glslang::EOpVectorSwizzle:
1029 {
1030 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001031 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001032 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001033 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001034 }
1035 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001036 case glslang::EOpLogicalOr:
1037 case glslang::EOpLogicalAnd:
1038 {
1039
1040 // These may require short circuiting, but can sometimes be done as straight
1041 // binary operations. The right operand must be short circuited if it has
1042 // side effects, and should probably be if it is complex.
1043 if (isTrivial(node->getRight()->getAsTyped()))
1044 break; // handle below as a normal binary operation
1045 // otherwise, we need to do dynamic short circuiting on the right operand
1046 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1047 builder.clearAccessChain();
1048 builder.setAccessChainRValue(result);
1049 }
1050 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001051 default:
1052 break;
1053 }
1054
1055 // Assume generic binary op...
1056
John Kessenich32cfd492016-02-02 12:37:46 -07001057 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001058 builder.clearAccessChain();
1059 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001060 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001061
John Kessenich32cfd492016-02-02 12:37:46 -07001062 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001063 builder.clearAccessChain();
1064 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001065 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001066
John Kessenich32cfd492016-02-02 12:37:46 -07001067 // get result
1068 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
qining25262b32016-05-06 17:25:16 -04001069 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001070 convertGlslangToSpvType(node->getType()), left, right,
1071 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001072
John Kessenich50e57562015-12-21 21:21:11 -07001073 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001074 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001075 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001076 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001077 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001078 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001079 return false;
1080 }
John Kessenich140f3df2015-06-26 16:58:36 -06001081}
1082
1083bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1084{
qining40887662016-04-03 22:20:42 -04001085 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1086 if (node->getType().getQualifier().isSpecConstant())
1087 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1088
John Kessenichfc51d282015-08-19 13:34:18 -06001089 spv::Id result = spv::NoResult;
1090
1091 // try texturing first
1092 result = createImageTextureFunctionCall(node);
1093 if (result != spv::NoResult) {
1094 builder.clearAccessChain();
1095 builder.setAccessChainRValue(result);
1096
1097 return false; // done with this node
1098 }
1099
1100 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001101
1102 if (node->getOp() == glslang::EOpArrayLength) {
1103 // Quite special; won't want to evaluate the operand.
1104
1105 // Normal .length() would have been constant folded by the front-end.
1106 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001107 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001108 assert(node->getOperand()->getType().isRuntimeSizedArray());
1109 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1110 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001111 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1112 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001113
1114 builder.clearAccessChain();
1115 builder.setAccessChainRValue(length);
1116
1117 return false;
1118 }
1119
John Kessenichfc51d282015-08-19 13:34:18 -06001120 // Start by evaluating the operand
1121
John Kessenich8c8505c2016-07-26 12:50:38 -06001122 // Does it need a swizzle inversion? If so, evaluation is inverted;
1123 // operate first on the swizzle base, then apply the swizzle.
1124 spv::Id invertedType = spv::NoType;
1125 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1126 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1127 invertedType = getInvertedSwizzleType(*node->getOperand());
1128
John Kessenich140f3df2015-06-26 16:58:36 -06001129 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001130 if (invertedType != spv::NoType)
1131 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1132 else
1133 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001134
Rex Xufc618912015-09-09 16:42:49 +08001135 spv::Id operand = spv::NoResult;
1136
1137 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1138 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001139 node->getOp() == glslang::EOpAtomicCounter ||
1140 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001141 operand = builder.accessChainGetLValue(); // Special case l-value operands
1142 else
John Kessenich32cfd492016-02-02 12:37:46 -07001143 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
qining25262b32016-05-06 17:25:16 -04001146 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001147
1148 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001149 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001150 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001151
1152 // if not, then possibly an operation
1153 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001154 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001155
1156 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001157 if (invertedType)
1158 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1159
John Kessenich140f3df2015-06-26 16:58:36 -06001160 builder.clearAccessChain();
1161 builder.setAccessChainRValue(result);
1162
1163 return false; // done with this node
1164 }
1165
1166 // it must be a special case, check...
1167 switch (node->getOp()) {
1168 case glslang::EOpPostIncrement:
1169 case glslang::EOpPostDecrement:
1170 case glslang::EOpPreIncrement:
1171 case glslang::EOpPreDecrement:
1172 {
1173 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001174 spv::Id one = 0;
1175 if (node->getBasicType() == glslang::EbtFloat)
1176 one = builder.makeFloatConstant(1.0F);
1177 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1178 one = builder.makeInt64Constant(1);
1179 else
1180 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001181 glslang::TOperator op;
1182 if (node->getOp() == glslang::EOpPreIncrement ||
1183 node->getOp() == glslang::EOpPostIncrement)
1184 op = glslang::EOpAdd;
1185 else
1186 op = glslang::EOpSub;
1187
qining25262b32016-05-06 17:25:16 -04001188 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1189 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001190 convertGlslangToSpvType(node->getType()), operand, one,
1191 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001192 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001193
1194 // The result of operation is always stored, but conditionally the
1195 // consumed result. The consumed result is always an r-value.
1196 builder.accessChainStore(result);
1197 builder.clearAccessChain();
1198 if (node->getOp() == glslang::EOpPreIncrement ||
1199 node->getOp() == glslang::EOpPreDecrement)
1200 builder.setAccessChainRValue(result);
1201 else
1202 builder.setAccessChainRValue(operand);
1203 }
1204
1205 return false;
1206
1207 case glslang::EOpEmitStreamVertex:
1208 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1209 return false;
1210 case glslang::EOpEndStreamPrimitive:
1211 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1212 return false;
1213
1214 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001215 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001216 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001217 }
John Kessenich140f3df2015-06-26 16:58:36 -06001218}
1219
1220bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1221{
qining27e04a02016-04-14 16:40:20 -04001222 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1223 if (node->getType().getQualifier().isSpecConstant())
1224 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1225
John Kessenichfc51d282015-08-19 13:34:18 -06001226 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001227 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1228 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001229
1230 // try texturing
1231 result = createImageTextureFunctionCall(node);
1232 if (result != spv::NoResult) {
1233 builder.clearAccessChain();
1234 builder.setAccessChainRValue(result);
1235
1236 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001237 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001238 // "imageStore" is a special case, which has no result
1239 return false;
1240 }
John Kessenichfc51d282015-08-19 13:34:18 -06001241
John Kessenich140f3df2015-06-26 16:58:36 -06001242 glslang::TOperator binOp = glslang::EOpNull;
1243 bool reduceComparison = true;
1244 bool isMatrix = false;
1245 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001246 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001247
1248 assert(node->getOp());
1249
1250 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1251
1252 switch (node->getOp()) {
1253 case glslang::EOpSequence:
1254 {
1255 if (preVisit)
1256 ++sequenceDepth;
1257 else
1258 --sequenceDepth;
1259
1260 if (sequenceDepth == 1) {
1261 // If this is the parent node of all the functions, we want to see them
1262 // early, so all call points have actual SPIR-V functions to reference.
1263 // In all cases, still let the traverser visit the children for us.
1264 makeFunctions(node->getAsAggregate()->getSequence());
1265
1266 // Also, we want all globals initializers to go into the entry of main(), before
1267 // anything else gets there, so visit out of order, doing them all now.
1268 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1269
1270 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1271 // so do them manually.
1272 visitFunctions(node->getAsAggregate()->getSequence());
1273
1274 return false;
1275 }
1276
1277 return true;
1278 }
1279 case glslang::EOpLinkerObjects:
1280 {
1281 if (visit == glslang::EvPreVisit)
1282 linkageOnly = true;
1283 else
1284 linkageOnly = false;
1285
1286 return true;
1287 }
1288 case glslang::EOpComma:
1289 {
1290 // processing from left to right naturally leaves the right-most
1291 // lying around in the access chain
1292 glslang::TIntermSequence& glslangOperands = node->getSequence();
1293 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1294 glslangOperands[i]->traverse(this);
1295
1296 return false;
1297 }
1298 case glslang::EOpFunction:
1299 if (visit == glslang::EvPreVisit) {
1300 if (isShaderEntrypoint(node)) {
1301 inMain = true;
1302 builder.setBuildPoint(shaderEntry->getLastBlock());
1303 } else {
1304 handleFunctionEntry(node);
1305 }
1306 } else {
1307 if (inMain)
1308 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001309 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001310 inMain = false;
1311 }
1312
1313 return true;
1314 case glslang::EOpParameters:
1315 // Parameters will have been consumed by EOpFunction processing, but not
1316 // the body, so we still visited the function node's children, making this
1317 // child redundant.
1318 return false;
1319 case glslang::EOpFunctionCall:
1320 {
1321 if (node->isUserDefined())
1322 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001323 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1324 if (result) {
1325 builder.clearAccessChain();
1326 builder.setAccessChainRValue(result);
1327 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001328 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 return false;
1331 }
1332 case glslang::EOpConstructMat2x2:
1333 case glslang::EOpConstructMat2x3:
1334 case glslang::EOpConstructMat2x4:
1335 case glslang::EOpConstructMat3x2:
1336 case glslang::EOpConstructMat3x3:
1337 case glslang::EOpConstructMat3x4:
1338 case glslang::EOpConstructMat4x2:
1339 case glslang::EOpConstructMat4x3:
1340 case glslang::EOpConstructMat4x4:
1341 case glslang::EOpConstructDMat2x2:
1342 case glslang::EOpConstructDMat2x3:
1343 case glslang::EOpConstructDMat2x4:
1344 case glslang::EOpConstructDMat3x2:
1345 case glslang::EOpConstructDMat3x3:
1346 case glslang::EOpConstructDMat3x4:
1347 case glslang::EOpConstructDMat4x2:
1348 case glslang::EOpConstructDMat4x3:
1349 case glslang::EOpConstructDMat4x4:
1350 isMatrix = true;
1351 // fall through
1352 case glslang::EOpConstructFloat:
1353 case glslang::EOpConstructVec2:
1354 case glslang::EOpConstructVec3:
1355 case glslang::EOpConstructVec4:
1356 case glslang::EOpConstructDouble:
1357 case glslang::EOpConstructDVec2:
1358 case glslang::EOpConstructDVec3:
1359 case glslang::EOpConstructDVec4:
1360 case glslang::EOpConstructBool:
1361 case glslang::EOpConstructBVec2:
1362 case glslang::EOpConstructBVec3:
1363 case glslang::EOpConstructBVec4:
1364 case glslang::EOpConstructInt:
1365 case glslang::EOpConstructIVec2:
1366 case glslang::EOpConstructIVec3:
1367 case glslang::EOpConstructIVec4:
1368 case glslang::EOpConstructUint:
1369 case glslang::EOpConstructUVec2:
1370 case glslang::EOpConstructUVec3:
1371 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001372 case glslang::EOpConstructInt64:
1373 case glslang::EOpConstructI64Vec2:
1374 case glslang::EOpConstructI64Vec3:
1375 case glslang::EOpConstructI64Vec4:
1376 case glslang::EOpConstructUint64:
1377 case glslang::EOpConstructU64Vec2:
1378 case glslang::EOpConstructU64Vec3:
1379 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001380 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001381 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001382 {
1383 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001384 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001385 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001386 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001387 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001388 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001389 std::vector<spv::Id> constituents;
1390 for (int c = 0; c < (int)arguments.size(); ++c)
1391 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001392 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001393 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001394 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001395 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001396 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001397
1398 builder.clearAccessChain();
1399 builder.setAccessChainRValue(constructed);
1400
1401 return false;
1402 }
1403
1404 // These six are component-wise compares with component-wise results.
1405 // Forward on to createBinaryOperation(), requesting a vector result.
1406 case glslang::EOpLessThan:
1407 case glslang::EOpGreaterThan:
1408 case glslang::EOpLessThanEqual:
1409 case glslang::EOpGreaterThanEqual:
1410 case glslang::EOpVectorEqual:
1411 case glslang::EOpVectorNotEqual:
1412 {
1413 // Map the operation to a binary
1414 binOp = node->getOp();
1415 reduceComparison = false;
1416 switch (node->getOp()) {
1417 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1418 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1419 default: binOp = node->getOp(); break;
1420 }
1421
1422 break;
1423 }
1424 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001425 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001426 binOp = glslang::EOpMul;
1427 break;
1428 case glslang::EOpOuterProduct:
1429 // two vectors multiplied to make a matrix
1430 binOp = glslang::EOpOuterProduct;
1431 break;
1432 case glslang::EOpDot:
1433 {
qining25262b32016-05-06 17:25:16 -04001434 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001435 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001436 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001437 binOp = glslang::EOpMul;
1438 break;
1439 }
1440 case glslang::EOpMod:
1441 // when an aggregate, this is the floating-point mod built-in function,
1442 // which can be emitted by the one in createBinaryOperation()
1443 binOp = glslang::EOpMod;
1444 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001445 case glslang::EOpEmitVertex:
1446 case glslang::EOpEndPrimitive:
1447 case glslang::EOpBarrier:
1448 case glslang::EOpMemoryBarrier:
1449 case glslang::EOpMemoryBarrierAtomicCounter:
1450 case glslang::EOpMemoryBarrierBuffer:
1451 case glslang::EOpMemoryBarrierImage:
1452 case glslang::EOpMemoryBarrierShared:
1453 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001454 case glslang::EOpAllMemoryBarrierWithGroupSync:
1455 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1456 case glslang::EOpWorkgroupMemoryBarrier:
1457 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001458 noReturnValue = true;
1459 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1460 break;
1461
John Kessenich426394d2015-07-23 10:22:48 -06001462 case glslang::EOpAtomicAdd:
1463 case glslang::EOpAtomicMin:
1464 case glslang::EOpAtomicMax:
1465 case glslang::EOpAtomicAnd:
1466 case glslang::EOpAtomicOr:
1467 case glslang::EOpAtomicXor:
1468 case glslang::EOpAtomicExchange:
1469 case glslang::EOpAtomicCompSwap:
1470 atomic = true;
1471 break;
1472
John Kessenich140f3df2015-06-26 16:58:36 -06001473 default:
1474 break;
1475 }
1476
1477 //
1478 // See if it maps to a regular operation.
1479 //
John Kessenich140f3df2015-06-26 16:58:36 -06001480 if (binOp != glslang::EOpNull) {
1481 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1482 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1483 assert(left && right);
1484
1485 builder.clearAccessChain();
1486 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001487 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001488
1489 builder.clearAccessChain();
1490 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001491 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001492
qining25262b32016-05-06 17:25:16 -04001493 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001494 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001495 left->getType().getBasicType(), reduceComparison);
1496
1497 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001498 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001499 builder.clearAccessChain();
1500 builder.setAccessChainRValue(result);
1501
1502 return false;
1503 }
1504
John Kessenich426394d2015-07-23 10:22:48 -06001505 //
1506 // Create the list of operands.
1507 //
John Kessenich140f3df2015-06-26 16:58:36 -06001508 glslang::TIntermSequence& glslangOperands = node->getSequence();
1509 std::vector<spv::Id> operands;
1510 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001511 // special case l-value operands; there are just a few
1512 bool lvalue = false;
1513 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001514 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001515 case glslang::EOpModf:
1516 if (arg == 1)
1517 lvalue = true;
1518 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001519 case glslang::EOpInterpolateAtSample:
1520 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001521#ifdef AMD_EXTENSIONS
1522 case glslang::EOpInterpolateAtVertex:
1523#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001524 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001525 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001526
1527 // Does it need a swizzle inversion? If so, evaluation is inverted;
1528 // operate first on the swizzle base, then apply the swizzle.
1529 if (glslangOperands[0]->getAsOperator() &&
1530 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1531 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1532 }
Rex Xu7a26c172015-12-08 17:12:09 +08001533 break;
Rex Xud4782c12015-09-06 16:30:11 +08001534 case glslang::EOpAtomicAdd:
1535 case glslang::EOpAtomicMin:
1536 case glslang::EOpAtomicMax:
1537 case glslang::EOpAtomicAnd:
1538 case glslang::EOpAtomicOr:
1539 case glslang::EOpAtomicXor:
1540 case glslang::EOpAtomicExchange:
1541 case glslang::EOpAtomicCompSwap:
1542 if (arg == 0)
1543 lvalue = true;
1544 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001545 case glslang::EOpAddCarry:
1546 case glslang::EOpSubBorrow:
1547 if (arg == 2)
1548 lvalue = true;
1549 break;
1550 case glslang::EOpUMulExtended:
1551 case glslang::EOpIMulExtended:
1552 if (arg >= 2)
1553 lvalue = true;
1554 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001555 default:
1556 break;
1557 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001558 builder.clearAccessChain();
1559 if (invertedType != spv::NoType && arg == 0)
1560 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1561 else
1562 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001563 if (lvalue)
1564 operands.push_back(builder.accessChainGetLValue());
1565 else
John Kessenich32cfd492016-02-02 12:37:46 -07001566 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001567 }
John Kessenich426394d2015-07-23 10:22:48 -06001568
1569 if (atomic) {
1570 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001571 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001572 } else {
1573 // Pass through to generic operations.
1574 switch (glslangOperands.size()) {
1575 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001576 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001577 break;
1578 case 1:
qining25262b32016-05-06 17:25:16 -04001579 result = createUnaryOperation(
1580 node->getOp(), precision,
1581 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001582 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001583 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001584 break;
1585 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001586 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001587 break;
1588 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001589 if (invertedType)
1590 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001591 }
1592
1593 if (noReturnValue)
1594 return false;
1595
1596 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001597 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001598 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001599 } else {
1600 builder.clearAccessChain();
1601 builder.setAccessChainRValue(result);
1602 return false;
1603 }
1604}
1605
1606bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1607{
1608 // This path handles both if-then-else and ?:
1609 // The if-then-else has a node type of void, while
1610 // ?: has a non-void node type
1611 spv::Id result = 0;
1612 if (node->getBasicType() != glslang::EbtVoid) {
1613 // don't handle this as just on-the-fly temporaries, because there will be two names
1614 // and better to leave SSA to later passes
1615 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1616 }
1617
1618 // emit the condition before doing anything with selection
1619 node->getCondition()->traverse(this);
1620
1621 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001622 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001623
1624 if (node->getTrueBlock()) {
1625 // emit the "then" statement
1626 node->getTrueBlock()->traverse(this);
1627 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001628 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001629 }
1630
1631 if (node->getFalseBlock()) {
1632 ifBuilder.makeBeginElse();
1633 // emit the "else" statement
1634 node->getFalseBlock()->traverse(this);
1635 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001636 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001637 }
1638
1639 ifBuilder.makeEndIf();
1640
1641 if (result) {
1642 // GLSL only has r-values as the result of a :?, but
1643 // if we have an l-value, that can be more efficient if it will
1644 // become the base of a complex r-value expression, because the
1645 // next layer copies r-values into memory to use the access-chain mechanism
1646 builder.clearAccessChain();
1647 builder.setAccessChainLValue(result);
1648 }
1649
1650 return false;
1651}
1652
1653bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1654{
1655 // emit and get the condition before doing anything with switch
1656 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001657 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001658
1659 // browse the children to sort out code segments
1660 int defaultSegment = -1;
1661 std::vector<TIntermNode*> codeSegments;
1662 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1663 std::vector<int> caseValues;
1664 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1665 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1666 TIntermNode* child = *c;
1667 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001668 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001669 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001670 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001671 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1672 } else
1673 codeSegments.push_back(child);
1674 }
1675
qining25262b32016-05-06 17:25:16 -04001676 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001677 // statements between the last case and the end of the switch statement
1678 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1679 (int)codeSegments.size() == defaultSegment)
1680 codeSegments.push_back(nullptr);
1681
1682 // make the switch statement
1683 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001684 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001685
1686 // emit all the code in the segments
1687 breakForLoop.push(false);
1688 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1689 builder.nextSwitchSegment(segmentBlocks, s);
1690 if (codeSegments[s])
1691 codeSegments[s]->traverse(this);
1692 else
1693 builder.addSwitchBreak();
1694 }
1695 breakForLoop.pop();
1696
1697 builder.endSwitch(segmentBlocks);
1698
1699 return false;
1700}
1701
1702void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1703{
1704 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001705 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001706
1707 builder.clearAccessChain();
1708 builder.setAccessChainRValue(constant);
1709}
1710
1711bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1712{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001713 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001714 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001715 // Spec requires back edges to target header blocks, and every header block
1716 // must dominate its merge block. Make a header block first to ensure these
1717 // conditions are met. By definition, it will contain OpLoopMerge, followed
1718 // by a block-ending branch. But we don't want to put any other body/test
1719 // instructions in it, since the body/test may have arbitrary instructions,
1720 // including merges of its own.
1721 builder.setBuildPoint(&blocks.head);
1722 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001723 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001724 spv::Block& test = builder.makeNewBlock();
1725 builder.createBranch(&test);
1726
1727 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001728 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001729 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001730 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001731 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1732
1733 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001734 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001735 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001736 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001737 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001738 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001739
1740 builder.setBuildPoint(&blocks.continue_target);
1741 if (node->getTerminal())
1742 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001743 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001744 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001745 builder.createBranch(&blocks.body);
1746
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001747 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001748 builder.setBuildPoint(&blocks.body);
1749 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001750 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001751 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001752 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001753
1754 builder.setBuildPoint(&blocks.continue_target);
1755 if (node->getTerminal())
1756 node->getTerminal()->traverse(this);
1757 if (node->getTest()) {
1758 node->getTest()->traverse(this);
1759 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001760 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001761 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001762 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001763 // TODO: unless there was a break/return/discard instruction
1764 // somewhere in the body, this is an infinite loop, so we should
1765 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001766 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001767 }
John Kessenich140f3df2015-06-26 16:58:36 -06001768 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001769 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001770 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001771 return false;
1772}
1773
1774bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1775{
1776 if (node->getExpression())
1777 node->getExpression()->traverse(this);
1778
1779 switch (node->getFlowOp()) {
1780 case glslang::EOpKill:
1781 builder.makeDiscard();
1782 break;
1783 case glslang::EOpBreak:
1784 if (breakForLoop.top())
1785 builder.createLoopExit();
1786 else
1787 builder.addSwitchBreak();
1788 break;
1789 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001790 builder.createLoopContinue();
1791 break;
1792 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001793 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001794 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001795 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001796 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001797
1798 builder.clearAccessChain();
1799 break;
1800
1801 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001802 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001803 break;
1804 }
1805
1806 return false;
1807}
1808
1809spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1810{
qining25262b32016-05-06 17:25:16 -04001811 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001812 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001813 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001814 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001815 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001816 }
1817
1818 // Now, handle actual variables
1819 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1820 spv::Id spvType = convertGlslangToSpvType(node->getType());
1821
1822 const char* name = node->getName().c_str();
1823 if (glslang::IsAnonymous(name))
1824 name = "";
1825
1826 return builder.createVariable(storageClass, spvType, name);
1827}
1828
1829// Return type Id of the sampled type.
1830spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1831{
1832 switch (sampler.type) {
1833 case glslang::EbtFloat: return builder.makeFloatType(32);
1834 case glslang::EbtInt: return builder.makeIntType(32);
1835 case glslang::EbtUint: return builder.makeUintType(32);
1836 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001837 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001838 return builder.makeFloatType(32);
1839 }
1840}
1841
John Kessenich8c8505c2016-07-26 12:50:38 -06001842// If node is a swizzle operation, return the type that should be used if
1843// the swizzle base is first consumed by another operation, before the swizzle
1844// is applied.
1845spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1846{
1847 if (node.getAsOperator() &&
1848 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1849 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1850 else
1851 return spv::NoType;
1852}
1853
1854// When inverting a swizzle with a parent op, this function
1855// will apply the swizzle operation to a completed parent operation.
1856spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1857{
1858 std::vector<unsigned> swizzle;
1859 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1860 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1861}
1862
1863
1864// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1865void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1866{
1867 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1868 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1869 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1870}
1871
John Kessenich3ac051e2015-12-20 11:29:16 -07001872// Convert from a glslang type to an SPV type, by calling into a
1873// recursive version of this function. This establishes the inherited
1874// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001875spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1876{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001877 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001878}
1879
1880// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001881// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001882// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001883spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001884{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001885 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001886
1887 switch (type.getBasicType()) {
1888 case glslang::EbtVoid:
1889 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001890 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001891 break;
1892 case glslang::EbtFloat:
1893 spvType = builder.makeFloatType(32);
1894 break;
1895 case glslang::EbtDouble:
1896 spvType = builder.makeFloatType(64);
1897 break;
1898 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001899 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1900 // a 32-bit int where non-0 means true.
1901 if (explicitLayout != glslang::ElpNone)
1902 spvType = builder.makeUintType(32);
1903 else
1904 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001905 break;
1906 case glslang::EbtInt:
1907 spvType = builder.makeIntType(32);
1908 break;
1909 case glslang::EbtUint:
1910 spvType = builder.makeUintType(32);
1911 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001912 case glslang::EbtInt64:
1913 builder.addCapability(spv::CapabilityInt64);
1914 spvType = builder.makeIntType(64);
1915 break;
1916 case glslang::EbtUint64:
1917 builder.addCapability(spv::CapabilityInt64);
1918 spvType = builder.makeUintType(64);
1919 break;
John Kessenich426394d2015-07-23 10:22:48 -06001920 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001921 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001922 spvType = builder.makeUintType(32);
1923 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001924 case glslang::EbtSampler:
1925 {
1926 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001927 if (sampler.sampler) {
1928 // pure sampler
1929 spvType = builder.makeSamplerType();
1930 } else {
1931 // an image is present, make its type
1932 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1933 sampler.image ? 2 : 1, TranslateImageFormat(type));
1934 if (sampler.combined) {
1935 // already has both image and sampler, make the combined type
1936 spvType = builder.makeSampledImageType(spvType);
1937 }
John Kessenich55e7d112015-11-15 21:33:39 -07001938 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001939 }
John Kessenich140f3df2015-06-26 16:58:36 -06001940 break;
1941 case glslang::EbtStruct:
1942 case glslang::EbtBlock:
1943 {
1944 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001945 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001946
1947 // Try to share structs for different layouts, but not yet for other
1948 // kinds of qualification (primarily not yet including interpolant qualification).
1949 if (! HasNonLayoutQualifiers(qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001950 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001951 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001952 break;
1953
1954 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001955 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001956 memberRemapper[glslangMembers].resize(glslangMembers->size());
1957 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001958 }
1959 break;
1960 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001961 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001962 break;
1963 }
1964
1965 if (type.isMatrix())
1966 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1967 else {
1968 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1969 if (type.getVectorSize() > 1)
1970 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1971 }
1972
1973 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001974 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1975
John Kessenichc9a80832015-09-12 12:17:44 -06001976 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001977 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001978 // We need to decorate array strides for types needing explicit layout, except blocks.
1979 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001980 // Use a dummy glslang type for querying internal strides of
1981 // arrays of arrays, but using just a one-dimensional array.
1982 glslang::TType simpleArrayType(type, 0); // deference type of the array
1983 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1984 simpleArrayType.getArraySizes().dereference();
1985
1986 // Will compute the higher-order strides here, rather than making a whole
1987 // pile of types and doing repetitive recursion on their contents.
1988 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1989 }
John Kessenichf8842e52016-01-04 19:22:56 -07001990
1991 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001992 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001993 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001994 if (stride > 0)
1995 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001996 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001997 }
1998 } else {
1999 // single-dimensional array, and don't yet have stride
2000
John Kessenichf8842e52016-01-04 19:22:56 -07002001 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002002 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2003 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002004 }
John Kessenich31ed4832015-09-09 17:51:38 -06002005
John Kessenichc9a80832015-09-12 12:17:44 -06002006 // Do the outer dimension, which might not be known for a runtime-sized array
2007 if (type.isRuntimeSizedArray()) {
2008 spvType = builder.makeRuntimeArray(spvType);
2009 } else {
2010 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002011 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002012 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002013 if (stride > 0)
2014 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002015 }
2016
2017 return spvType;
2018}
2019
John Kessenich6090df02016-06-30 21:18:02 -06002020
2021// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2022// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2023// Mutually recursive with convertGlslangToSpvType().
2024spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2025 const glslang::TTypeList* glslangMembers,
2026 glslang::TLayoutPacking explicitLayout,
2027 const glslang::TQualifier& qualifier)
2028{
2029 // Create a vector of struct types for SPIR-V to consume
2030 std::vector<spv::Id> spvMembers;
2031 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2032 int locationOffset = 0; // for use across struct members, when they are called recursively
2033 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2034 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2035 if (glslangMember.hiddenMember()) {
2036 ++memberDelta;
2037 if (type.getBasicType() == glslang::EbtBlock)
2038 memberRemapper[glslangMembers][i] = -1;
2039 } else {
2040 if (type.getBasicType() == glslang::EbtBlock)
2041 memberRemapper[glslangMembers][i] = i - memberDelta;
2042 // modify just this child's view of the qualifier
2043 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2044 InheritQualifiers(memberQualifier, qualifier);
2045
2046 // manually inherit location; it's more complex
2047 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2048 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2049 if (qualifier.hasLocation())
2050 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2051
2052 // recurse
2053 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2054 }
2055 }
2056
2057 // Make the SPIR-V type
2058 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
2059 if (! HasNonLayoutQualifiers(qualifier))
2060 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2061
2062 // Decorate it
2063 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2064
2065 return spvType;
2066}
2067
2068void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2069 const glslang::TTypeList* glslangMembers,
2070 glslang::TLayoutPacking explicitLayout,
2071 const glslang::TQualifier& qualifier,
2072 spv::Id spvType)
2073{
2074 // Name and decorate the non-hidden members
2075 int offset = -1;
2076 int locationOffset = 0; // for use within the members of this struct
2077 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2078 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2079 int member = i;
2080 if (type.getBasicType() == glslang::EbtBlock)
2081 member = memberRemapper[glslangMembers][i];
2082
2083 // modify just this child's view of the qualifier
2084 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2085 InheritQualifiers(memberQualifier, qualifier);
2086
2087 // using -1 above to indicate a hidden member
2088 if (member >= 0) {
2089 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2090 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2091 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2092 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2093 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2094 if (type.getBasicType() == glslang::EbtBlock) {
2095 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2096 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2097 }
2098 }
2099 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2100
2101 if (qualifier.storage == glslang::EvqBuffer) {
2102 std::vector<spv::Decoration> memory;
2103 TranslateMemoryDecoration(memberQualifier, memory);
2104 for (unsigned int i = 0; i < memory.size(); ++i)
2105 addMemberDecoration(spvType, member, memory[i]);
2106 }
2107
John Kessenich2f47bc92016-06-30 21:47:35 -06002108 // Compute location decoration; tricky based on whether inheritance is at play and
2109 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002110 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2111 // probably move to the linker stage of the front end proper, and just have the
2112 // answer sitting already distributed throughout the individual member locations.
2113 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002114 // Ignore member locations if the container is an array, as that's
2115 // ill-specified and decisions have been made to not allow this anyway.
2116 // The object itself must have a location, and that comes out from decorating the object,
2117 // not the type (this code decorates types).
2118 if (! type.isArray()) {
2119 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2120 // struct members should not have explicit locations
2121 assert(type.getBasicType() != glslang::EbtStruct);
2122 location = memberQualifier.layoutLocation;
2123 } else if (type.getBasicType() != glslang::EbtBlock) {
2124 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2125 // The members, and their nested types, must not themselves have Location decorations.
2126 } else if (qualifier.hasLocation()) // inheritance
2127 location = qualifier.layoutLocation + locationOffset;
2128 }
John Kessenich6090df02016-06-30 21:18:02 -06002129 if (location >= 0)
2130 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2131
John Kessenich2f47bc92016-06-30 21:47:35 -06002132 if (qualifier.hasLocation()) // track for upcoming inheritance
2133 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2134
John Kessenich6090df02016-06-30 21:18:02 -06002135 // component, XFB, others
2136 if (glslangMember.getQualifier().hasComponent())
2137 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2138 if (glslangMember.getQualifier().hasXfbOffset())
2139 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2140 else if (explicitLayout != glslang::ElpNone) {
2141 // figure out what to do with offset, which is accumulating
2142 int nextOffset;
2143 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2144 if (offset >= 0)
2145 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2146 offset = nextOffset;
2147 }
2148
2149 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2150 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2151
2152 // built-in variable decorations
2153 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002154 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002155 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2156 }
2157 }
2158
2159 // Decorate the structure
2160 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2161 addDecoration(spvType, TranslateBlockDecoration(type));
2162 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2163 builder.addCapability(spv::CapabilityGeometryStreams);
2164 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2165 }
2166 if (glslangIntermediate->getXfbMode()) {
2167 builder.addCapability(spv::CapabilityTransformFeedback);
2168 if (type.getQualifier().hasXfbStride())
2169 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2170 if (type.getQualifier().hasXfbBuffer())
2171 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2172 }
2173}
2174
John Kessenich6c292d32016-02-15 20:58:50 -07002175// Turn the expression forming the array size into an id.
2176// This is not quite trivial, because of specialization constants.
2177// Sometimes, a raw constant is turned into an Id, and sometimes
2178// a specialization constant expression is.
2179spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2180{
2181 // First, see if this is sized with a node, meaning a specialization constant:
2182 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2183 if (specNode != nullptr) {
2184 builder.clearAccessChain();
2185 specNode->traverse(this);
2186 return accessChainLoad(specNode->getAsTyped()->getType());
2187 }
qining25262b32016-05-06 17:25:16 -04002188
John Kessenich6c292d32016-02-15 20:58:50 -07002189 // Otherwise, need a compile-time (front end) size, get it:
2190 int size = arraySizes.getDimSize(dim);
2191 assert(size > 0);
2192 return builder.makeUintConstant(size);
2193}
2194
John Kessenich103bef92016-02-08 21:38:15 -07002195// Wrap the builder's accessChainLoad to:
2196// - localize handling of RelaxedPrecision
2197// - use the SPIR-V inferred type instead of another conversion of the glslang type
2198// (avoids unnecessary work and possible type punning for structures)
2199// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002200spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2201{
John Kessenich103bef92016-02-08 21:38:15 -07002202 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2203 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2204
2205 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002206 if (type.getBasicType() == glslang::EbtBool) {
2207 if (builder.isScalarType(nominalTypeId)) {
2208 // Conversion for bool
2209 spv::Id boolType = builder.makeBoolType();
2210 if (nominalTypeId != boolType)
2211 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2212 } else if (builder.isVectorType(nominalTypeId)) {
2213 // Conversion for bvec
2214 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2215 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2216 if (nominalTypeId != bvecType)
2217 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2218 }
2219 }
John Kessenich103bef92016-02-08 21:38:15 -07002220
2221 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002222}
2223
Rex Xu27253232016-02-23 17:51:09 +08002224// Wrap the builder's accessChainStore to:
2225// - do conversion of concrete to abstract type
2226void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2227{
2228 // Need to convert to abstract types when necessary
2229 if (type.getBasicType() == glslang::EbtBool) {
2230 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2231
2232 if (builder.isScalarType(nominalTypeId)) {
2233 // Conversion for bool
2234 spv::Id boolType = builder.makeBoolType();
2235 if (nominalTypeId != boolType) {
2236 spv::Id zero = builder.makeUintConstant(0);
2237 spv::Id one = builder.makeUintConstant(1);
2238 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2239 }
2240 } else if (builder.isVectorType(nominalTypeId)) {
2241 // Conversion for bvec
2242 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2243 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2244 if (nominalTypeId != bvecType) {
2245 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2246 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2247 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2248 }
2249 }
2250 }
2251
2252 builder.accessChainStore(rvalue);
2253}
2254
John Kessenichf85e8062015-12-19 13:57:10 -07002255// Decide whether or not this type should be
2256// decorated with offsets and strides, and if so
2257// whether std140 or std430 rules should be applied.
2258glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002259{
John Kessenichf85e8062015-12-19 13:57:10 -07002260 // has to be a block
2261 if (type.getBasicType() != glslang::EbtBlock)
2262 return glslang::ElpNone;
2263
2264 // has to be a uniform or buffer block
2265 if (type.getQualifier().storage != glslang::EvqUniform &&
2266 type.getQualifier().storage != glslang::EvqBuffer)
2267 return glslang::ElpNone;
2268
2269 // return the layout to use
2270 switch (type.getQualifier().layoutPacking) {
2271 case glslang::ElpStd140:
2272 case glslang::ElpStd430:
2273 return type.getQualifier().layoutPacking;
2274 default:
2275 return glslang::ElpNone;
2276 }
John Kessenich31ed4832015-09-09 17:51:38 -06002277}
2278
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002279// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002280int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002281{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002282 int size;
John Kessenich49987892015-12-29 17:11:44 -07002283 int stride;
2284 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002285
2286 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002287}
2288
John Kessenich49987892015-12-29 17:11:44 -07002289// 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 -07002290// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002291int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002292{
John Kessenich49987892015-12-29 17:11:44 -07002293 glslang::TType elementType;
2294 elementType.shallowCopy(matrixType);
2295 elementType.clearArraySizes();
2296
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002297 int size;
John Kessenich49987892015-12-29 17:11:44 -07002298 int stride;
2299 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2300
2301 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002302}
2303
John Kessenich5e4b1242015-08-06 22:53:06 -06002304// Given a member type of a struct, realign the current offset for it, and compute
2305// the next (not yet aligned) offset for the next member, which will get aligned
2306// on the next call.
2307// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2308// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2309// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002310void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002311 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002312{
2313 // this will get a positive value when deemed necessary
2314 nextOffset = -1;
2315
John Kessenich5e4b1242015-08-06 22:53:06 -06002316 // override anything in currentOffset with user-set offset
2317 if (memberType.getQualifier().hasOffset())
2318 currentOffset = memberType.getQualifier().layoutOffset;
2319
2320 // It could be that current linker usage in glslang updated all the layoutOffset,
2321 // in which case the following code does not matter. But, that's not quite right
2322 // once cross-compilation unit GLSL validation is done, as the original user
2323 // settings are needed in layoutOffset, and then the following will come into play.
2324
John Kessenichf85e8062015-12-19 13:57:10 -07002325 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002326 if (! memberType.getQualifier().hasOffset())
2327 currentOffset = -1;
2328
2329 return;
2330 }
2331
John Kessenichf85e8062015-12-19 13:57:10 -07002332 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002333 if (currentOffset < 0)
2334 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002335
John Kessenich5e4b1242015-08-06 22:53:06 -06002336 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2337 // but possibly not yet correctly aligned.
2338
2339 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002340 int dummyStride;
2341 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002342 glslang::RoundToPow2(currentOffset, memberAlignment);
2343 nextOffset = currentOffset + memberSize;
2344}
2345
David Netoa901ffe2016-06-08 14:11:40 +01002346void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002347{
David Netoa901ffe2016-06-08 14:11:40 +01002348 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2349 switch (glslangBuiltIn)
2350 {
2351 case glslang::EbvClipDistance:
2352 case glslang::EbvCullDistance:
2353 case glslang::EbvPointSize:
2354 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2355 // Alternately, we could just call this for any glslang built-in, since the
2356 // capability already guards against duplicates.
2357 TranslateBuiltInDecoration(glslangBuiltIn, false);
2358 break;
2359 default:
2360 // Capabilities were already generated when the struct was declared.
2361 break;
2362 }
John Kessenichebb50532016-05-16 19:22:05 -06002363}
2364
John Kessenich140f3df2015-06-26 16:58:36 -06002365bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2366{
John Kessenich4d65ee32016-03-12 18:17:47 -07002367 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002368 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002369 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002370}
2371
2372// Make all the functions, skeletally, without actually visiting their bodies.
2373void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2374{
2375 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2376 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2377 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2378 continue;
2379
2380 // We're on a user function. Set up the basic interface for the function now,
2381 // so that it's available to call.
2382 // Translating the body will happen later.
2383 //
qining25262b32016-05-06 17:25:16 -04002384 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002385 // function. What it is an address of varies:
2386 //
2387 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2388 // so that write needs to be to a copy, hence the address of a copy works.
2389 //
2390 // - "const in" parameters can just be the r-value, as no writes need occur.
2391 //
2392 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2393 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2394
2395 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002396 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002397 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2398
2399 for (int p = 0; p < (int)parameters.size(); ++p) {
2400 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2401 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002402 if (paramType.isOpaque())
2403 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2404 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002405 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2406 else
2407 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002408 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002409 paramTypes.push_back(typeId);
2410 }
2411
2412 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002413 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2414 convertGlslangToSpvType(glslFunction->getType()),
2415 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002416
2417 // Track function to emit/call later
2418 functionMap[glslFunction->getName().c_str()] = function;
2419
2420 // Set the parameter id's
2421 for (int p = 0; p < (int)parameters.size(); ++p) {
2422 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2423 // give a name too
2424 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2425 }
2426 }
2427}
2428
2429// Process all the initializers, while skipping the functions and link objects
2430void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2431{
2432 builder.setBuildPoint(shaderEntry->getLastBlock());
2433 for (int i = 0; i < (int)initializers.size(); ++i) {
2434 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2435 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2436
2437 // We're on a top-level node that's not a function. Treat as an initializer, whose
2438 // code goes into the beginning of main.
2439 initializer->traverse(this);
2440 }
2441 }
2442}
2443
2444// Process all the functions, while skipping initializers.
2445void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2446{
2447 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2448 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2449 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2450 node->traverse(this);
2451 }
2452}
2453
2454void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2455{
qining25262b32016-05-06 17:25:16 -04002456 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002457 // that called makeFunctions().
2458 spv::Function* function = functionMap[node->getName().c_str()];
2459 spv::Block* functionBlock = function->getEntryBlock();
2460 builder.setBuildPoint(functionBlock);
2461}
2462
Rex Xu04db3f52015-09-16 11:44:02 +08002463void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002464{
Rex Xufc618912015-09-09 16:42:49 +08002465 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002466
2467 glslang::TSampler sampler = {};
2468 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002469 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002470 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2471 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2472 }
2473
John Kessenich140f3df2015-06-26 16:58:36 -06002474 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2475 builder.clearAccessChain();
2476 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002477
2478 // Special case l-value operands
2479 bool lvalue = false;
2480 switch (node.getOp()) {
2481 case glslang::EOpImageAtomicAdd:
2482 case glslang::EOpImageAtomicMin:
2483 case glslang::EOpImageAtomicMax:
2484 case glslang::EOpImageAtomicAnd:
2485 case glslang::EOpImageAtomicOr:
2486 case glslang::EOpImageAtomicXor:
2487 case glslang::EOpImageAtomicExchange:
2488 case glslang::EOpImageAtomicCompSwap:
2489 if (i == 0)
2490 lvalue = true;
2491 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002492 case glslang::EOpSparseImageLoad:
2493 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2494 lvalue = true;
2495 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002496 case glslang::EOpSparseTexture:
2497 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2498 lvalue = true;
2499 break;
2500 case glslang::EOpSparseTextureClamp:
2501 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2502 lvalue = true;
2503 break;
2504 case glslang::EOpSparseTextureLod:
2505 case glslang::EOpSparseTextureOffset:
2506 if (i == 3)
2507 lvalue = true;
2508 break;
2509 case glslang::EOpSparseTextureFetch:
2510 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2511 lvalue = true;
2512 break;
2513 case glslang::EOpSparseTextureFetchOffset:
2514 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2515 lvalue = true;
2516 break;
2517 case glslang::EOpSparseTextureLodOffset:
2518 case glslang::EOpSparseTextureGrad:
2519 case glslang::EOpSparseTextureOffsetClamp:
2520 if (i == 4)
2521 lvalue = true;
2522 break;
2523 case glslang::EOpSparseTextureGradOffset:
2524 case glslang::EOpSparseTextureGradClamp:
2525 if (i == 5)
2526 lvalue = true;
2527 break;
2528 case glslang::EOpSparseTextureGradOffsetClamp:
2529 if (i == 6)
2530 lvalue = true;
2531 break;
2532 case glslang::EOpSparseTextureGather:
2533 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2534 lvalue = true;
2535 break;
2536 case glslang::EOpSparseTextureGatherOffset:
2537 case glslang::EOpSparseTextureGatherOffsets:
2538 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2539 lvalue = true;
2540 break;
Rex Xufc618912015-09-09 16:42:49 +08002541 default:
2542 break;
2543 }
2544
Rex Xu6b86d492015-09-16 17:48:22 +08002545 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002546 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002547 else
John Kessenich32cfd492016-02-02 12:37:46 -07002548 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002549 }
2550}
2551
John Kessenichfc51d282015-08-19 13:34:18 -06002552void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002553{
John Kessenichfc51d282015-08-19 13:34:18 -06002554 builder.clearAccessChain();
2555 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002556 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002557}
John Kessenich140f3df2015-06-26 16:58:36 -06002558
John Kessenichfc51d282015-08-19 13:34:18 -06002559spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2560{
Rex Xufc618912015-09-09 16:42:49 +08002561 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002562 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002563 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002564 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002565
John Kessenichfc51d282015-08-19 13:34:18 -06002566 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002567 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2568 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2569 std::vector<spv::Id> arguments;
2570 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002571 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002572 else
2573 translateArguments(*node->getAsUnaryNode(), arguments);
2574 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2575
2576 spv::Builder::TextureParameters params = { };
2577 params.sampler = arguments[0];
2578
Rex Xu04db3f52015-09-16 11:44:02 +08002579 glslang::TCrackedTextureOp cracked;
2580 node->crackTexture(sampler, cracked);
2581
John Kessenichfc51d282015-08-19 13:34:18 -06002582 // Check for queries
2583 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002584 // a sampled image needs to have the image extracted first
2585 if (builder.isSampledImage(params.sampler))
2586 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002587 switch (node->getOp()) {
2588 case glslang::EOpImageQuerySize:
2589 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002590 if (arguments.size() > 1) {
2591 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002592 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002593 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002594 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002595 case glslang::EOpImageQuerySamples:
2596 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002597 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002598 case glslang::EOpTextureQueryLod:
2599 params.coords = arguments[1];
2600 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2601 case glslang::EOpTextureQueryLevels:
2602 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002603 case glslang::EOpSparseTexelsResident:
2604 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002605 default:
2606 assert(0);
2607 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002608 }
John Kessenich140f3df2015-06-26 16:58:36 -06002609 }
2610
Rex Xufc618912015-09-09 16:42:49 +08002611 // Check for image functions other than queries
2612 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002613 std::vector<spv::Id> operands;
2614 auto opIt = arguments.begin();
2615 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002616
2617 // Handle subpass operations
2618 // TODO: GLSL should change to have the "MS" only on the type rather than the
2619 // built-in function.
2620 if (cracked.subpass) {
2621 // add on the (0,0) coordinate
2622 spv::Id zero = builder.makeIntConstant(0);
2623 std::vector<spv::Id> comps;
2624 comps.push_back(zero);
2625 comps.push_back(zero);
2626 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2627 if (sampler.ms) {
2628 operands.push_back(spv::ImageOperandsSampleMask);
2629 operands.push_back(*(opIt++));
2630 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002631 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002632 }
2633
John Kessenich56bab042015-09-16 10:54:31 -06002634 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002635 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002636 if (sampler.ms) {
2637 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002638 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002639 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002640 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2641 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002642 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002643 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002644 if (sampler.ms) {
2645 operands.push_back(*(opIt + 1));
2646 operands.push_back(spv::ImageOperandsSampleMask);
2647 operands.push_back(*opIt);
2648 } else
2649 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002650 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002651 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2652 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002653 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002654 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2655 builder.addCapability(spv::CapabilitySparseResidency);
2656 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2657 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2658
2659 if (sampler.ms) {
2660 operands.push_back(spv::ImageOperandsSampleMask);
2661 operands.push_back(*opIt++);
2662 }
2663
2664 // Create the return type that was a special structure
2665 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002666 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002667 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2668 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2669
2670 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2671
2672 // Decode the return type
2673 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2674 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002675 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002676 // Process image atomic operations
2677
2678 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2679 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002680 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002681
John Kessenich8c8505c2016-07-26 12:50:38 -06002682 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002683 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002684
2685 std::vector<spv::Id> operands;
2686 operands.push_back(pointer);
2687 for (; opIt != arguments.end(); ++opIt)
2688 operands.push_back(*opIt);
2689
John Kessenich8c8505c2016-07-26 12:50:38 -06002690 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002691 }
2692 }
2693
2694 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002695 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002696 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2697
John Kessenichfc51d282015-08-19 13:34:18 -06002698 // check for bias argument
2699 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002700 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002701 int nonBiasArgCount = 2;
2702 if (cracked.offset)
2703 ++nonBiasArgCount;
2704 if (cracked.grad)
2705 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002706 if (cracked.lodClamp)
2707 ++nonBiasArgCount;
2708 if (sparse)
2709 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002710
2711 if ((int)arguments.size() > nonBiasArgCount)
2712 bias = true;
2713 }
2714
John Kessenicha5c33d62016-06-02 23:45:21 -06002715 // See if the sampler param should really be just the SPV image part
2716 if (cracked.fetch) {
2717 // a fetch needs to have the image extracted first
2718 if (builder.isSampledImage(params.sampler))
2719 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2720 }
2721
John Kessenichfc51d282015-08-19 13:34:18 -06002722 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002723
John Kessenichfc51d282015-08-19 13:34:18 -06002724 params.coords = arguments[1];
2725 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002726 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002727
2728 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002729 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002730 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002731 ++extraArgs;
2732 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002733 params.Dref = arguments[2];
2734 ++extraArgs;
2735 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002736 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002737 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002738 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002739 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002740 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002741 dRefComp = builder.getNumComponents(params.coords) - 1;
2742 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002743 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2744 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002745
2746 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002747 if (cracked.lod) {
2748 params.lod = arguments[2];
2749 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002750 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2751 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2752 noImplicitLod = true;
2753 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002754
2755 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002756 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002757 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002758 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002759 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002760
2761 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002762 if (cracked.grad) {
2763 params.gradX = arguments[2 + extraArgs];
2764 params.gradY = arguments[3 + extraArgs];
2765 extraArgs += 2;
2766 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002767
2768 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002769 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002770 params.offset = arguments[2 + extraArgs];
2771 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002772 } else if (cracked.offsets) {
2773 params.offsets = arguments[2 + extraArgs];
2774 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002775 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002776
2777 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002778 if (cracked.lodClamp) {
2779 params.lodClamp = arguments[2 + extraArgs];
2780 ++extraArgs;
2781 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002782
2783 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002784 if (sparse) {
2785 params.texelOut = arguments[2 + extraArgs];
2786 ++extraArgs;
2787 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002788
2789 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002790 if (bias) {
2791 params.bias = arguments[2 + extraArgs];
2792 ++extraArgs;
2793 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002794
2795 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002796 if (cracked.gather && ! sampler.shadow) {
2797 // default component is 0, if missing, otherwise an argument
2798 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002799 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002800 ++extraArgs;
2801 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002802 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002803 }
2804 }
John Kessenichfc51d282015-08-19 13:34:18 -06002805
John Kessenich65336482016-06-16 14:06:26 -06002806 // projective component (might not to move)
2807 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2808 // are divided by the last component of P."
2809 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2810 // unused components will appear after all used components."
2811 if (cracked.proj) {
2812 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2813 int projTargetComp;
2814 switch (sampler.dim) {
2815 case glslang::Esd1D: projTargetComp = 1; break;
2816 case glslang::Esd2D: projTargetComp = 2; break;
2817 case glslang::EsdRect: projTargetComp = 2; break;
2818 default: projTargetComp = projSourceComp; break;
2819 }
2820 // copy the projective coordinate if we have to
2821 if (projTargetComp != projSourceComp) {
2822 spv::Id projComp = builder.createCompositeExtract(params.coords,
2823 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2824 projSourceComp);
2825 params.coords = builder.createCompositeInsert(projComp, params.coords,
2826 builder.getTypeId(params.coords), projTargetComp);
2827 }
2828 }
2829
John Kessenich8c8505c2016-07-26 12:50:38 -06002830 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002831}
2832
2833spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2834{
2835 // Grab the function's pointer from the previously created function
2836 spv::Function* function = functionMap[node->getName().c_str()];
2837 if (! function)
2838 return 0;
2839
2840 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2841 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2842
2843 // See comments in makeFunctions() for details about the semantics for parameter passing.
2844 //
2845 // These imply we need a four step process:
2846 // 1. Evaluate the arguments
2847 // 2. Allocate and make copies of in, out, and inout arguments
2848 // 3. Make the call
2849 // 4. Copy back the results
2850
2851 // 1. Evaluate the arguments
2852 std::vector<spv::Builder::AccessChain> lValues;
2853 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002854 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002855 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002856 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002857 // build l-value
2858 builder.clearAccessChain();
2859 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002860 argTypes.push_back(&paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002861 // keep outputs as and opaque objects l-values, evaluate input-only as r-values
2862 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002863 // save l-value
2864 lValues.push_back(builder.getAccessChain());
2865 } else {
2866 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002867 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002868 }
2869 }
2870
2871 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2872 // copy the original into that space.
2873 //
2874 // Also, build up the list of actual arguments to pass in for the call
2875 int lValueCount = 0;
2876 int rValueCount = 0;
2877 std::vector<spv::Id> spvArgs;
2878 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002879 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002880 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002881 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002882 builder.setAccessChain(lValues[lValueCount]);
2883 arg = builder.accessChainGetLValue();
2884 ++lValueCount;
2885 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002886 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002887 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2888 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2889 // need to copy the input into output space
2890 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002891 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002892 builder.createStore(copy, arg);
2893 }
2894 ++lValueCount;
2895 } else {
2896 arg = rValues[rValueCount];
2897 ++rValueCount;
2898 }
2899 spvArgs.push_back(arg);
2900 }
2901
2902 // 3. Make the call.
2903 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002904 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002905
2906 // 4. Copy back out an "out" arguments.
2907 lValueCount = 0;
2908 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2909 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2910 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2911 spv::Id copy = builder.createLoad(spvArgs[a]);
2912 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002913 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002914 }
2915 ++lValueCount;
2916 }
2917 }
2918
2919 return result;
2920}
2921
2922// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002923spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2924 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002925 spv::Id typeId, spv::Id left, spv::Id right,
2926 glslang::TBasicType typeProxy, bool reduceComparison)
2927{
Rex Xu8ff43de2016-04-22 16:51:45 +08002928 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002929 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002930 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002931
2932 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002933 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002934 bool comparison = false;
2935
2936 switch (op) {
2937 case glslang::EOpAdd:
2938 case glslang::EOpAddAssign:
2939 if (isFloat)
2940 binOp = spv::OpFAdd;
2941 else
2942 binOp = spv::OpIAdd;
2943 break;
2944 case glslang::EOpSub:
2945 case glslang::EOpSubAssign:
2946 if (isFloat)
2947 binOp = spv::OpFSub;
2948 else
2949 binOp = spv::OpISub;
2950 break;
2951 case glslang::EOpMul:
2952 case glslang::EOpMulAssign:
2953 if (isFloat)
2954 binOp = spv::OpFMul;
2955 else
2956 binOp = spv::OpIMul;
2957 break;
2958 case glslang::EOpVectorTimesScalar:
2959 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06002960 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06002961 if (builder.isVector(right))
2962 std::swap(left, right);
2963 assert(builder.isScalar(right));
2964 needMatchingVectors = false;
2965 binOp = spv::OpVectorTimesScalar;
2966 } else
2967 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002968 break;
2969 case glslang::EOpVectorTimesMatrix:
2970 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002971 binOp = spv::OpVectorTimesMatrix;
2972 break;
2973 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002974 binOp = spv::OpMatrixTimesVector;
2975 break;
2976 case glslang::EOpMatrixTimesScalar:
2977 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002978 binOp = spv::OpMatrixTimesScalar;
2979 break;
2980 case glslang::EOpMatrixTimesMatrix:
2981 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002982 binOp = spv::OpMatrixTimesMatrix;
2983 break;
2984 case glslang::EOpOuterProduct:
2985 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002986 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002987 break;
2988
2989 case glslang::EOpDiv:
2990 case glslang::EOpDivAssign:
2991 if (isFloat)
2992 binOp = spv::OpFDiv;
2993 else if (isUnsigned)
2994 binOp = spv::OpUDiv;
2995 else
2996 binOp = spv::OpSDiv;
2997 break;
2998 case glslang::EOpMod:
2999 case glslang::EOpModAssign:
3000 if (isFloat)
3001 binOp = spv::OpFMod;
3002 else if (isUnsigned)
3003 binOp = spv::OpUMod;
3004 else
3005 binOp = spv::OpSMod;
3006 break;
3007 case glslang::EOpRightShift:
3008 case glslang::EOpRightShiftAssign:
3009 if (isUnsigned)
3010 binOp = spv::OpShiftRightLogical;
3011 else
3012 binOp = spv::OpShiftRightArithmetic;
3013 break;
3014 case glslang::EOpLeftShift:
3015 case glslang::EOpLeftShiftAssign:
3016 binOp = spv::OpShiftLeftLogical;
3017 break;
3018 case glslang::EOpAnd:
3019 case glslang::EOpAndAssign:
3020 binOp = spv::OpBitwiseAnd;
3021 break;
3022 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003023 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003024 binOp = spv::OpLogicalAnd;
3025 break;
3026 case glslang::EOpInclusiveOr:
3027 case glslang::EOpInclusiveOrAssign:
3028 binOp = spv::OpBitwiseOr;
3029 break;
3030 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003031 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 binOp = spv::OpLogicalOr;
3033 break;
3034 case glslang::EOpExclusiveOr:
3035 case glslang::EOpExclusiveOrAssign:
3036 binOp = spv::OpBitwiseXor;
3037 break;
3038 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003039 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003040 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003041 break;
3042
3043 case glslang::EOpLessThan:
3044 case glslang::EOpGreaterThan:
3045 case glslang::EOpLessThanEqual:
3046 case glslang::EOpGreaterThanEqual:
3047 case glslang::EOpEqual:
3048 case glslang::EOpNotEqual:
3049 case glslang::EOpVectorEqual:
3050 case glslang::EOpVectorNotEqual:
3051 comparison = true;
3052 break;
3053 default:
3054 break;
3055 }
3056
John Kessenich7c1aa102015-10-15 13:29:11 -06003057 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003058 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003059 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003060 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003061 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003062
3063 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003064 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003065 builder.promoteScalar(precision, left, right);
3066
qining25262b32016-05-06 17:25:16 -04003067 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3068 addDecoration(result, noContraction);
3069 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003070 }
3071
3072 if (! comparison)
3073 return 0;
3074
John Kessenich7c1aa102015-10-15 13:29:11 -06003075 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003076
3077 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
3078 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
3079
John Kessenich22118352015-12-21 20:54:09 -07003080 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003081 }
3082
3083 switch (op) {
3084 case glslang::EOpLessThan:
3085 if (isFloat)
3086 binOp = spv::OpFOrdLessThan;
3087 else if (isUnsigned)
3088 binOp = spv::OpULessThan;
3089 else
3090 binOp = spv::OpSLessThan;
3091 break;
3092 case glslang::EOpGreaterThan:
3093 if (isFloat)
3094 binOp = spv::OpFOrdGreaterThan;
3095 else if (isUnsigned)
3096 binOp = spv::OpUGreaterThan;
3097 else
3098 binOp = spv::OpSGreaterThan;
3099 break;
3100 case glslang::EOpLessThanEqual:
3101 if (isFloat)
3102 binOp = spv::OpFOrdLessThanEqual;
3103 else if (isUnsigned)
3104 binOp = spv::OpULessThanEqual;
3105 else
3106 binOp = spv::OpSLessThanEqual;
3107 break;
3108 case glslang::EOpGreaterThanEqual:
3109 if (isFloat)
3110 binOp = spv::OpFOrdGreaterThanEqual;
3111 else if (isUnsigned)
3112 binOp = spv::OpUGreaterThanEqual;
3113 else
3114 binOp = spv::OpSGreaterThanEqual;
3115 break;
3116 case glslang::EOpEqual:
3117 case glslang::EOpVectorEqual:
3118 if (isFloat)
3119 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003120 else if (isBool)
3121 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003122 else
3123 binOp = spv::OpIEqual;
3124 break;
3125 case glslang::EOpNotEqual:
3126 case glslang::EOpVectorNotEqual:
3127 if (isFloat)
3128 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003129 else if (isBool)
3130 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003131 else
3132 binOp = spv::OpINotEqual;
3133 break;
3134 default:
3135 break;
3136 }
3137
qining25262b32016-05-06 17:25:16 -04003138 if (binOp != spv::OpNop) {
3139 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3140 addDecoration(result, noContraction);
3141 return builder.setPrecision(result, precision);
3142 }
John Kessenich140f3df2015-06-26 16:58:36 -06003143
3144 return 0;
3145}
3146
John Kessenich04bb8a02015-12-12 12:28:14 -07003147//
3148// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3149// These can be any of:
3150//
3151// matrix * scalar
3152// scalar * matrix
3153// matrix * matrix linear algebraic
3154// matrix * vector
3155// vector * matrix
3156// matrix * matrix componentwise
3157// matrix op matrix op in {+, -, /}
3158// matrix op scalar op in {+, -, /}
3159// scalar op matrix op in {+, -, /}
3160//
qining25262b32016-05-06 17:25:16 -04003161spv::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 -07003162{
3163 bool firstClass = true;
3164
3165 // First, handle first-class matrix operations (* and matrix/scalar)
3166 switch (op) {
3167 case spv::OpFDiv:
3168 if (builder.isMatrix(left) && builder.isScalar(right)) {
3169 // turn matrix / scalar into a multiply...
3170 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3171 op = spv::OpMatrixTimesScalar;
3172 } else
3173 firstClass = false;
3174 break;
3175 case spv::OpMatrixTimesScalar:
3176 if (builder.isMatrix(right))
3177 std::swap(left, right);
3178 assert(builder.isScalar(right));
3179 break;
3180 case spv::OpVectorTimesMatrix:
3181 assert(builder.isVector(left));
3182 assert(builder.isMatrix(right));
3183 break;
3184 case spv::OpMatrixTimesVector:
3185 assert(builder.isMatrix(left));
3186 assert(builder.isVector(right));
3187 break;
3188 case spv::OpMatrixTimesMatrix:
3189 assert(builder.isMatrix(left));
3190 assert(builder.isMatrix(right));
3191 break;
3192 default:
3193 firstClass = false;
3194 break;
3195 }
3196
qining25262b32016-05-06 17:25:16 -04003197 if (firstClass) {
3198 spv::Id result = builder.createBinOp(op, typeId, left, right);
3199 addDecoration(result, noContraction);
3200 return builder.setPrecision(result, precision);
3201 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003202
LoopDawg592860c2016-06-09 08:57:35 -06003203 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003204 // The result type of all of them is the same type as the (a) matrix operand.
3205 // The algorithm is to:
3206 // - break the matrix(es) into vectors
3207 // - smear any scalar to a vector
3208 // - do vector operations
3209 // - make a matrix out the vector results
3210 switch (op) {
3211 case spv::OpFAdd:
3212 case spv::OpFSub:
3213 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003214 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003215 case spv::OpFMul:
3216 {
3217 // one time set up...
3218 bool leftMat = builder.isMatrix(left);
3219 bool rightMat = builder.isMatrix(right);
3220 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3221 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3222 spv::Id scalarType = builder.getScalarTypeId(typeId);
3223 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3224 std::vector<spv::Id> results;
3225 spv::Id smearVec = spv::NoResult;
3226 if (builder.isScalar(left))
3227 smearVec = builder.smearScalar(precision, left, vecType);
3228 else if (builder.isScalar(right))
3229 smearVec = builder.smearScalar(precision, right, vecType);
3230
3231 // do each vector op
3232 for (unsigned int c = 0; c < numCols; ++c) {
3233 std::vector<unsigned int> indexes;
3234 indexes.push_back(c);
3235 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3236 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003237 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3238 addDecoration(result, noContraction);
3239 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003240 }
3241
3242 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003243 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003244 }
3245 default:
3246 assert(0);
3247 return spv::NoResult;
3248 }
3249}
3250
qining25262b32016-05-06 17:25:16 -04003251spv::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 -06003252{
3253 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003254 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003255 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003256 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003257 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003258
3259 switch (op) {
3260 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003261 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003262 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003263 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003264 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003265 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003266 unaryOp = spv::OpSNegate;
3267 break;
3268
3269 case glslang::EOpLogicalNot:
3270 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003271 unaryOp = spv::OpLogicalNot;
3272 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003273 case glslang::EOpBitwiseNot:
3274 unaryOp = spv::OpNot;
3275 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003276
John Kessenich140f3df2015-06-26 16:58:36 -06003277 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003278 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003279 break;
3280 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003281 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003282 break;
3283 case glslang::EOpTranspose:
3284 unaryOp = spv::OpTranspose;
3285 break;
3286
3287 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003288 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003289 break;
3290 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003291 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003292 break;
3293 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003294 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003295 break;
3296 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003297 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003298 break;
3299 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003300 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003301 break;
3302 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003303 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003304 break;
3305 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003306 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003307 break;
3308 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003309 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003310 break;
3311
3312 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003317 break;
3318 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003319 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003322 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003323 break;
3324 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003325 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003326 break;
3327 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003328 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003329 break;
3330
3331 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003332 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003333 break;
3334 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003335 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003336 break;
3337
3338 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003339 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003340 break;
3341 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003342 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003343 break;
3344 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003345 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003346 break;
3347 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003348 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003349 break;
3350 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003351 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003354 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003355 break;
3356
3357 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003358 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003359 break;
3360 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003361 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003362 break;
3363 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003364 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003365 break;
3366 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003367 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003368 break;
3369 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003370 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003371 break;
3372 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003373 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003374 break;
3375
3376 case glslang::EOpIsNan:
3377 unaryOp = spv::OpIsNan;
3378 break;
3379 case glslang::EOpIsInf:
3380 unaryOp = spv::OpIsInf;
3381 break;
LoopDawg592860c2016-06-09 08:57:35 -06003382 case glslang::EOpIsFinite:
3383 unaryOp = spv::OpIsFinite;
3384 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003385
Rex Xucbc426e2015-12-15 16:03:10 +08003386 case glslang::EOpFloatBitsToInt:
3387 case glslang::EOpFloatBitsToUint:
3388 case glslang::EOpIntBitsToFloat:
3389 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003390 case glslang::EOpDoubleBitsToInt64:
3391 case glslang::EOpDoubleBitsToUint64:
3392 case glslang::EOpInt64BitsToDouble:
3393 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003394 unaryOp = spv::OpBitcast;
3395 break;
3396
John Kessenich140f3df2015-06-26 16:58:36 -06003397 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003398 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003399 break;
3400 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003401 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003402 break;
3403 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003404 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003405 break;
3406 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003407 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003408 break;
3409 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003410 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003411 break;
3412 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003413 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003414 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003415 case glslang::EOpPackSnorm4x8:
3416 libCall = spv::GLSLstd450PackSnorm4x8;
3417 break;
3418 case glslang::EOpUnpackSnorm4x8:
3419 libCall = spv::GLSLstd450UnpackSnorm4x8;
3420 break;
3421 case glslang::EOpPackUnorm4x8:
3422 libCall = spv::GLSLstd450PackUnorm4x8;
3423 break;
3424 case glslang::EOpUnpackUnorm4x8:
3425 libCall = spv::GLSLstd450UnpackUnorm4x8;
3426 break;
3427 case glslang::EOpPackDouble2x32:
3428 libCall = spv::GLSLstd450PackDouble2x32;
3429 break;
3430 case glslang::EOpUnpackDouble2x32:
3431 libCall = spv::GLSLstd450UnpackDouble2x32;
3432 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003433
Rex Xu8ff43de2016-04-22 16:51:45 +08003434 case glslang::EOpPackInt2x32:
3435 case glslang::EOpUnpackInt2x32:
3436 case glslang::EOpPackUint2x32:
3437 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003438 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003439 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3440 break;
3441
John Kessenich140f3df2015-06-26 16:58:36 -06003442 case glslang::EOpDPdx:
3443 unaryOp = spv::OpDPdx;
3444 break;
3445 case glslang::EOpDPdy:
3446 unaryOp = spv::OpDPdy;
3447 break;
3448 case glslang::EOpFwidth:
3449 unaryOp = spv::OpFwidth;
3450 break;
3451 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003452 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003453 unaryOp = spv::OpDPdxFine;
3454 break;
3455 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003456 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003457 unaryOp = spv::OpDPdyFine;
3458 break;
3459 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003460 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003461 unaryOp = spv::OpFwidthFine;
3462 break;
3463 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003464 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003465 unaryOp = spv::OpDPdxCoarse;
3466 break;
3467 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003468 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003469 unaryOp = spv::OpDPdyCoarse;
3470 break;
3471 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003472 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003473 unaryOp = spv::OpFwidthCoarse;
3474 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003475 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003476 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003477 libCall = spv::GLSLstd450InterpolateAtCentroid;
3478 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 case glslang::EOpAny:
3480 unaryOp = spv::OpAny;
3481 break;
3482 case glslang::EOpAll:
3483 unaryOp = spv::OpAll;
3484 break;
3485
3486 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003487 if (isFloat)
3488 libCall = spv::GLSLstd450FAbs;
3489 else
3490 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003491 break;
3492 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003493 if (isFloat)
3494 libCall = spv::GLSLstd450FSign;
3495 else
3496 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003497 break;
3498
John Kessenichfc51d282015-08-19 13:34:18 -06003499 case glslang::EOpAtomicCounterIncrement:
3500 case glslang::EOpAtomicCounterDecrement:
3501 case glslang::EOpAtomicCounter:
3502 {
3503 // Handle all of the atomics in one place, in createAtomicOperation()
3504 std::vector<spv::Id> operands;
3505 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003506 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003507 }
3508
John Kessenichfc51d282015-08-19 13:34:18 -06003509 case glslang::EOpBitFieldReverse:
3510 unaryOp = spv::OpBitReverse;
3511 break;
3512 case glslang::EOpBitCount:
3513 unaryOp = spv::OpBitCount;
3514 break;
3515 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003516 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003517 break;
3518 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003519 if (isUnsigned)
3520 libCall = spv::GLSLstd450FindUMsb;
3521 else
3522 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003523 break;
3524
Rex Xu574ab042016-04-14 16:53:07 +08003525 case glslang::EOpBallot:
3526 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003527 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003528 libCall = spv::GLSLstd450Bad;
3529 break;
3530
Rex Xu338b1852016-05-05 20:38:33 +08003531 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003532 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003533 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003534#ifdef AMD_EXTENSIONS
3535 case glslang::EOpMinInvocations:
3536 case glslang::EOpMaxInvocations:
3537 case glslang::EOpAddInvocations:
3538 case glslang::EOpMinInvocationsNonUniform:
3539 case glslang::EOpMaxInvocationsNonUniform:
3540 case glslang::EOpAddInvocationsNonUniform:
3541#endif
3542 return createInvocationsOperation(op, typeId, operand, typeProxy);
3543
3544#ifdef AMD_EXTENSIONS
3545 case glslang::EOpMbcnt:
3546 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3547 libCall = spv::MbcntAMD;
3548 break;
3549
3550 case glslang::EOpCubeFaceIndex:
3551 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3552 libCall = spv::CubeFaceIndexAMD;
3553 break;
3554
3555 case glslang::EOpCubeFaceCoord:
3556 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3557 libCall = spv::CubeFaceCoordAMD;
3558 break;
3559#endif
Rex Xu338b1852016-05-05 20:38:33 +08003560
John Kessenich140f3df2015-06-26 16:58:36 -06003561 default:
3562 return 0;
3563 }
3564
3565 spv::Id id;
3566 if (libCall >= 0) {
3567 std::vector<spv::Id> args;
3568 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003569 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003570 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003571 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003572 }
John Kessenich140f3df2015-06-26 16:58:36 -06003573
qining25262b32016-05-06 17:25:16 -04003574 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003575 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003576}
3577
John Kessenich7a53f762016-01-20 11:19:27 -07003578// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003579spv::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 -07003580{
3581 // Handle unary operations vector by vector.
3582 // The result type is the same type as the original type.
3583 // The algorithm is to:
3584 // - break the matrix into vectors
3585 // - apply the operation to each vector
3586 // - make a matrix out the vector results
3587
3588 // get the types sorted out
3589 int numCols = builder.getNumColumns(operand);
3590 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003591 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3592 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003593 std::vector<spv::Id> results;
3594
3595 // do each vector op
3596 for (int c = 0; c < numCols; ++c) {
3597 std::vector<unsigned int> indexes;
3598 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003599 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3600 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3601 addDecoration(destVec, noContraction);
3602 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003603 }
3604
3605 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003606 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003607}
3608
Rex Xu73e3ce72016-04-27 18:48:17 +08003609spv::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 -06003610{
3611 spv::Op convOp = spv::OpNop;
3612 spv::Id zero = 0;
3613 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003614 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003615
3616 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3617
3618 switch (op) {
3619 case glslang::EOpConvIntToBool:
3620 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003621 case glslang::EOpConvInt64ToBool:
3622 case glslang::EOpConvUint64ToBool:
3623 zero = (op == glslang::EOpConvInt64ToBool ||
3624 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003625 zero = makeSmearedConstant(zero, vectorSize);
3626 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3627
3628 case glslang::EOpConvFloatToBool:
3629 zero = builder.makeFloatConstant(0.0F);
3630 zero = makeSmearedConstant(zero, vectorSize);
3631 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3632
3633 case glslang::EOpConvDoubleToBool:
3634 zero = builder.makeDoubleConstant(0.0);
3635 zero = makeSmearedConstant(zero, vectorSize);
3636 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3637
3638 case glslang::EOpConvBoolToFloat:
3639 convOp = spv::OpSelect;
3640 zero = builder.makeFloatConstant(0.0);
3641 one = builder.makeFloatConstant(1.0);
3642 break;
3643 case glslang::EOpConvBoolToDouble:
3644 convOp = spv::OpSelect;
3645 zero = builder.makeDoubleConstant(0.0);
3646 one = builder.makeDoubleConstant(1.0);
3647 break;
3648 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003649 case glslang::EOpConvBoolToInt64:
3650 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3651 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003652 convOp = spv::OpSelect;
3653 break;
3654 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003655 case glslang::EOpConvBoolToUint64:
3656 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3657 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003658 convOp = spv::OpSelect;
3659 break;
3660
3661 case glslang::EOpConvIntToFloat:
3662 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003663 case glslang::EOpConvInt64ToFloat:
3664 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003665 convOp = spv::OpConvertSToF;
3666 break;
3667
3668 case glslang::EOpConvUintToFloat:
3669 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003670 case glslang::EOpConvUint64ToFloat:
3671 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003672 convOp = spv::OpConvertUToF;
3673 break;
3674
3675 case glslang::EOpConvDoubleToFloat:
3676 case glslang::EOpConvFloatToDouble:
3677 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003678 if (builder.isMatrixType(destType))
3679 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003680 break;
3681
3682 case glslang::EOpConvFloatToInt:
3683 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003684 case glslang::EOpConvFloatToInt64:
3685 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003686 convOp = spv::OpConvertFToS;
3687 break;
3688
3689 case glslang::EOpConvUintToInt:
3690 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003691 case glslang::EOpConvUint64ToInt64:
3692 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003693 if (builder.isInSpecConstCodeGenMode()) {
3694 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003695 zero = (op == glslang::EOpConvUintToInt64 ||
3696 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003697 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003698 // Use OpIAdd, instead of OpBitcast to do the conversion when
3699 // generating for OpSpecConstantOp instruction.
3700 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3701 }
3702 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003703 convOp = spv::OpBitcast;
3704 break;
3705
3706 case glslang::EOpConvFloatToUint:
3707 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003708 case glslang::EOpConvFloatToUint64:
3709 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003710 convOp = spv::OpConvertFToU;
3711 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003712
3713 case glslang::EOpConvIntToInt64:
3714 case glslang::EOpConvInt64ToInt:
3715 convOp = spv::OpSConvert;
3716 break;
3717
3718 case glslang::EOpConvUintToUint64:
3719 case glslang::EOpConvUint64ToUint:
3720 convOp = spv::OpUConvert;
3721 break;
3722
3723 case glslang::EOpConvIntToUint64:
3724 case glslang::EOpConvInt64ToUint:
3725 case glslang::EOpConvUint64ToInt:
3726 case glslang::EOpConvUintToInt64:
3727 // OpSConvert/OpUConvert + OpBitCast
3728 switch (op) {
3729 case glslang::EOpConvIntToUint64:
3730 convOp = spv::OpSConvert;
3731 type = builder.makeIntType(64);
3732 break;
3733 case glslang::EOpConvInt64ToUint:
3734 convOp = spv::OpSConvert;
3735 type = builder.makeIntType(32);
3736 break;
3737 case glslang::EOpConvUint64ToInt:
3738 convOp = spv::OpUConvert;
3739 type = builder.makeUintType(32);
3740 break;
3741 case glslang::EOpConvUintToInt64:
3742 convOp = spv::OpUConvert;
3743 type = builder.makeUintType(64);
3744 break;
3745 default:
3746 assert(0);
3747 break;
3748 }
3749
3750 if (vectorSize > 0)
3751 type = builder.makeVectorType(type, vectorSize);
3752
3753 operand = builder.createUnaryOp(convOp, type, operand);
3754
3755 if (builder.isInSpecConstCodeGenMode()) {
3756 // Build zero scalar or vector for OpIAdd.
3757 zero = (op == glslang::EOpConvIntToUint64 ||
3758 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3759 zero = makeSmearedConstant(zero, vectorSize);
3760 // Use OpIAdd, instead of OpBitcast to do the conversion when
3761 // generating for OpSpecConstantOp instruction.
3762 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3763 }
3764 // For normal run-time conversion instruction, use OpBitcast.
3765 convOp = spv::OpBitcast;
3766 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003767 default:
3768 break;
3769 }
3770
3771 spv::Id result = 0;
3772 if (convOp == spv::OpNop)
3773 return result;
3774
3775 if (convOp == spv::OpSelect) {
3776 zero = makeSmearedConstant(zero, vectorSize);
3777 one = makeSmearedConstant(one, vectorSize);
3778 result = builder.createTriOp(convOp, destType, operand, one, zero);
3779 } else
3780 result = builder.createUnaryOp(convOp, destType, operand);
3781
John Kessenich32cfd492016-02-02 12:37:46 -07003782 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003783}
3784
3785spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3786{
3787 if (vectorSize == 0)
3788 return constant;
3789
3790 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3791 std::vector<spv::Id> components;
3792 for (int c = 0; c < vectorSize; ++c)
3793 components.push_back(constant);
3794 return builder.makeCompositeConstant(vectorTypeId, components);
3795}
3796
John Kessenich426394d2015-07-23 10:22:48 -06003797// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003798spv::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 -06003799{
3800 spv::Op opCode = spv::OpNop;
3801
3802 switch (op) {
3803 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003804 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003805 opCode = spv::OpAtomicIAdd;
3806 break;
3807 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003808 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003809 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003810 break;
3811 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003812 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003813 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003814 break;
3815 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003816 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003817 opCode = spv::OpAtomicAnd;
3818 break;
3819 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003820 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003821 opCode = spv::OpAtomicOr;
3822 break;
3823 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003824 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003825 opCode = spv::OpAtomicXor;
3826 break;
3827 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003828 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003829 opCode = spv::OpAtomicExchange;
3830 break;
3831 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003832 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003833 opCode = spv::OpAtomicCompareExchange;
3834 break;
3835 case glslang::EOpAtomicCounterIncrement:
3836 opCode = spv::OpAtomicIIncrement;
3837 break;
3838 case glslang::EOpAtomicCounterDecrement:
3839 opCode = spv::OpAtomicIDecrement;
3840 break;
3841 case glslang::EOpAtomicCounter:
3842 opCode = spv::OpAtomicLoad;
3843 break;
3844 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003845 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003846 break;
3847 }
3848
3849 // Sort out the operands
3850 // - mapping from glslang -> SPV
3851 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003852 // - compare-exchange swaps the value and comparator
3853 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003854 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3855 auto opIt = operands.begin(); // walk the glslang operands
3856 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003857 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3858 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3859 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003860 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3861 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003862 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003863 spvAtomicOperands.push_back(*(opIt + 1));
3864 spvAtomicOperands.push_back(*opIt);
3865 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003866 }
John Kessenich426394d2015-07-23 10:22:48 -06003867
John Kessenich3e60a6f2015-09-14 22:45:16 -06003868 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003869 for (; opIt != operands.end(); ++opIt)
3870 spvAtomicOperands.push_back(*opIt);
3871
3872 return builder.createOp(opCode, typeId, spvAtomicOperands);
3873}
3874
John Kessenich91cef522016-05-05 16:45:40 -06003875// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003876spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003877{
Rex Xu9d93a232016-05-05 12:30:44 +08003878 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3879 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3880
John Kessenich91cef522016-05-05 16:45:40 -06003881 builder.addCapability(spv::CapabilityGroups);
3882
3883 std::vector<spv::Id> operands;
3884 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003885#ifdef AMD_EXTENSIONS
3886 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3887 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3888 operands.push_back(spv::GroupOperationReduce);
3889#endif
John Kessenich91cef522016-05-05 16:45:40 -06003890 operands.push_back(operand);
3891
3892 switch (op) {
3893 case glslang::EOpAnyInvocation:
3894 case glslang::EOpAllInvocations:
3895 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3896
3897 case glslang::EOpAllInvocationsEqual:
3898 {
3899 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3900 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3901
3902 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3903 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3904 }
Rex Xu9d93a232016-05-05 12:30:44 +08003905#ifdef AMD_EXTENSIONS
3906 case glslang::EOpMinInvocations:
3907 case glslang::EOpMaxInvocations:
3908 case glslang::EOpAddInvocations:
3909 {
3910 spv::Op spvOp = spv::OpNop;
3911 if (op == glslang::EOpMinInvocations) {
3912 if (isFloat)
3913 spvOp = spv::OpGroupFMin;
3914 else {
3915 if (isUnsigned)
3916 spvOp = spv::OpGroupUMin;
3917 else
3918 spvOp = spv::OpGroupSMin;
3919 }
3920 } else if (op == glslang::EOpMaxInvocations) {
3921 if (isFloat)
3922 spvOp = spv::OpGroupFMax;
3923 else {
3924 if (isUnsigned)
3925 spvOp = spv::OpGroupUMax;
3926 else
3927 spvOp = spv::OpGroupSMax;
3928 }
3929 } else {
3930 if (isFloat)
3931 spvOp = spv::OpGroupFAdd;
3932 else
3933 spvOp = spv::OpGroupIAdd;
3934 }
3935
3936 return builder.createOp(spvOp, typeId, operands);
3937 }
3938 case glslang::EOpMinInvocationsNonUniform:
3939 case glslang::EOpMaxInvocationsNonUniform:
3940 case glslang::EOpAddInvocationsNonUniform:
3941 {
3942 spv::Op spvOp = spv::OpNop;
3943 if (op == glslang::EOpMinInvocationsNonUniform) {
3944 if (isFloat)
3945 spvOp = spv::OpGroupFMinNonUniformAMD;
3946 else {
3947 if (isUnsigned)
3948 spvOp = spv::OpGroupUMinNonUniformAMD;
3949 else
3950 spvOp = spv::OpGroupSMinNonUniformAMD;
3951 }
3952 }
3953 else if (op == glslang::EOpMaxInvocationsNonUniform) {
3954 if (isFloat)
3955 spvOp = spv::OpGroupFMaxNonUniformAMD;
3956 else {
3957 if (isUnsigned)
3958 spvOp = spv::OpGroupUMaxNonUniformAMD;
3959 else
3960 spvOp = spv::OpGroupSMaxNonUniformAMD;
3961 }
3962 }
3963 else {
3964 if (isFloat)
3965 spvOp = spv::OpGroupFAddNonUniformAMD;
3966 else
3967 spvOp = spv::OpGroupIAddNonUniformAMD;
3968 }
3969
3970 return builder.createOp(spvOp, typeId, operands);
3971 }
3972#endif
John Kessenich91cef522016-05-05 16:45:40 -06003973 default:
3974 logger->missingFunctionality("invocation operation");
3975 return spv::NoResult;
3976 }
3977}
3978
John Kessenich5e4b1242015-08-06 22:53:06 -06003979spv::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 -06003980{
Rex Xu8ff43de2016-04-22 16:51:45 +08003981 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003982 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3983
John Kessenich140f3df2015-06-26 16:58:36 -06003984 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003985 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003986 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003987 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003988 spv::Id typeId0 = 0;
3989 if (consumedOperands > 0)
3990 typeId0 = builder.getTypeId(operands[0]);
3991 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003992
3993 switch (op) {
3994 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003995 if (isFloat)
3996 libCall = spv::GLSLstd450FMin;
3997 else if (isUnsigned)
3998 libCall = spv::GLSLstd450UMin;
3999 else
4000 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004001 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004002 break;
4003 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004004 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004005 break;
4006 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004007 if (isFloat)
4008 libCall = spv::GLSLstd450FMax;
4009 else if (isUnsigned)
4010 libCall = spv::GLSLstd450UMax;
4011 else
4012 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004013 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004014 break;
4015 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004016 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004017 break;
4018 case glslang::EOpDot:
4019 opCode = spv::OpDot;
4020 break;
4021 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004022 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004023 break;
4024
4025 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004026 if (isFloat)
4027 libCall = spv::GLSLstd450FClamp;
4028 else if (isUnsigned)
4029 libCall = spv::GLSLstd450UClamp;
4030 else
4031 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004032 builder.promoteScalar(precision, operands.front(), operands[1]);
4033 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004034 break;
4035 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004036 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4037 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004038 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004039 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004040 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004041 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004042 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004043 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004044 break;
4045 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004047 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004048 break;
4049 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004051 builder.promoteScalar(precision, operands[0], operands[2]);
4052 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004053 break;
4054
4055 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
4058 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004070 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004071 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004072 libCall = spv::GLSLstd450InterpolateAtSample;
4073 break;
4074 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004075 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004076 libCall = spv::GLSLstd450InterpolateAtOffset;
4077 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004078 case glslang::EOpAddCarry:
4079 opCode = spv::OpIAddCarry;
4080 typeId = builder.makeStructResultType(typeId0, typeId0);
4081 consumedOperands = 2;
4082 break;
4083 case glslang::EOpSubBorrow:
4084 opCode = spv::OpISubBorrow;
4085 typeId = builder.makeStructResultType(typeId0, typeId0);
4086 consumedOperands = 2;
4087 break;
4088 case glslang::EOpUMulExtended:
4089 opCode = spv::OpUMulExtended;
4090 typeId = builder.makeStructResultType(typeId0, typeId0);
4091 consumedOperands = 2;
4092 break;
4093 case glslang::EOpIMulExtended:
4094 opCode = spv::OpSMulExtended;
4095 typeId = builder.makeStructResultType(typeId0, typeId0);
4096 consumedOperands = 2;
4097 break;
4098 case glslang::EOpBitfieldExtract:
4099 if (isUnsigned)
4100 opCode = spv::OpBitFieldUExtract;
4101 else
4102 opCode = spv::OpBitFieldSExtract;
4103 break;
4104 case glslang::EOpBitfieldInsert:
4105 opCode = spv::OpBitFieldInsert;
4106 break;
4107
4108 case glslang::EOpFma:
4109 libCall = spv::GLSLstd450Fma;
4110 break;
4111 case glslang::EOpFrexp:
4112 libCall = spv::GLSLstd450FrexpStruct;
4113 if (builder.getNumComponents(operands[0]) == 1)
4114 frexpIntType = builder.makeIntegerType(32, true);
4115 else
4116 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4117 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4118 consumedOperands = 1;
4119 break;
4120 case glslang::EOpLdexp:
4121 libCall = spv::GLSLstd450Ldexp;
4122 break;
4123
Rex Xu574ab042016-04-14 16:53:07 +08004124 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004125 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004126 libCall = spv::GLSLstd450Bad;
4127 break;
4128
Rex Xu9d93a232016-05-05 12:30:44 +08004129#ifdef AMD_EXTENSIONS
4130 case glslang::EOpSwizzleInvocations:
4131 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4132 libCall = spv::SwizzleInvocationsAMD;
4133 break;
4134 case glslang::EOpSwizzleInvocationsMasked:
4135 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4136 libCall = spv::SwizzleInvocationsMaskedAMD;
4137 break;
4138 case glslang::EOpWriteInvocation:
4139 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4140 libCall = spv::WriteInvocationAMD;
4141 break;
4142
4143 case glslang::EOpMin3:
4144 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4145 if (isFloat)
4146 libCall = spv::FMin3AMD;
4147 else {
4148 if (isUnsigned)
4149 libCall = spv::UMin3AMD;
4150 else
4151 libCall = spv::SMin3AMD;
4152 }
4153 break;
4154 case glslang::EOpMax3:
4155 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4156 if (isFloat)
4157 libCall = spv::FMax3AMD;
4158 else {
4159 if (isUnsigned)
4160 libCall = spv::UMax3AMD;
4161 else
4162 libCall = spv::SMax3AMD;
4163 }
4164 break;
4165 case glslang::EOpMid3:
4166 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4167 if (isFloat)
4168 libCall = spv::FMid3AMD;
4169 else {
4170 if (isUnsigned)
4171 libCall = spv::UMid3AMD;
4172 else
4173 libCall = spv::SMid3AMD;
4174 }
4175 break;
4176
4177 case glslang::EOpInterpolateAtVertex:
4178 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4179 libCall = spv::InterpolateAtVertexAMD;
4180 break;
4181#endif
4182
John Kessenich140f3df2015-06-26 16:58:36 -06004183 default:
4184 return 0;
4185 }
4186
4187 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004188 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004189 // Use an extended instruction from the standard library.
4190 // Construct the call arguments, without modifying the original operands vector.
4191 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4192 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004193 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004194 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004195 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004196 case 0:
4197 // should all be handled by visitAggregate and createNoArgOperation
4198 assert(0);
4199 return 0;
4200 case 1:
4201 // should all be handled by createUnaryOperation
4202 assert(0);
4203 return 0;
4204 case 2:
4205 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4206 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004207 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004208 // anything 3 or over doesn't have l-value operands, so all should be consumed
4209 assert(consumedOperands == operands.size());
4210 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004211 break;
4212 }
4213 }
4214
John Kessenich55e7d112015-11-15 21:33:39 -07004215 // Decode the return types that were structures
4216 switch (op) {
4217 case glslang::EOpAddCarry:
4218 case glslang::EOpSubBorrow:
4219 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4220 id = builder.createCompositeExtract(id, typeId0, 0);
4221 break;
4222 case glslang::EOpUMulExtended:
4223 case glslang::EOpIMulExtended:
4224 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4225 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4226 break;
4227 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004228 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004229 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4230 id = builder.createCompositeExtract(id, typeId0, 0);
4231 break;
4232 default:
4233 break;
4234 }
4235
John Kessenich32cfd492016-02-02 12:37:46 -07004236 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004237}
4238
Rex Xu9d93a232016-05-05 12:30:44 +08004239// Intrinsics with no arguments (or no return value, and no precision).
4240spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004241{
4242 // TODO: get the barrier operands correct
4243
4244 switch (op) {
4245 case glslang::EOpEmitVertex:
4246 builder.createNoResultOp(spv::OpEmitVertex);
4247 return 0;
4248 case glslang::EOpEndPrimitive:
4249 builder.createNoResultOp(spv::OpEndPrimitive);
4250 return 0;
4251 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004252 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004253 return 0;
4254 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004255 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004256 return 0;
4257 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004258 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004259 return 0;
4260 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004261 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004262 return 0;
4263 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004264 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004265 return 0;
4266 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004267 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004268 return 0;
4269 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004270 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004271 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004272 case glslang::EOpAllMemoryBarrierWithGroupSync:
4273 // Control barrier with non-"None" semantic is also a memory barrier.
4274 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4275 return 0;
4276 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4277 // Control barrier with non-"None" semantic is also a memory barrier.
4278 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4279 return 0;
4280 case glslang::EOpWorkgroupMemoryBarrier:
4281 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4282 return 0;
4283 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4284 // Control barrier with non-"None" semantic is also a memory barrier.
4285 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4286 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004287#ifdef AMD_EXTENSIONS
4288 case glslang::EOpTime:
4289 {
4290 std::vector<spv::Id> args; // Dummy arguments
4291 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4292 return builder.setPrecision(id, precision);
4293 }
4294#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004295 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004296 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004297 return 0;
4298 }
4299}
4300
4301spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4302{
John Kessenich2f273362015-07-18 22:34:27 -06004303 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004304 spv::Id id;
4305 if (symbolValues.end() != iter) {
4306 id = iter->second;
4307 return id;
4308 }
4309
4310 // it was not found, create it
4311 id = createSpvVariable(symbol);
4312 symbolValues[symbol->getId()] = id;
4313
Rex Xuc884b4a2016-06-29 15:03:44 +08004314 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004315 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004316 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004317 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004318 if (symbol->getType().getQualifier().hasSpecConstantId())
4319 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004320 if (symbol->getQualifier().hasIndex())
4321 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4322 if (symbol->getQualifier().hasComponent())
4323 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4324 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004325 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004326 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004327 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004328 if (symbol->getQualifier().hasXfbBuffer())
4329 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4330 if (symbol->getQualifier().hasXfbOffset())
4331 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4332 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004333 // atomic counters use this:
4334 if (symbol->getQualifier().hasOffset())
4335 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004336 }
4337
scygan2c864272016-05-18 18:09:17 +02004338 if (symbol->getQualifier().hasLocation())
4339 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004340 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004341 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004342 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004343 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004344 }
John Kessenich140f3df2015-06-26 16:58:36 -06004345 if (symbol->getQualifier().hasSet())
4346 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004347 else if (IsDescriptorResource(symbol->getType())) {
4348 // default to 0
4349 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4350 }
John Kessenich140f3df2015-06-26 16:58:36 -06004351 if (symbol->getQualifier().hasBinding())
4352 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004353 if (symbol->getQualifier().hasAttachment())
4354 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004355 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004356 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004357 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004358 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004359 if (symbol->getQualifier().hasXfbBuffer())
4360 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4361 }
4362
Rex Xu1da878f2016-02-21 20:59:01 +08004363 if (symbol->getType().isImage()) {
4364 std::vector<spv::Decoration> memory;
4365 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4366 for (unsigned int i = 0; i < memory.size(); ++i)
4367 addDecoration(id, memory[i]);
4368 }
4369
John Kessenich140f3df2015-06-26 16:58:36 -06004370 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004371 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004372 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004373 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004374
John Kessenich140f3df2015-06-26 16:58:36 -06004375 return id;
4376}
4377
John Kessenich55e7d112015-11-15 21:33:39 -07004378// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004379void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4380{
John Kessenich4016e382016-07-15 11:53:56 -06004381 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004382 builder.addDecoration(id, dec);
4383}
4384
John Kessenich55e7d112015-11-15 21:33:39 -07004385// If 'dec' is valid, add a one-operand decoration to an object
4386void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4387{
John Kessenich4016e382016-07-15 11:53:56 -06004388 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004389 builder.addDecoration(id, dec, value);
4390}
4391
4392// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004393void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4394{
John Kessenich4016e382016-07-15 11:53:56 -06004395 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004396 builder.addMemberDecoration(id, (unsigned)member, dec);
4397}
4398
John Kessenich92187592016-02-01 13:45:25 -07004399// If 'dec' is valid, add a one-operand decoration to a struct member
4400void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4401{
John Kessenich4016e382016-07-15 11:53:56 -06004402 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004403 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4404}
4405
John Kessenich55e7d112015-11-15 21:33:39 -07004406// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004407// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004408//
4409// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4410//
4411// Recursively walk the nodes. The nodes form a tree whose leaves are
4412// regular constants, which themselves are trees that createSpvConstant()
4413// recursively walks. So, this function walks the "top" of the tree:
4414// - emit specialization constant-building instructions for specConstant
4415// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004416spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004417{
John Kessenich7cc0e282016-03-20 00:46:02 -06004418 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004419
qining4f4bb812016-04-03 23:55:17 -04004420 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004421 if (! node.getQualifier().specConstant) {
4422 // hand off to the non-spec-constant path
4423 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4424 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004425 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004426 nextConst, false);
4427 }
4428
4429 // We now know we have a specialization constant to build
4430
John Kessenichd94c0032016-05-30 19:29:40 -06004431 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004432 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4433 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4434 std::vector<spv::Id> dimConstId;
4435 for (int dim = 0; dim < 3; ++dim) {
4436 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4437 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4438 if (specConst)
4439 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4440 }
4441 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4442 }
4443
4444 // An AST node labelled as specialization constant should be a symbol node.
4445 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4446 if (auto* sn = node.getAsSymbolNode()) {
4447 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004448 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4449 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4450 // will set the builder into spec constant op instruction generating mode.
4451 sub_tree->traverse(this);
4452 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004453 } else if (auto* const_union_array = &sn->getConstArray()){
4454 int nextConst = 0;
4455 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004456 }
4457 }
qining4f4bb812016-04-03 23:55:17 -04004458
4459 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4460 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004461 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004462 exit(1);
4463 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004464}
4465
John Kessenich140f3df2015-06-26 16:58:36 -06004466// Use 'consts' as the flattened glslang source of scalar constants to recursively
4467// build the aggregate SPIR-V constant.
4468//
4469// If there are not enough elements present in 'consts', 0 will be substituted;
4470// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4471//
qining08408382016-03-21 09:51:37 -04004472spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004473{
4474 // vector of constants for SPIR-V
4475 std::vector<spv::Id> spvConsts;
4476
4477 // Type is used for struct and array constants
4478 spv::Id typeId = convertGlslangToSpvType(glslangType);
4479
4480 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004481 glslang::TType elementType(glslangType, 0);
4482 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004483 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004484 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004485 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004486 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004487 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004488 } else if (glslangType.getStruct()) {
4489 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4490 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004491 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004492 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004493 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4494 bool zero = nextConst >= consts.size();
4495 switch (glslangType.getBasicType()) {
4496 case glslang::EbtInt:
4497 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4498 break;
4499 case glslang::EbtUint:
4500 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4501 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004502 case glslang::EbtInt64:
4503 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4504 break;
4505 case glslang::EbtUint64:
4506 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4507 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004508 case glslang::EbtFloat:
4509 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4510 break;
4511 case glslang::EbtDouble:
4512 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4513 break;
4514 case glslang::EbtBool:
4515 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4516 break;
4517 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004518 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004519 break;
4520 }
4521 ++nextConst;
4522 }
4523 } else {
4524 // we have a non-aggregate (scalar) constant
4525 bool zero = nextConst >= consts.size();
4526 spv::Id scalar = 0;
4527 switch (glslangType.getBasicType()) {
4528 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004529 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004530 break;
4531 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004532 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004533 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004534 case glslang::EbtInt64:
4535 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4536 break;
4537 case glslang::EbtUint64:
4538 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4539 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004540 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004541 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004542 break;
4543 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004544 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004545 break;
4546 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004547 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004548 break;
4549 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004550 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004551 break;
4552 }
4553 ++nextConst;
4554 return scalar;
4555 }
4556
4557 return builder.makeCompositeConstant(typeId, spvConsts);
4558}
4559
John Kessenich7c1aa102015-10-15 13:29:11 -06004560// Return true if the node is a constant or symbol whose reading has no
4561// non-trivial observable cost or effect.
4562bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4563{
4564 // don't know what this is
4565 if (node == nullptr)
4566 return false;
4567
4568 // a constant is safe
4569 if (node->getAsConstantUnion() != nullptr)
4570 return true;
4571
4572 // not a symbol means non-trivial
4573 if (node->getAsSymbolNode() == nullptr)
4574 return false;
4575
4576 // a symbol, depends on what's being read
4577 switch (node->getType().getQualifier().storage) {
4578 case glslang::EvqTemporary:
4579 case glslang::EvqGlobal:
4580 case glslang::EvqIn:
4581 case glslang::EvqInOut:
4582 case glslang::EvqConst:
4583 case glslang::EvqConstReadOnly:
4584 case glslang::EvqUniform:
4585 return true;
4586 default:
4587 return false;
4588 }
qining25262b32016-05-06 17:25:16 -04004589}
John Kessenich7c1aa102015-10-15 13:29:11 -06004590
4591// A node is trivial if it is a single operation with no side effects.
4592// Error on the side of saying non-trivial.
4593// Return true if trivial.
4594bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4595{
4596 if (node == nullptr)
4597 return false;
4598
4599 // symbols and constants are trivial
4600 if (isTrivialLeaf(node))
4601 return true;
4602
4603 // otherwise, it needs to be a simple operation or one or two leaf nodes
4604
4605 // not a simple operation
4606 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4607 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4608 if (binaryNode == nullptr && unaryNode == nullptr)
4609 return false;
4610
4611 // not on leaf nodes
4612 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4613 return false;
4614
4615 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4616 return false;
4617 }
4618
4619 switch (node->getAsOperator()->getOp()) {
4620 case glslang::EOpLogicalNot:
4621 case glslang::EOpConvIntToBool:
4622 case glslang::EOpConvUintToBool:
4623 case glslang::EOpConvFloatToBool:
4624 case glslang::EOpConvDoubleToBool:
4625 case glslang::EOpEqual:
4626 case glslang::EOpNotEqual:
4627 case glslang::EOpLessThan:
4628 case glslang::EOpGreaterThan:
4629 case glslang::EOpLessThanEqual:
4630 case glslang::EOpGreaterThanEqual:
4631 case glslang::EOpIndexDirect:
4632 case glslang::EOpIndexDirectStruct:
4633 case glslang::EOpLogicalXor:
4634 case glslang::EOpAny:
4635 case glslang::EOpAll:
4636 return true;
4637 default:
4638 return false;
4639 }
4640}
4641
4642// Emit short-circuiting code, where 'right' is never evaluated unless
4643// the left side is true (for &&) or false (for ||).
4644spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4645{
4646 spv::Id boolTypeId = builder.makeBoolType();
4647
4648 // emit left operand
4649 builder.clearAccessChain();
4650 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004651 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004652
4653 // Operands to accumulate OpPhi operands
4654 std::vector<spv::Id> phiOperands;
4655 // accumulate left operand's phi information
4656 phiOperands.push_back(leftId);
4657 phiOperands.push_back(builder.getBuildPoint()->getId());
4658
4659 // Make the two kinds of operation symmetric with a "!"
4660 // || => emit "if (! left) result = right"
4661 // && => emit "if ( left) result = right"
4662 //
4663 // TODO: this runtime "not" for || could be avoided by adding functionality
4664 // to 'builder' to have an "else" without an "then"
4665 if (op == glslang::EOpLogicalOr)
4666 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4667
4668 // make an "if" based on the left value
4669 spv::Builder::If ifBuilder(leftId, builder);
4670
4671 // emit right operand as the "then" part of the "if"
4672 builder.clearAccessChain();
4673 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004674 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004675
4676 // accumulate left operand's phi information
4677 phiOperands.push_back(rightId);
4678 phiOperands.push_back(builder.getBuildPoint()->getId());
4679
4680 // finish the "if"
4681 ifBuilder.makeEndIf();
4682
4683 // phi together the two results
4684 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4685}
4686
Rex Xu9d93a232016-05-05 12:30:44 +08004687// Return type Id of the imported set of extended instructions corresponds to the name.
4688// Import this set if it has not been imported yet.
4689spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4690{
4691 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4692 return extBuiltinMap[name];
4693 else {
4694 builder.addExtensions(name);
4695 spv::Id extBuiltins = builder.import(name);
4696 extBuiltinMap[name] = extBuiltins;
4697 return extBuiltins;
4698 }
4699}
4700
John Kessenich140f3df2015-06-26 16:58:36 -06004701}; // end anonymous namespace
4702
4703namespace glslang {
4704
John Kessenich68d78fd2015-07-12 19:28:10 -06004705void GetSpirvVersion(std::string& version)
4706{
John Kessenich9e55f632015-07-15 10:03:39 -06004707 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004708 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004709 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004710 version = buf;
4711}
4712
John Kessenich140f3df2015-06-26 16:58:36 -06004713// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004714void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004715{
4716 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004717 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004718 for (int i = 0; i < (int)spirv.size(); ++i) {
4719 unsigned int word = spirv[i];
4720 out.write((const char*)&word, 4);
4721 }
4722 out.close();
4723}
4724
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004725// Write SPIR-V out to a text file with 32-bit hexadecimal words
4726void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4727{
4728 std::ofstream out;
4729 out.open(baseName, std::ios::binary | std::ios::out);
4730 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4731 const int WORDS_PER_LINE = 8;
4732 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4733 out << "\t";
4734 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4735 const unsigned int word = spirv[i + j];
4736 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4737 if (i + j + 1 < (int)spirv.size()) {
4738 out << ",";
4739 }
4740 }
4741 out << std::endl;
4742 }
4743 out.close();
4744}
4745
John Kessenich140f3df2015-06-26 16:58:36 -06004746//
4747// Set up the glslang traversal
4748//
4749void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4750{
Lei Zhang17535f72016-05-04 15:55:59 -04004751 spv::SpvBuildLogger logger;
4752 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004753}
4754
Lei Zhang17535f72016-05-04 15:55:59 -04004755void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004756{
John Kessenich140f3df2015-06-26 16:58:36 -06004757 TIntermNode* root = intermediate.getTreeRoot();
4758
4759 if (root == 0)
4760 return;
4761
4762 glslang::GetThreadPoolAllocator().push();
4763
Lei Zhang17535f72016-05-04 15:55:59 -04004764 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004765
4766 root->traverse(&it);
4767
4768 it.dumpSpv(spirv);
4769
4770 glslang::GetThreadPoolAllocator().pop();
4771}
4772
4773}; // end namespace glslang