blob: 84c9e734f6a91267b40fd83b07dd9559ad59af79 [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 Kessenich4bf71552016-09-02 11:20:21 -0600133 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700134 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700135 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
136 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
137 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 +0100138 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600139
140 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
141 void makeFunctions(const glslang::TIntermSequence&);
142 void makeGlobalInitializers(const glslang::TIntermSequence&);
143 void visitFunctions(const glslang::TIntermSequence&);
144 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800145 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600146 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
147 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
149
qining25262b32016-05-06 17:25:16 -0400150 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);
151 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
152 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800153 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800154 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 -0600155 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800156 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800157 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy);
158#ifdef AMD_EXTENSIONS
159 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand);
160#endif
John Kessenich5e4b1242015-08-06 22:53:06 -0600161 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 +0800162 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600163 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
164 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700165 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700167 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400168 spv::Id createSpvConstant(const glslang::TIntermTyped&);
169 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600170 bool isTrivialLeaf(const glslang::TIntermTyped* node);
171 bool isTrivial(const glslang::TIntermTyped* node);
172 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800173 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600174
175 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700176 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600177 int sequenceDepth;
178
Lei Zhang17535f72016-05-04 15:55:59 -0400179 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400180
John Kessenich140f3df2015-06-26 16:58:36 -0600181 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
182 spv::Builder builder;
183 bool inMain;
184 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700185 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 -0700186 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600187 const glslang::TIntermediate* glslangIntermediate;
188 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800189 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600190
John Kessenich2f273362015-07-18 22:34:27 -0600191 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600192 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600193 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700194 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600195 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 -0600196 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600197};
198
199//
200// Helper functions for translating glslang representations to SPIR-V enumerants.
201//
202
203// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700204spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600205{
John Kessenich66e2faf2016-03-12 18:34:36 -0700206 switch (source) {
207 case glslang::EShSourceGlsl:
208 switch (profile) {
209 case ENoProfile:
210 case ECoreProfile:
211 case ECompatibilityProfile:
212 return spv::SourceLanguageGLSL;
213 case EEsProfile:
214 return spv::SourceLanguageESSL;
215 default:
216 return spv::SourceLanguageUnknown;
217 }
218 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400219 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
220 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
222 return spv::SourceLanguageUnknown;
223 }
224}
225
226// Translate glslang language (stage) to SPIR-V execution model.
227spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
228{
229 switch (stage) {
230 case EShLangVertex: return spv::ExecutionModelVertex;
231 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
232 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
233 case EShLangGeometry: return spv::ExecutionModelGeometry;
234 case EShLangFragment: return spv::ExecutionModelFragment;
235 case EShLangCompute: return spv::ExecutionModelGLCompute;
236 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700237 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600238 return spv::ExecutionModelFragment;
239 }
240}
241
242// Translate glslang type to SPIR-V storage class.
243spv::StorageClass TranslateStorageClass(const glslang::TType& type)
244{
245 if (type.getQualifier().isPipeInput())
246 return spv::StorageClassInput;
247 else if (type.getQualifier().isPipeOutput())
248 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700249 else if (type.getBasicType() == glslang::EbtSampler)
250 return spv::StorageClassUniformConstant;
251 else if (type.getBasicType() == glslang::EbtAtomicUint)
252 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600253 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700254 if (type.getQualifier().layoutPushConstant)
255 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600256 if (type.getBasicType() == glslang::EbtBlock)
257 return spv::StorageClassUniform;
258 else
259 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600260 // 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 -0600261 } else {
262 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
264 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
266 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400267 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700268 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600269 return spv::StorageClassFunction;
270 }
271 }
272}
273
274// Translate glslang sampler type to SPIR-V dimensionality.
275spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
276{
277 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700278 case glslang::Esd1D: return spv::Dim1D;
279 case glslang::Esd2D: return spv::Dim2D;
280 case glslang::Esd3D: return spv::Dim3D;
281 case glslang::EsdCube: return spv::DimCube;
282 case glslang::EsdRect: return spv::DimRect;
283 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700284 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600285 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700286 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600287 return spv::Dim2D;
288 }
289}
290
John Kessenichf6640762016-08-01 19:44:00 -0600291// Translate glslang precision to SPIR-V precision decorations.
292spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600293{
John Kessenichf6640762016-08-01 19:44:00 -0600294 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700295 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600296 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
298 return spv::NoPrecision;
299 }
300}
301
John Kessenichf6640762016-08-01 19:44:00 -0600302// Translate glslang type to SPIR-V precision decorations.
303spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
304{
305 return TranslatePrecisionDecoration(type.getQualifier().precision);
306}
307
John Kessenich140f3df2015-06-26 16:58:36 -0600308// Translate glslang type to SPIR-V block decorations.
309spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
310{
311 if (type.getBasicType() == glslang::EbtBlock) {
312 switch (type.getQualifier().storage) {
313 case glslang::EvqUniform: return spv::DecorationBlock;
314 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
315 case glslang::EvqVaryingIn: return spv::DecorationBlock;
316 case glslang::EvqVaryingOut: return spv::DecorationBlock;
317 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700318 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600319 break;
320 }
321 }
322
John Kessenich4016e382016-07-15 11:53:56 -0600323 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600324}
325
Rex Xu1da878f2016-02-21 20:59:01 +0800326// Translate glslang type to SPIR-V memory decorations.
327void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
328{
329 if (qualifier.coherent)
330 memory.push_back(spv::DecorationCoherent);
331 if (qualifier.volatil)
332 memory.push_back(spv::DecorationVolatile);
333 if (qualifier.restrict)
334 memory.push_back(spv::DecorationRestrict);
335 if (qualifier.readonly)
336 memory.push_back(spv::DecorationNonWritable);
337 if (qualifier.writeonly)
338 memory.push_back(spv::DecorationNonReadable);
339}
340
John Kessenich140f3df2015-06-26 16:58:36 -0600341// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700342spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600343{
344 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700345 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600346 case glslang::ElmRowMajor:
347 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700348 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600349 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 default:
351 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 } else {
355 switch (type.getBasicType()) {
356 default:
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 break;
359 case glslang::EbtBlock:
360 switch (type.getQualifier().storage) {
361 case glslang::EvqUniform:
362 case glslang::EvqBuffer:
363 switch (type.getQualifier().layoutPacking) {
364 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
366 default:
John Kessenich4016e382016-07-15 11:53:56 -0600367 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600368 }
369 case glslang::EvqVaryingIn:
370 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700371 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700374 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 }
377 }
378 }
379}
380
381// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600382// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700383// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800384spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600385{
Rex Xubbceed72016-05-21 09:40:44 +0800386 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700387 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800389 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700390 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700391 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600392 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800393#ifdef AMD_EXTENSIONS
394 else if (qualifier.explicitInterp)
395 return spv::DecorationExplicitInterpAMD;
396#endif
Rex Xubbceed72016-05-21 09:40:44 +0800397 else
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800399}
400
401// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600402// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800403// should be applied.
404spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
405{
406 if (qualifier.patch)
407 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700408 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600409 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700410 else if (qualifier.sample) {
411 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700413 } else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600415}
416
John Kessenich92187592016-02-01 13:45:25 -0700417// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700418spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600419{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700420 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600421 return spv::DecorationInvariant;
422 else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600424}
425
qining9220dbb2016-05-04 17:34:38 -0400426// If glslang type is noContraction, return SPIR-V NoContraction decoration.
427spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
428{
429 if (qualifier.noContraction)
430 return spv::DecorationNoContraction;
431 else
John Kessenich4016e382016-07-15 11:53:56 -0600432 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400433}
434
David Netoa901ffe2016-06-08 14:11:40 +0100435// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
436// associated capabilities when required. For some built-in variables, a capability
437// is generated only when using the variable in an executable instruction, but not when
438// just declaring a struct member variable with it. This is true for PointSize,
439// ClipDistance, and CullDistance.
440spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600441{
442 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700443 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600444 // Defer adding the capability until the built-in is actually used.
445 if (! memberDeclaration) {
446 switch (glslangIntermediate->getStage()) {
447 case EShLangGeometry:
448 builder.addCapability(spv::CapabilityGeometryPointSize);
449 break;
450 case EShLangTessControl:
451 case EShLangTessEvaluation:
452 builder.addCapability(spv::CapabilityTessellationPointSize);
453 break;
454 default:
455 break;
456 }
John Kessenich92187592016-02-01 13:45:25 -0700457 }
458 return spv::BuiltInPointSize;
459
John Kessenichebb50532016-05-16 19:22:05 -0600460 // These *Distance capabilities logically belong here, but if the member is declared and
461 // then never used, consumers of SPIR-V prefer the capability not be declared.
462 // They are now generated when used, rather than here when declared.
463 // Potentially, the specification should be more clear what the minimum
464 // use needed is to trigger the capability.
465 //
John Kessenich92187592016-02-01 13:45:25 -0700466 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100467 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600468 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700469 return spv::BuiltInClipDistance;
470
471 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100472 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600473 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700474 return spv::BuiltInCullDistance;
475
476 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500477 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700478 return spv::BuiltInViewportIndex;
479
John Kessenich5e801132016-02-15 11:09:46 -0700480 case glslang::EbvSampleId:
481 builder.addCapability(spv::CapabilitySampleRateShading);
482 return spv::BuiltInSampleId;
483
484 case glslang::EbvSamplePosition:
485 builder.addCapability(spv::CapabilitySampleRateShading);
486 return spv::BuiltInSamplePosition;
487
488 case glslang::EbvSampleMask:
489 builder.addCapability(spv::CapabilitySampleRateShading);
490 return spv::BuiltInSampleMask;
491
John Kessenich78a45572016-07-08 14:05:15 -0600492 case glslang::EbvLayer:
493 builder.addCapability(spv::CapabilityGeometry);
494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600501 case glslang::EbvBaseVertex:
502 case glslang::EbvBaseInstance:
503 case glslang::EbvDrawId:
504 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600505 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600506 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600507 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
508 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600509 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
510 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
511 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
512 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
513 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
514 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
515 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600516 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
517 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
518 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
519 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
520 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
521 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
522 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
523 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu574ab042016-04-14 16:53:07 +0800524 case glslang::EbvSubGroupSize:
525 case glslang::EbvSubGroupInvocation:
526 case glslang::EbvSubGroupEqMask:
527 case glslang::EbvSubGroupGeMask:
528 case glslang::EbvSubGroupGtMask:
529 case glslang::EbvSubGroupLeMask:
530 case glslang::EbvSubGroupLtMask:
531 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600532 logger->missingFunctionality("shader ballot");
John Kessenich4016e382016-07-15 11:53:56 -0600533 return spv::BuiltInMax;
Rex Xu9d93a232016-05-05 12:30:44 +0800534#ifdef AMD_EXTENSIONS
535 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
536 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
537 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
538 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
539 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
540 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
541 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
542#endif
John Kessenich4016e382016-07-15 11:53:56 -0600543 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600544 }
545}
546
Rex Xufc618912015-09-09 16:42:49 +0800547// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700548spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800549{
550 assert(type.getBasicType() == glslang::EbtSampler);
551
John Kessenich5d0fa972016-02-15 11:57:00 -0700552 // Check for capabilities
553 switch (type.getQualifier().layoutFormat) {
554 case glslang::ElfRg32f:
555 case glslang::ElfRg16f:
556 case glslang::ElfR11fG11fB10f:
557 case glslang::ElfR16f:
558 case glslang::ElfRgba16:
559 case glslang::ElfRgb10A2:
560 case glslang::ElfRg16:
561 case glslang::ElfRg8:
562 case glslang::ElfR16:
563 case glslang::ElfR8:
564 case glslang::ElfRgba16Snorm:
565 case glslang::ElfRg16Snorm:
566 case glslang::ElfRg8Snorm:
567 case glslang::ElfR16Snorm:
568 case glslang::ElfR8Snorm:
569
570 case glslang::ElfRg32i:
571 case glslang::ElfRg16i:
572 case glslang::ElfRg8i:
573 case glslang::ElfR16i:
574 case glslang::ElfR8i:
575
576 case glslang::ElfRgb10a2ui:
577 case glslang::ElfRg32ui:
578 case glslang::ElfRg16ui:
579 case glslang::ElfRg8ui:
580 case glslang::ElfR16ui:
581 case glslang::ElfR8ui:
582 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
583 break;
584
585 default:
586 break;
587 }
588
589 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800590 switch (type.getQualifier().layoutFormat) {
591 case glslang::ElfNone: return spv::ImageFormatUnknown;
592 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
593 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
594 case glslang::ElfR32f: return spv::ImageFormatR32f;
595 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
596 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
597 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
598 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
599 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
600 case glslang::ElfR16f: return spv::ImageFormatR16f;
601 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
602 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
603 case glslang::ElfRg16: return spv::ImageFormatRg16;
604 case glslang::ElfRg8: return spv::ImageFormatRg8;
605 case glslang::ElfR16: return spv::ImageFormatR16;
606 case glslang::ElfR8: return spv::ImageFormatR8;
607 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
608 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
609 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
610 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
611 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
612 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
613 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
614 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
615 case glslang::ElfR32i: return spv::ImageFormatR32i;
616 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
617 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
618 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
619 case glslang::ElfR16i: return spv::ImageFormatR16i;
620 case glslang::ElfR8i: return spv::ImageFormatR8i;
621 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
622 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
623 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
624 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
625 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
626 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
627 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
628 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
629 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
630 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600631 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800632 }
633}
634
qining25262b32016-05-06 17:25:16 -0400635// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700636// descriptor set.
637bool IsDescriptorResource(const glslang::TType& type)
638{
John Kessenichf7497e22016-03-08 21:36:22 -0700639 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700640 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700641 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700642
643 // non block...
644 // basically samplerXXX/subpass/sampler/texture are all included
645 // if they are the global-scope-class, not the function parameter
646 // (or local, if they ever exist) class.
647 if (type.getBasicType() == glslang::EbtSampler)
648 return type.getQualifier().isUniformOrBuffer();
649
650 // None of the above.
651 return false;
652}
653
John Kesseniche0b6cad2015-12-24 10:30:13 -0700654void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
655{
656 if (child.layoutMatrix == glslang::ElmNone)
657 child.layoutMatrix = parent.layoutMatrix;
658
659 if (parent.invariant)
660 child.invariant = true;
661 if (parent.nopersp)
662 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800663#ifdef AMD_EXTENSIONS
664 if (parent.explicitInterp)
665 child.explicitInterp = true;
666#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700667 if (parent.flat)
668 child.flat = true;
669 if (parent.centroid)
670 child.centroid = true;
671 if (parent.patch)
672 child.patch = true;
673 if (parent.sample)
674 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800675 if (parent.coherent)
676 child.coherent = true;
677 if (parent.volatil)
678 child.volatil = true;
679 if (parent.restrict)
680 child.restrict = true;
681 if (parent.readonly)
682 child.readonly = true;
683 if (parent.writeonly)
684 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700685}
686
John Kessenichf2b7f332016-09-01 17:05:23 -0600687bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700688{
John Kessenich7b9fa252016-01-21 18:56:57 -0700689 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600690 // - struct members might inherit from a struct declaration
691 // (note that non-block structs don't explicitly inherit,
692 // only implicitly, meaning no decoration involved)
693 // - affect decorations on the struct members
694 // (note smooth does not, and expecting something like volatile
695 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700696 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600697 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700698}
699
John Kessenich140f3df2015-06-26 16:58:36 -0600700//
701// Implement the TGlslangToSpvTraverser class.
702//
703
Lei Zhang17535f72016-05-04 15:55:59 -0400704TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
705 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
706 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600707 inMain(false), mainTerminated(false), linkageOnly(false),
708 glslangIntermediate(glslangIntermediate)
709{
710 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
711
712 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700713 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600714 stdBuiltins = builder.import("GLSL.std.450");
715 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700716 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
717 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600718
719 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600720 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
721 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600722 builder.addSourceExtension(it->c_str());
723
724 // Add the top-level modes for this shader.
725
John Kessenich92187592016-02-01 13:45:25 -0700726 if (glslangIntermediate->getXfbMode()) {
727 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600728 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700729 }
John Kessenich140f3df2015-06-26 16:58:36 -0600730
731 unsigned int mode;
732 switch (glslangIntermediate->getStage()) {
733 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600734 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600735 break;
736
737 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600738 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600739 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
740 break;
741
742 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600743 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600744 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700745 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
746 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
747 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600748 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600749 }
John Kessenich4016e382016-07-15 11:53:56 -0600750 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600751 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
752
John Kesseniche6903322015-10-13 16:29:02 -0600753 switch (glslangIntermediate->getVertexSpacing()) {
754 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
755 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
756 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600757 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600758 }
John Kessenich4016e382016-07-15 11:53:56 -0600759 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600760 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
761
762 switch (glslangIntermediate->getVertexOrder()) {
763 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
764 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600765 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600766 }
John Kessenich4016e382016-07-15 11:53:56 -0600767 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600768 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
769
770 if (glslangIntermediate->getPointMode())
771 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600772 break;
773
774 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600775 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600776 switch (glslangIntermediate->getInputPrimitive()) {
777 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
778 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
779 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700780 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600781 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600782 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600783 }
John Kessenich4016e382016-07-15 11:53:56 -0600784 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600785 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600786
John Kessenich140f3df2015-06-26 16:58:36 -0600787 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
788
789 switch (glslangIntermediate->getOutputPrimitive()) {
790 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
791 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
792 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600793 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600794 }
John Kessenich4016e382016-07-15 11:53:56 -0600795 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600796 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
797 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
798 break;
799
800 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600801 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600802 if (glslangIntermediate->getPixelCenterInteger())
803 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600804
John Kessenich140f3df2015-06-26 16:58:36 -0600805 if (glslangIntermediate->getOriginUpperLeft())
806 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600807 else
808 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600809
810 if (glslangIntermediate->getEarlyFragmentTests())
811 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
812
813 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600814 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
815 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600816 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600817 }
John Kessenich4016e382016-07-15 11:53:56 -0600818 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600819 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
820
821 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
822 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600823 break;
824
825 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600826 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600827 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
828 glslangIntermediate->getLocalSize(1),
829 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600830 break;
831
832 default:
833 break;
834 }
835
836}
837
John Kessenich7ba63412015-12-20 17:37:07 -0700838// Finish everything and dump
839void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
840{
841 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100842 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
843 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700844
qiningda397332016-03-09 19:54:03 -0500845 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700846 builder.dump(out);
847}
848
John Kessenich140f3df2015-06-26 16:58:36 -0600849TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
850{
851 if (! mainTerminated) {
852 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
853 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600854 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600855 }
856}
857
858//
859// Implement the traversal functions.
860//
861// Return true from interior nodes to have the external traversal
862// continue on to children. Return false if children were
863// already processed.
864//
865
866//
qining25262b32016-05-06 17:25:16 -0400867// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600868// - uniform/input reads
869// - output writes
870// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
871// - something simple that degenerates into the last bullet
872//
873void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
874{
qining75d1d802016-04-06 14:42:01 -0400875 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
876 if (symbol->getType().getQualifier().isSpecConstant())
877 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
878
John Kessenich140f3df2015-06-26 16:58:36 -0600879 // getSymbolId() will set up all the IO decorations on the first call.
880 // Formal function parameters were mapped during makeFunctions().
881 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700882
883 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
884 if (builder.isPointer(id)) {
885 spv::StorageClass sc = builder.getStorageClass(id);
886 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
887 iOSet.insert(id);
888 }
889
890 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700891 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600892 // Prepare to generate code for the access
893
894 // L-value chains will be computed left to right. We're on the symbol now,
895 // which is the left-most part of the access chain, so now is "clear" time,
896 // followed by setting the base.
897 builder.clearAccessChain();
898
899 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700900 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600901 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700902 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600903 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700904 // These are also pure R-values.
905 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600906 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600907 builder.setAccessChainRValue(id);
908 else
909 builder.setAccessChainLValue(id);
910 }
911}
912
913bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
914{
qining40887662016-04-03 22:20:42 -0400915 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
916 if (node->getType().getQualifier().isSpecConstant())
917 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
918
John Kessenich140f3df2015-06-26 16:58:36 -0600919 // First, handle special cases
920 switch (node->getOp()) {
921 case glslang::EOpAssign:
922 case glslang::EOpAddAssign:
923 case glslang::EOpSubAssign:
924 case glslang::EOpMulAssign:
925 case glslang::EOpVectorTimesMatrixAssign:
926 case glslang::EOpVectorTimesScalarAssign:
927 case glslang::EOpMatrixTimesScalarAssign:
928 case glslang::EOpMatrixTimesMatrixAssign:
929 case glslang::EOpDivAssign:
930 case glslang::EOpModAssign:
931 case glslang::EOpAndAssign:
932 case glslang::EOpInclusiveOrAssign:
933 case glslang::EOpExclusiveOrAssign:
934 case glslang::EOpLeftShiftAssign:
935 case glslang::EOpRightShiftAssign:
936 // A bin-op assign "a += b" means the same thing as "a = a + b"
937 // where a is evaluated before b. For a simple assignment, GLSL
938 // says to evaluate the left before the right. So, always, left
939 // node then right node.
940 {
941 // get the left l-value, save it away
942 builder.clearAccessChain();
943 node->getLeft()->traverse(this);
944 spv::Builder::AccessChain lValue = builder.getAccessChain();
945
946 // evaluate the right
947 builder.clearAccessChain();
948 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700949 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600950
951 if (node->getOp() != glslang::EOpAssign) {
952 // the left is also an r-value
953 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700954 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600957 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400958 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600959 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
960 node->getType().getBasicType());
961
962 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700963 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
965
966 // store the result
967 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -0600968 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600969
970 // assignments are expressions having an rValue after they are evaluated...
971 builder.clearAccessChain();
972 builder.setAccessChainRValue(rValue);
973 }
974 return false;
975 case glslang::EOpIndexDirect:
976 case glslang::EOpIndexDirectStruct:
977 {
978 // Get the left part of the access chain.
979 node->getLeft()->traverse(this);
980
981 // Add the next element in the chain
982
David Netoa901ffe2016-06-08 14:11:40 +0100983 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600984 if (! node->getLeft()->getType().isArray() &&
985 node->getLeft()->getType().isVector() &&
986 node->getOp() == glslang::EOpIndexDirect) {
987 // This is essentially a hard-coded vector swizzle of size 1,
988 // so short circuit the access-chain stuff with a swizzle.
989 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +0100990 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -0600991 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600992 } else {
David Netoa901ffe2016-06-08 14:11:40 +0100993 int spvIndex = glslangIndex;
994 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
995 node->getOp() == glslang::EOpIndexDirectStruct)
996 {
997 // This may be, e.g., an anonymous block-member selection, which generally need
998 // index remapping due to hidden members in anonymous blocks.
999 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1000 assert(remapper.size() > 0);
1001 spvIndex = remapper[glslangIndex];
1002 }
John Kessenichebb50532016-05-16 19:22:05 -06001003
David Netoa901ffe2016-06-08 14:11:40 +01001004 // normal case for indexing array or structure or block
1005 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1006
1007 // Add capabilities here for accessing PointSize and clip/cull distance.
1008 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001009 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001010 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001011 }
1012 }
1013 return false;
1014 case glslang::EOpIndexIndirect:
1015 {
1016 // Structure or array or vector indirection.
1017 // Will use native SPIR-V access-chain for struct and array indirection;
1018 // matrices are arrays of vectors, so will also work for a matrix.
1019 // Will use the access chain's 'component' for variable index into a vector.
1020
1021 // This adapter is building access chains left to right.
1022 // Set up the access chain to the left.
1023 node->getLeft()->traverse(this);
1024
1025 // save it so that computing the right side doesn't trash it
1026 spv::Builder::AccessChain partial = builder.getAccessChain();
1027
1028 // compute the next index in the chain
1029 builder.clearAccessChain();
1030 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001031 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001032
1033 // restore the saved access chain
1034 builder.setAccessChain(partial);
1035
1036 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001037 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001038 else
John Kessenichfa668da2015-09-13 14:46:30 -06001039 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001040 }
1041 return false;
1042 case glslang::EOpVectorSwizzle:
1043 {
1044 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001045 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001046 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001047 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001048 }
1049 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001050 case glslang::EOpLogicalOr:
1051 case glslang::EOpLogicalAnd:
1052 {
1053
1054 // These may require short circuiting, but can sometimes be done as straight
1055 // binary operations. The right operand must be short circuited if it has
1056 // side effects, and should probably be if it is complex.
1057 if (isTrivial(node->getRight()->getAsTyped()))
1058 break; // handle below as a normal binary operation
1059 // otherwise, we need to do dynamic short circuiting on the right operand
1060 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1061 builder.clearAccessChain();
1062 builder.setAccessChainRValue(result);
1063 }
1064 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001065 default:
1066 break;
1067 }
1068
1069 // Assume generic binary op...
1070
John Kessenich32cfd492016-02-02 12:37:46 -07001071 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001072 builder.clearAccessChain();
1073 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001074 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001075
John Kessenich32cfd492016-02-02 12:37:46 -07001076 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001077 builder.clearAccessChain();
1078 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001079 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001080
John Kessenich32cfd492016-02-02 12:37:46 -07001081 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001082 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001083 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001084 convertGlslangToSpvType(node->getType()), left, right,
1085 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001086
John Kessenich50e57562015-12-21 21:21:11 -07001087 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001088 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001089 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001090 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001091 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001092 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001093 return false;
1094 }
John Kessenich140f3df2015-06-26 16:58:36 -06001095}
1096
1097bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1098{
qining40887662016-04-03 22:20:42 -04001099 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1100 if (node->getType().getQualifier().isSpecConstant())
1101 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1102
John Kessenichfc51d282015-08-19 13:34:18 -06001103 spv::Id result = spv::NoResult;
1104
1105 // try texturing first
1106 result = createImageTextureFunctionCall(node);
1107 if (result != spv::NoResult) {
1108 builder.clearAccessChain();
1109 builder.setAccessChainRValue(result);
1110
1111 return false; // done with this node
1112 }
1113
1114 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001115
1116 if (node->getOp() == glslang::EOpArrayLength) {
1117 // Quite special; won't want to evaluate the operand.
1118
1119 // Normal .length() would have been constant folded by the front-end.
1120 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001121 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001122 assert(node->getOperand()->getType().isRuntimeSizedArray());
1123 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1124 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001125 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1126 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001127
1128 builder.clearAccessChain();
1129 builder.setAccessChainRValue(length);
1130
1131 return false;
1132 }
1133
John Kessenichfc51d282015-08-19 13:34:18 -06001134 // Start by evaluating the operand
1135
John Kessenich8c8505c2016-07-26 12:50:38 -06001136 // Does it need a swizzle inversion? If so, evaluation is inverted;
1137 // operate first on the swizzle base, then apply the swizzle.
1138 spv::Id invertedType = spv::NoType;
1139 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1140 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1141 invertedType = getInvertedSwizzleType(*node->getOperand());
1142
John Kessenich140f3df2015-06-26 16:58:36 -06001143 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001144 if (invertedType != spv::NoType)
1145 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1146 else
1147 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001148
Rex Xufc618912015-09-09 16:42:49 +08001149 spv::Id operand = spv::NoResult;
1150
1151 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1152 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001153 node->getOp() == glslang::EOpAtomicCounter ||
1154 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001155 operand = builder.accessChainGetLValue(); // Special case l-value operands
1156 else
John Kessenich32cfd492016-02-02 12:37:46 -07001157 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001158
John Kessenichf6640762016-08-01 19:44:00 -06001159 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001160 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001161
1162 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001163 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001164 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001165
1166 // if not, then possibly an operation
1167 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001168 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001169
1170 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001171 if (invertedType)
1172 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1173
John Kessenich140f3df2015-06-26 16:58:36 -06001174 builder.clearAccessChain();
1175 builder.setAccessChainRValue(result);
1176
1177 return false; // done with this node
1178 }
1179
1180 // it must be a special case, check...
1181 switch (node->getOp()) {
1182 case glslang::EOpPostIncrement:
1183 case glslang::EOpPostDecrement:
1184 case glslang::EOpPreIncrement:
1185 case glslang::EOpPreDecrement:
1186 {
1187 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001188 spv::Id one = 0;
1189 if (node->getBasicType() == glslang::EbtFloat)
1190 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001191 else if (node->getBasicType() == glslang::EbtDouble)
1192 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001193 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1194 one = builder.makeInt64Constant(1);
1195 else
1196 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 glslang::TOperator op;
1198 if (node->getOp() == glslang::EOpPreIncrement ||
1199 node->getOp() == glslang::EOpPostIncrement)
1200 op = glslang::EOpAdd;
1201 else
1202 op = glslang::EOpSub;
1203
John Kessenichf6640762016-08-01 19:44:00 -06001204 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001205 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001206 convertGlslangToSpvType(node->getType()), operand, one,
1207 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001208 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001209
1210 // The result of operation is always stored, but conditionally the
1211 // consumed result. The consumed result is always an r-value.
1212 builder.accessChainStore(result);
1213 builder.clearAccessChain();
1214 if (node->getOp() == glslang::EOpPreIncrement ||
1215 node->getOp() == glslang::EOpPreDecrement)
1216 builder.setAccessChainRValue(result);
1217 else
1218 builder.setAccessChainRValue(operand);
1219 }
1220
1221 return false;
1222
1223 case glslang::EOpEmitStreamVertex:
1224 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1225 return false;
1226 case glslang::EOpEndStreamPrimitive:
1227 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1228 return false;
1229
1230 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001231 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001232 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001233 }
John Kessenich140f3df2015-06-26 16:58:36 -06001234}
1235
1236bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1237{
qining27e04a02016-04-14 16:40:20 -04001238 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1239 if (node->getType().getQualifier().isSpecConstant())
1240 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1241
John Kessenichfc51d282015-08-19 13:34:18 -06001242 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001243 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1244 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001245
1246 // try texturing
1247 result = createImageTextureFunctionCall(node);
1248 if (result != spv::NoResult) {
1249 builder.clearAccessChain();
1250 builder.setAccessChainRValue(result);
1251
1252 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001253 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001254 // "imageStore" is a special case, which has no result
1255 return false;
1256 }
John Kessenichfc51d282015-08-19 13:34:18 -06001257
John Kessenich140f3df2015-06-26 16:58:36 -06001258 glslang::TOperator binOp = glslang::EOpNull;
1259 bool reduceComparison = true;
1260 bool isMatrix = false;
1261 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001262 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001263
1264 assert(node->getOp());
1265
John Kessenichf6640762016-08-01 19:44:00 -06001266 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001267
1268 switch (node->getOp()) {
1269 case glslang::EOpSequence:
1270 {
1271 if (preVisit)
1272 ++sequenceDepth;
1273 else
1274 --sequenceDepth;
1275
1276 if (sequenceDepth == 1) {
1277 // If this is the parent node of all the functions, we want to see them
1278 // early, so all call points have actual SPIR-V functions to reference.
1279 // In all cases, still let the traverser visit the children for us.
1280 makeFunctions(node->getAsAggregate()->getSequence());
1281
1282 // Also, we want all globals initializers to go into the entry of main(), before
1283 // anything else gets there, so visit out of order, doing them all now.
1284 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1285
1286 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1287 // so do them manually.
1288 visitFunctions(node->getAsAggregate()->getSequence());
1289
1290 return false;
1291 }
1292
1293 return true;
1294 }
1295 case glslang::EOpLinkerObjects:
1296 {
1297 if (visit == glslang::EvPreVisit)
1298 linkageOnly = true;
1299 else
1300 linkageOnly = false;
1301
1302 return true;
1303 }
1304 case glslang::EOpComma:
1305 {
1306 // processing from left to right naturally leaves the right-most
1307 // lying around in the access chain
1308 glslang::TIntermSequence& glslangOperands = node->getSequence();
1309 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1310 glslangOperands[i]->traverse(this);
1311
1312 return false;
1313 }
1314 case glslang::EOpFunction:
1315 if (visit == glslang::EvPreVisit) {
1316 if (isShaderEntrypoint(node)) {
1317 inMain = true;
1318 builder.setBuildPoint(shaderEntry->getLastBlock());
1319 } else {
1320 handleFunctionEntry(node);
1321 }
1322 } else {
1323 if (inMain)
1324 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001325 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001326 inMain = false;
1327 }
1328
1329 return true;
1330 case glslang::EOpParameters:
1331 // Parameters will have been consumed by EOpFunction processing, but not
1332 // the body, so we still visited the function node's children, making this
1333 // child redundant.
1334 return false;
1335 case glslang::EOpFunctionCall:
1336 {
1337 if (node->isUserDefined())
1338 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001339 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1340 if (result) {
1341 builder.clearAccessChain();
1342 builder.setAccessChainRValue(result);
1343 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001344 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001345
1346 return false;
1347 }
1348 case glslang::EOpConstructMat2x2:
1349 case glslang::EOpConstructMat2x3:
1350 case glslang::EOpConstructMat2x4:
1351 case glslang::EOpConstructMat3x2:
1352 case glslang::EOpConstructMat3x3:
1353 case glslang::EOpConstructMat3x4:
1354 case glslang::EOpConstructMat4x2:
1355 case glslang::EOpConstructMat4x3:
1356 case glslang::EOpConstructMat4x4:
1357 case glslang::EOpConstructDMat2x2:
1358 case glslang::EOpConstructDMat2x3:
1359 case glslang::EOpConstructDMat2x4:
1360 case glslang::EOpConstructDMat3x2:
1361 case glslang::EOpConstructDMat3x3:
1362 case glslang::EOpConstructDMat3x4:
1363 case glslang::EOpConstructDMat4x2:
1364 case glslang::EOpConstructDMat4x3:
1365 case glslang::EOpConstructDMat4x4:
1366 isMatrix = true;
1367 // fall through
1368 case glslang::EOpConstructFloat:
1369 case glslang::EOpConstructVec2:
1370 case glslang::EOpConstructVec3:
1371 case glslang::EOpConstructVec4:
1372 case glslang::EOpConstructDouble:
1373 case glslang::EOpConstructDVec2:
1374 case glslang::EOpConstructDVec3:
1375 case glslang::EOpConstructDVec4:
1376 case glslang::EOpConstructBool:
1377 case glslang::EOpConstructBVec2:
1378 case glslang::EOpConstructBVec3:
1379 case glslang::EOpConstructBVec4:
1380 case glslang::EOpConstructInt:
1381 case glslang::EOpConstructIVec2:
1382 case glslang::EOpConstructIVec3:
1383 case glslang::EOpConstructIVec4:
1384 case glslang::EOpConstructUint:
1385 case glslang::EOpConstructUVec2:
1386 case glslang::EOpConstructUVec3:
1387 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001388 case glslang::EOpConstructInt64:
1389 case glslang::EOpConstructI64Vec2:
1390 case glslang::EOpConstructI64Vec3:
1391 case glslang::EOpConstructI64Vec4:
1392 case glslang::EOpConstructUint64:
1393 case glslang::EOpConstructU64Vec2:
1394 case glslang::EOpConstructU64Vec3:
1395 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001396 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001397 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001398 {
1399 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001400 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001401 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001402 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001403 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001404 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001405 std::vector<spv::Id> constituents;
1406 for (int c = 0; c < (int)arguments.size(); ++c)
1407 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001408 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001409 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001410 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001411 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001412 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001413
1414 builder.clearAccessChain();
1415 builder.setAccessChainRValue(constructed);
1416
1417 return false;
1418 }
1419
1420 // These six are component-wise compares with component-wise results.
1421 // Forward on to createBinaryOperation(), requesting a vector result.
1422 case glslang::EOpLessThan:
1423 case glslang::EOpGreaterThan:
1424 case glslang::EOpLessThanEqual:
1425 case glslang::EOpGreaterThanEqual:
1426 case glslang::EOpVectorEqual:
1427 case glslang::EOpVectorNotEqual:
1428 {
1429 // Map the operation to a binary
1430 binOp = node->getOp();
1431 reduceComparison = false;
1432 switch (node->getOp()) {
1433 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1434 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1435 default: binOp = node->getOp(); break;
1436 }
1437
1438 break;
1439 }
1440 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001441 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001442 binOp = glslang::EOpMul;
1443 break;
1444 case glslang::EOpOuterProduct:
1445 // two vectors multiplied to make a matrix
1446 binOp = glslang::EOpOuterProduct;
1447 break;
1448 case glslang::EOpDot:
1449 {
qining25262b32016-05-06 17:25:16 -04001450 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001451 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001452 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001453 binOp = glslang::EOpMul;
1454 break;
1455 }
1456 case glslang::EOpMod:
1457 // when an aggregate, this is the floating-point mod built-in function,
1458 // which can be emitted by the one in createBinaryOperation()
1459 binOp = glslang::EOpMod;
1460 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001461 case glslang::EOpEmitVertex:
1462 case glslang::EOpEndPrimitive:
1463 case glslang::EOpBarrier:
1464 case glslang::EOpMemoryBarrier:
1465 case glslang::EOpMemoryBarrierAtomicCounter:
1466 case glslang::EOpMemoryBarrierBuffer:
1467 case glslang::EOpMemoryBarrierImage:
1468 case glslang::EOpMemoryBarrierShared:
1469 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001470 case glslang::EOpAllMemoryBarrierWithGroupSync:
1471 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1472 case glslang::EOpWorkgroupMemoryBarrier:
1473 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001474 noReturnValue = true;
1475 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1476 break;
1477
John Kessenich426394d2015-07-23 10:22:48 -06001478 case glslang::EOpAtomicAdd:
1479 case glslang::EOpAtomicMin:
1480 case glslang::EOpAtomicMax:
1481 case glslang::EOpAtomicAnd:
1482 case glslang::EOpAtomicOr:
1483 case glslang::EOpAtomicXor:
1484 case glslang::EOpAtomicExchange:
1485 case glslang::EOpAtomicCompSwap:
1486 atomic = true;
1487 break;
1488
John Kessenich140f3df2015-06-26 16:58:36 -06001489 default:
1490 break;
1491 }
1492
1493 //
1494 // See if it maps to a regular operation.
1495 //
John Kessenich140f3df2015-06-26 16:58:36 -06001496 if (binOp != glslang::EOpNull) {
1497 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1498 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1499 assert(left && right);
1500
1501 builder.clearAccessChain();
1502 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001503 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 builder.clearAccessChain();
1506 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001507 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001508
qining25262b32016-05-06 17:25:16 -04001509 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001510 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001511 left->getType().getBasicType(), reduceComparison);
1512
1513 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001514 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001515 builder.clearAccessChain();
1516 builder.setAccessChainRValue(result);
1517
1518 return false;
1519 }
1520
John Kessenich426394d2015-07-23 10:22:48 -06001521 //
1522 // Create the list of operands.
1523 //
John Kessenich140f3df2015-06-26 16:58:36 -06001524 glslang::TIntermSequence& glslangOperands = node->getSequence();
1525 std::vector<spv::Id> operands;
1526 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001527 // special case l-value operands; there are just a few
1528 bool lvalue = false;
1529 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001530 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001531 case glslang::EOpModf:
1532 if (arg == 1)
1533 lvalue = true;
1534 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001535 case glslang::EOpInterpolateAtSample:
1536 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001537#ifdef AMD_EXTENSIONS
1538 case glslang::EOpInterpolateAtVertex:
1539#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001540 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001541 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001542
1543 // Does it need a swizzle inversion? If so, evaluation is inverted;
1544 // operate first on the swizzle base, then apply the swizzle.
1545 if (glslangOperands[0]->getAsOperator() &&
1546 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1547 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1548 }
Rex Xu7a26c172015-12-08 17:12:09 +08001549 break;
Rex Xud4782c12015-09-06 16:30:11 +08001550 case glslang::EOpAtomicAdd:
1551 case glslang::EOpAtomicMin:
1552 case glslang::EOpAtomicMax:
1553 case glslang::EOpAtomicAnd:
1554 case glslang::EOpAtomicOr:
1555 case glslang::EOpAtomicXor:
1556 case glslang::EOpAtomicExchange:
1557 case glslang::EOpAtomicCompSwap:
1558 if (arg == 0)
1559 lvalue = true;
1560 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001561 case glslang::EOpAddCarry:
1562 case glslang::EOpSubBorrow:
1563 if (arg == 2)
1564 lvalue = true;
1565 break;
1566 case glslang::EOpUMulExtended:
1567 case glslang::EOpIMulExtended:
1568 if (arg >= 2)
1569 lvalue = true;
1570 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001571 default:
1572 break;
1573 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001574 builder.clearAccessChain();
1575 if (invertedType != spv::NoType && arg == 0)
1576 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1577 else
1578 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001579 if (lvalue)
1580 operands.push_back(builder.accessChainGetLValue());
1581 else
John Kessenich32cfd492016-02-02 12:37:46 -07001582 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001583 }
John Kessenich426394d2015-07-23 10:22:48 -06001584
1585 if (atomic) {
1586 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001587 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001588 } else {
1589 // Pass through to generic operations.
1590 switch (glslangOperands.size()) {
1591 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001592 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001593 break;
1594 case 1:
qining25262b32016-05-06 17:25:16 -04001595 result = createUnaryOperation(
1596 node->getOp(), precision,
1597 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001598 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001599 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001600 break;
1601 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001602 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001603 break;
1604 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001605 if (invertedType)
1606 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001607 }
1608
1609 if (noReturnValue)
1610 return false;
1611
1612 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001613 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001614 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001615 } else {
1616 builder.clearAccessChain();
1617 builder.setAccessChainRValue(result);
1618 return false;
1619 }
1620}
1621
1622bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1623{
1624 // This path handles both if-then-else and ?:
1625 // The if-then-else has a node type of void, while
1626 // ?: has a non-void node type
1627 spv::Id result = 0;
1628 if (node->getBasicType() != glslang::EbtVoid) {
1629 // don't handle this as just on-the-fly temporaries, because there will be two names
1630 // and better to leave SSA to later passes
1631 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1632 }
1633
1634 // emit the condition before doing anything with selection
1635 node->getCondition()->traverse(this);
1636
1637 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001638 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001639
1640 if (node->getTrueBlock()) {
1641 // emit the "then" statement
1642 node->getTrueBlock()->traverse(this);
1643 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001644 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001645 }
1646
1647 if (node->getFalseBlock()) {
1648 ifBuilder.makeBeginElse();
1649 // emit the "else" statement
1650 node->getFalseBlock()->traverse(this);
1651 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001652 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001653 }
1654
1655 ifBuilder.makeEndIf();
1656
1657 if (result) {
1658 // GLSL only has r-values as the result of a :?, but
1659 // if we have an l-value, that can be more efficient if it will
1660 // become the base of a complex r-value expression, because the
1661 // next layer copies r-values into memory to use the access-chain mechanism
1662 builder.clearAccessChain();
1663 builder.setAccessChainLValue(result);
1664 }
1665
1666 return false;
1667}
1668
1669bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1670{
1671 // emit and get the condition before doing anything with switch
1672 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001673 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001674
1675 // browse the children to sort out code segments
1676 int defaultSegment = -1;
1677 std::vector<TIntermNode*> codeSegments;
1678 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1679 std::vector<int> caseValues;
1680 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1681 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1682 TIntermNode* child = *c;
1683 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001684 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001685 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001686 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001687 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1688 } else
1689 codeSegments.push_back(child);
1690 }
1691
qining25262b32016-05-06 17:25:16 -04001692 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001693 // statements between the last case and the end of the switch statement
1694 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1695 (int)codeSegments.size() == defaultSegment)
1696 codeSegments.push_back(nullptr);
1697
1698 // make the switch statement
1699 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001700 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001701
1702 // emit all the code in the segments
1703 breakForLoop.push(false);
1704 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1705 builder.nextSwitchSegment(segmentBlocks, s);
1706 if (codeSegments[s])
1707 codeSegments[s]->traverse(this);
1708 else
1709 builder.addSwitchBreak();
1710 }
1711 breakForLoop.pop();
1712
1713 builder.endSwitch(segmentBlocks);
1714
1715 return false;
1716}
1717
1718void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1719{
1720 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001721 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001722
1723 builder.clearAccessChain();
1724 builder.setAccessChainRValue(constant);
1725}
1726
1727bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1728{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001729 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001730 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001731 // Spec requires back edges to target header blocks, and every header block
1732 // must dominate its merge block. Make a header block first to ensure these
1733 // conditions are met. By definition, it will contain OpLoopMerge, followed
1734 // by a block-ending branch. But we don't want to put any other body/test
1735 // instructions in it, since the body/test may have arbitrary instructions,
1736 // including merges of its own.
1737 builder.setBuildPoint(&blocks.head);
1738 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001739 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001740 spv::Block& test = builder.makeNewBlock();
1741 builder.createBranch(&test);
1742
1743 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001745 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001746 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001747 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1748
1749 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001750 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001751 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001752 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001753 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001754 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001755
1756 builder.setBuildPoint(&blocks.continue_target);
1757 if (node->getTerminal())
1758 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001759 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001760 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001761 builder.createBranch(&blocks.body);
1762
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001763 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001764 builder.setBuildPoint(&blocks.body);
1765 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001766 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001767 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001768 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001769
1770 builder.setBuildPoint(&blocks.continue_target);
1771 if (node->getTerminal())
1772 node->getTerminal()->traverse(this);
1773 if (node->getTest()) {
1774 node->getTest()->traverse(this);
1775 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001776 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001777 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001778 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001779 // TODO: unless there was a break/return/discard instruction
1780 // somewhere in the body, this is an infinite loop, so we should
1781 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001782 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001783 }
John Kessenich140f3df2015-06-26 16:58:36 -06001784 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001785 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001786 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001787 return false;
1788}
1789
1790bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1791{
1792 if (node->getExpression())
1793 node->getExpression()->traverse(this);
1794
1795 switch (node->getFlowOp()) {
1796 case glslang::EOpKill:
1797 builder.makeDiscard();
1798 break;
1799 case glslang::EOpBreak:
1800 if (breakForLoop.top())
1801 builder.createLoopExit();
1802 else
1803 builder.addSwitchBreak();
1804 break;
1805 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001806 builder.createLoopContinue();
1807 break;
1808 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001809 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001810 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001811 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001812 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001813
1814 builder.clearAccessChain();
1815 break;
1816
1817 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001818 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001819 break;
1820 }
1821
1822 return false;
1823}
1824
1825spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1826{
qining25262b32016-05-06 17:25:16 -04001827 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001828 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001829 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001830 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001831 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001832 }
1833
1834 // Now, handle actual variables
1835 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1836 spv::Id spvType = convertGlslangToSpvType(node->getType());
1837
1838 const char* name = node->getName().c_str();
1839 if (glslang::IsAnonymous(name))
1840 name = "";
1841
1842 return builder.createVariable(storageClass, spvType, name);
1843}
1844
1845// Return type Id of the sampled type.
1846spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1847{
1848 switch (sampler.type) {
1849 case glslang::EbtFloat: return builder.makeFloatType(32);
1850 case glslang::EbtInt: return builder.makeIntType(32);
1851 case glslang::EbtUint: return builder.makeUintType(32);
1852 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001853 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001854 return builder.makeFloatType(32);
1855 }
1856}
1857
John Kessenich8c8505c2016-07-26 12:50:38 -06001858// If node is a swizzle operation, return the type that should be used if
1859// the swizzle base is first consumed by another operation, before the swizzle
1860// is applied.
1861spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1862{
1863 if (node.getAsOperator() &&
1864 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1865 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1866 else
1867 return spv::NoType;
1868}
1869
1870// When inverting a swizzle with a parent op, this function
1871// will apply the swizzle operation to a completed parent operation.
1872spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1873{
1874 std::vector<unsigned> swizzle;
1875 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1876 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1877}
1878
1879
1880// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1881void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1882{
1883 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1884 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1885 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1886}
1887
John Kessenich3ac051e2015-12-20 11:29:16 -07001888// Convert from a glslang type to an SPV type, by calling into a
1889// recursive version of this function. This establishes the inherited
1890// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001891spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1892{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001894}
1895
1896// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001897// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001898// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001899spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001900{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001901 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001902
1903 switch (type.getBasicType()) {
1904 case glslang::EbtVoid:
1905 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001906 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001907 break;
1908 case glslang::EbtFloat:
1909 spvType = builder.makeFloatType(32);
1910 break;
1911 case glslang::EbtDouble:
1912 spvType = builder.makeFloatType(64);
1913 break;
1914 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001915 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1916 // a 32-bit int where non-0 means true.
1917 if (explicitLayout != glslang::ElpNone)
1918 spvType = builder.makeUintType(32);
1919 else
1920 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001921 break;
1922 case glslang::EbtInt:
1923 spvType = builder.makeIntType(32);
1924 break;
1925 case glslang::EbtUint:
1926 spvType = builder.makeUintType(32);
1927 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001928 case glslang::EbtInt64:
1929 builder.addCapability(spv::CapabilityInt64);
1930 spvType = builder.makeIntType(64);
1931 break;
1932 case glslang::EbtUint64:
1933 builder.addCapability(spv::CapabilityInt64);
1934 spvType = builder.makeUintType(64);
1935 break;
John Kessenich426394d2015-07-23 10:22:48 -06001936 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001937 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001938 spvType = builder.makeUintType(32);
1939 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001940 case glslang::EbtSampler:
1941 {
1942 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001943 if (sampler.sampler) {
1944 // pure sampler
1945 spvType = builder.makeSamplerType();
1946 } else {
1947 // an image is present, make its type
1948 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1949 sampler.image ? 2 : 1, TranslateImageFormat(type));
1950 if (sampler.combined) {
1951 // already has both image and sampler, make the combined type
1952 spvType = builder.makeSampledImageType(spvType);
1953 }
John Kessenich55e7d112015-11-15 21:33:39 -07001954 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001955 }
John Kessenich140f3df2015-06-26 16:58:36 -06001956 break;
1957 case glslang::EbtStruct:
1958 case glslang::EbtBlock:
1959 {
1960 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001961 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001962
1963 // Try to share structs for different layouts, but not yet for other
1964 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06001965 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001966 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001967 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001968 break;
1969
1970 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06001971 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06001972 memberRemapper[glslangMembers].resize(glslangMembers->size());
1973 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06001974 }
1975 break;
1976 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001977 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001978 break;
1979 }
1980
1981 if (type.isMatrix())
1982 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1983 else {
1984 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1985 if (type.getVectorSize() > 1)
1986 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1987 }
1988
1989 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001990 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1991
John Kessenichc9a80832015-09-12 12:17:44 -06001992 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001993 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001994 // We need to decorate array strides for types needing explicit layout, except blocks.
1995 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001996 // Use a dummy glslang type for querying internal strides of
1997 // arrays of arrays, but using just a one-dimensional array.
1998 glslang::TType simpleArrayType(type, 0); // deference type of the array
1999 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2000 simpleArrayType.getArraySizes().dereference();
2001
2002 // Will compute the higher-order strides here, rather than making a whole
2003 // pile of types and doing repetitive recursion on their contents.
2004 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2005 }
John Kessenichf8842e52016-01-04 19:22:56 -07002006
2007 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002008 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002009 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002010 if (stride > 0)
2011 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002012 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002013 }
2014 } else {
2015 // single-dimensional array, and don't yet have stride
2016
John Kessenichf8842e52016-01-04 19:22:56 -07002017 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002018 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2019 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002020 }
John Kessenich31ed4832015-09-09 17:51:38 -06002021
John Kessenichc9a80832015-09-12 12:17:44 -06002022 // Do the outer dimension, which might not be known for a runtime-sized array
2023 if (type.isRuntimeSizedArray()) {
2024 spvType = builder.makeRuntimeArray(spvType);
2025 } else {
2026 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002027 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002028 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002029 if (stride > 0)
2030 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002031 }
2032
2033 return spvType;
2034}
2035
John Kessenich6090df02016-06-30 21:18:02 -06002036
2037// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2038// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2039// Mutually recursive with convertGlslangToSpvType().
2040spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2041 const glslang::TTypeList* glslangMembers,
2042 glslang::TLayoutPacking explicitLayout,
2043 const glslang::TQualifier& qualifier)
2044{
2045 // Create a vector of struct types for SPIR-V to consume
2046 std::vector<spv::Id> spvMembers;
2047 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2048 int locationOffset = 0; // for use across struct members, when they are called recursively
2049 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2050 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2051 if (glslangMember.hiddenMember()) {
2052 ++memberDelta;
2053 if (type.getBasicType() == glslang::EbtBlock)
2054 memberRemapper[glslangMembers][i] = -1;
2055 } else {
2056 if (type.getBasicType() == glslang::EbtBlock)
2057 memberRemapper[glslangMembers][i] = i - memberDelta;
2058 // modify just this child's view of the qualifier
2059 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2060 InheritQualifiers(memberQualifier, qualifier);
2061
2062 // manually inherit location; it's more complex
2063 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2064 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2065 if (qualifier.hasLocation())
2066 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2067
2068 // recurse
2069 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2070 }
2071 }
2072
2073 // Make the SPIR-V type
2074 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002075 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002076 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2077
2078 // Decorate it
2079 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2080
2081 return spvType;
2082}
2083
2084void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2085 const glslang::TTypeList* glslangMembers,
2086 glslang::TLayoutPacking explicitLayout,
2087 const glslang::TQualifier& qualifier,
2088 spv::Id spvType)
2089{
2090 // Name and decorate the non-hidden members
2091 int offset = -1;
2092 int locationOffset = 0; // for use within the members of this struct
2093 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2094 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2095 int member = i;
2096 if (type.getBasicType() == glslang::EbtBlock)
2097 member = memberRemapper[glslangMembers][i];
2098
2099 // modify just this child's view of the qualifier
2100 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2101 InheritQualifiers(memberQualifier, qualifier);
2102
2103 // using -1 above to indicate a hidden member
2104 if (member >= 0) {
2105 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2106 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2107 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2108 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2109 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2110 if (type.getBasicType() == glslang::EbtBlock) {
2111 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2112 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2113 }
2114 }
2115 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2116
2117 if (qualifier.storage == glslang::EvqBuffer) {
2118 std::vector<spv::Decoration> memory;
2119 TranslateMemoryDecoration(memberQualifier, memory);
2120 for (unsigned int i = 0; i < memory.size(); ++i)
2121 addMemberDecoration(spvType, member, memory[i]);
2122 }
2123
John Kessenich2f47bc92016-06-30 21:47:35 -06002124 // Compute location decoration; tricky based on whether inheritance is at play and
2125 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002126 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2127 // probably move to the linker stage of the front end proper, and just have the
2128 // answer sitting already distributed throughout the individual member locations.
2129 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002130 // Ignore member locations if the container is an array, as that's
2131 // ill-specified and decisions have been made to not allow this anyway.
2132 // The object itself must have a location, and that comes out from decorating the object,
2133 // not the type (this code decorates types).
2134 if (! type.isArray()) {
2135 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2136 // struct members should not have explicit locations
2137 assert(type.getBasicType() != glslang::EbtStruct);
2138 location = memberQualifier.layoutLocation;
2139 } else if (type.getBasicType() != glslang::EbtBlock) {
2140 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2141 // The members, and their nested types, must not themselves have Location decorations.
2142 } else if (qualifier.hasLocation()) // inheritance
2143 location = qualifier.layoutLocation + locationOffset;
2144 }
John Kessenich6090df02016-06-30 21:18:02 -06002145 if (location >= 0)
2146 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2147
John Kessenich2f47bc92016-06-30 21:47:35 -06002148 if (qualifier.hasLocation()) // track for upcoming inheritance
2149 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2150
John Kessenich6090df02016-06-30 21:18:02 -06002151 // component, XFB, others
2152 if (glslangMember.getQualifier().hasComponent())
2153 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2154 if (glslangMember.getQualifier().hasXfbOffset())
2155 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2156 else if (explicitLayout != glslang::ElpNone) {
2157 // figure out what to do with offset, which is accumulating
2158 int nextOffset;
2159 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2160 if (offset >= 0)
2161 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2162 offset = nextOffset;
2163 }
2164
2165 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2166 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2167
2168 // built-in variable decorations
2169 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002170 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002171 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2172 }
2173 }
2174
2175 // Decorate the structure
2176 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2177 addDecoration(spvType, TranslateBlockDecoration(type));
2178 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2179 builder.addCapability(spv::CapabilityGeometryStreams);
2180 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2181 }
2182 if (glslangIntermediate->getXfbMode()) {
2183 builder.addCapability(spv::CapabilityTransformFeedback);
2184 if (type.getQualifier().hasXfbStride())
2185 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2186 if (type.getQualifier().hasXfbBuffer())
2187 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2188 }
2189}
2190
John Kessenich6c292d32016-02-15 20:58:50 -07002191// Turn the expression forming the array size into an id.
2192// This is not quite trivial, because of specialization constants.
2193// Sometimes, a raw constant is turned into an Id, and sometimes
2194// a specialization constant expression is.
2195spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2196{
2197 // First, see if this is sized with a node, meaning a specialization constant:
2198 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2199 if (specNode != nullptr) {
2200 builder.clearAccessChain();
2201 specNode->traverse(this);
2202 return accessChainLoad(specNode->getAsTyped()->getType());
2203 }
qining25262b32016-05-06 17:25:16 -04002204
John Kessenich6c292d32016-02-15 20:58:50 -07002205 // Otherwise, need a compile-time (front end) size, get it:
2206 int size = arraySizes.getDimSize(dim);
2207 assert(size > 0);
2208 return builder.makeUintConstant(size);
2209}
2210
John Kessenich103bef92016-02-08 21:38:15 -07002211// Wrap the builder's accessChainLoad to:
2212// - localize handling of RelaxedPrecision
2213// - use the SPIR-V inferred type instead of another conversion of the glslang type
2214// (avoids unnecessary work and possible type punning for structures)
2215// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002216spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2217{
John Kessenich103bef92016-02-08 21:38:15 -07002218 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2219 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2220
2221 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002222 if (type.getBasicType() == glslang::EbtBool) {
2223 if (builder.isScalarType(nominalTypeId)) {
2224 // Conversion for bool
2225 spv::Id boolType = builder.makeBoolType();
2226 if (nominalTypeId != boolType)
2227 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2228 } else if (builder.isVectorType(nominalTypeId)) {
2229 // Conversion for bvec
2230 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2231 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2232 if (nominalTypeId != bvecType)
2233 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2234 }
2235 }
John Kessenich103bef92016-02-08 21:38:15 -07002236
2237 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002238}
2239
Rex Xu27253232016-02-23 17:51:09 +08002240// Wrap the builder's accessChainStore to:
2241// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002242//
2243// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002244void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2245{
2246 // Need to convert to abstract types when necessary
2247 if (type.getBasicType() == glslang::EbtBool) {
2248 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2249
2250 if (builder.isScalarType(nominalTypeId)) {
2251 // Conversion for bool
2252 spv::Id boolType = builder.makeBoolType();
2253 if (nominalTypeId != boolType) {
2254 spv::Id zero = builder.makeUintConstant(0);
2255 spv::Id one = builder.makeUintConstant(1);
2256 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2257 }
2258 } else if (builder.isVectorType(nominalTypeId)) {
2259 // Conversion for bvec
2260 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2261 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2262 if (nominalTypeId != bvecType) {
2263 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2264 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2265 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2266 }
2267 }
2268 }
2269
2270 builder.accessChainStore(rvalue);
2271}
2272
John Kessenich4bf71552016-09-02 11:20:21 -06002273// For storing when types match at the glslang level, but not might match at the
2274// SPIR-V level.
2275//
2276// This especially happens when a single glslang type expands to multiple
2277// SPIR-V types, like a struct that is used in an member-undecorated way as well
2278// as in a member-decorated way.
2279//
2280// NOTE: This function can handle any store request; if it's not special it
2281// simplifies to a simple OpStore.
2282//
2283// Implicitly uses the existing builder.accessChain as the storage target.
2284void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2285{
2286 // we only do the complex path here if it's a structure
2287 if (! type.isStruct()) {
2288 accessChainStore(type, rValue);
2289 return;
2290 }
2291
2292 // and, it has to be a case of structure type aliasing
2293 spv::Id rType = builder.getTypeId(rValue);
2294 spv::Id lValue = builder.accessChainGetLValue();
2295 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2296 if (lType == rType) {
2297 accessChainStore(type, rValue);
2298 return;
2299 }
2300
2301 // Recursively (as needed) copy a struct type to a different struct type,
2302 // where the two types were the same type in GLSL. This requires member
2303 // by member copy, recursively.
2304
2305 // loop over members
2306 const glslang::TTypeList& members = *type.getStruct();
2307 for (int m = 0; m < (int)members.size(); ++m) {
2308 const glslang::TType& glslangMemberType = *members[m].type;
2309
2310 // get the source member
2311 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2312 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2313
2314 // set up the target storage
2315 builder.clearAccessChain();
2316 builder.setAccessChainLValue(lValue);
2317 builder.accessChainPush(builder.makeIntConstant(m));
2318
2319 // store the member
2320 multiTypeStore(glslangMemberType, memberRValue);
2321 }
2322}
2323
John Kessenichf85e8062015-12-19 13:57:10 -07002324// Decide whether or not this type should be
2325// decorated with offsets and strides, and if so
2326// whether std140 or std430 rules should be applied.
2327glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002328{
John Kessenichf85e8062015-12-19 13:57:10 -07002329 // has to be a block
2330 if (type.getBasicType() != glslang::EbtBlock)
2331 return glslang::ElpNone;
2332
2333 // has to be a uniform or buffer block
2334 if (type.getQualifier().storage != glslang::EvqUniform &&
2335 type.getQualifier().storage != glslang::EvqBuffer)
2336 return glslang::ElpNone;
2337
2338 // return the layout to use
2339 switch (type.getQualifier().layoutPacking) {
2340 case glslang::ElpStd140:
2341 case glslang::ElpStd430:
2342 return type.getQualifier().layoutPacking;
2343 default:
2344 return glslang::ElpNone;
2345 }
John Kessenich31ed4832015-09-09 17:51:38 -06002346}
2347
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002348// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002349int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002350{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002351 int size;
John Kessenich49987892015-12-29 17:11:44 -07002352 int stride;
2353 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002354
2355 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002356}
2357
John Kessenich49987892015-12-29 17:11:44 -07002358// 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 -07002359// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002360int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002361{
John Kessenich49987892015-12-29 17:11:44 -07002362 glslang::TType elementType;
2363 elementType.shallowCopy(matrixType);
2364 elementType.clearArraySizes();
2365
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002366 int size;
John Kessenich49987892015-12-29 17:11:44 -07002367 int stride;
2368 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2369
2370 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002371}
2372
John Kessenich5e4b1242015-08-06 22:53:06 -06002373// Given a member type of a struct, realign the current offset for it, and compute
2374// the next (not yet aligned) offset for the next member, which will get aligned
2375// on the next call.
2376// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2377// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2378// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002379void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002380 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002381{
2382 // this will get a positive value when deemed necessary
2383 nextOffset = -1;
2384
John Kessenich5e4b1242015-08-06 22:53:06 -06002385 // override anything in currentOffset with user-set offset
2386 if (memberType.getQualifier().hasOffset())
2387 currentOffset = memberType.getQualifier().layoutOffset;
2388
2389 // It could be that current linker usage in glslang updated all the layoutOffset,
2390 // in which case the following code does not matter. But, that's not quite right
2391 // once cross-compilation unit GLSL validation is done, as the original user
2392 // settings are needed in layoutOffset, and then the following will come into play.
2393
John Kessenichf85e8062015-12-19 13:57:10 -07002394 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002395 if (! memberType.getQualifier().hasOffset())
2396 currentOffset = -1;
2397
2398 return;
2399 }
2400
John Kessenichf85e8062015-12-19 13:57:10 -07002401 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002402 if (currentOffset < 0)
2403 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002404
John Kessenich5e4b1242015-08-06 22:53:06 -06002405 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2406 // but possibly not yet correctly aligned.
2407
2408 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002409 int dummyStride;
2410 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002411 glslang::RoundToPow2(currentOffset, memberAlignment);
2412 nextOffset = currentOffset + memberSize;
2413}
2414
David Netoa901ffe2016-06-08 14:11:40 +01002415void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002416{
David Netoa901ffe2016-06-08 14:11:40 +01002417 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2418 switch (glslangBuiltIn)
2419 {
2420 case glslang::EbvClipDistance:
2421 case glslang::EbvCullDistance:
2422 case glslang::EbvPointSize:
2423 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2424 // Alternately, we could just call this for any glslang built-in, since the
2425 // capability already guards against duplicates.
2426 TranslateBuiltInDecoration(glslangBuiltIn, false);
2427 break;
2428 default:
2429 // Capabilities were already generated when the struct was declared.
2430 break;
2431 }
John Kessenichebb50532016-05-16 19:22:05 -06002432}
2433
John Kessenich140f3df2015-06-26 16:58:36 -06002434bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2435{
John Kessenich4d65ee32016-03-12 18:17:47 -07002436 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002437 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002438 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002439}
2440
2441// Make all the functions, skeletally, without actually visiting their bodies.
2442void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2443{
2444 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2445 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2446 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2447 continue;
2448
2449 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002450 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002451 //
qining25262b32016-05-06 17:25:16 -04002452 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002453 // function. What it is an address of varies:
2454 //
John Kessenich4bf71552016-09-02 11:20:21 -06002455 // - "in" parameters not marked as "const" can be written to without modifying the calling
2456 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002457 //
2458 // - "const in" parameters can just be the r-value, as no writes need occur.
2459 //
John Kessenich4bf71552016-09-02 11:20:21 -06002460 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2461 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06002462
2463 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002464 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002465 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2466
2467 for (int p = 0; p < (int)parameters.size(); ++p) {
2468 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2469 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002470 if (paramType.isOpaque())
2471 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2472 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002473 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2474 else
John Kessenich4bf71552016-09-02 11:20:21 -06002475 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002476 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002477 paramTypes.push_back(typeId);
2478 }
2479
2480 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002481 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2482 convertGlslangToSpvType(glslFunction->getType()),
2483 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002484
2485 // Track function to emit/call later
2486 functionMap[glslFunction->getName().c_str()] = function;
2487
2488 // Set the parameter id's
2489 for (int p = 0; p < (int)parameters.size(); ++p) {
2490 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2491 // give a name too
2492 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2493 }
2494 }
2495}
2496
2497// Process all the initializers, while skipping the functions and link objects
2498void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2499{
2500 builder.setBuildPoint(shaderEntry->getLastBlock());
2501 for (int i = 0; i < (int)initializers.size(); ++i) {
2502 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2503 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2504
2505 // We're on a top-level node that's not a function. Treat as an initializer, whose
2506 // code goes into the beginning of main.
2507 initializer->traverse(this);
2508 }
2509 }
2510}
2511
2512// Process all the functions, while skipping initializers.
2513void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2514{
2515 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2516 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2517 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2518 node->traverse(this);
2519 }
2520}
2521
2522void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2523{
qining25262b32016-05-06 17:25:16 -04002524 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002525 // that called makeFunctions().
2526 spv::Function* function = functionMap[node->getName().c_str()];
2527 spv::Block* functionBlock = function->getEntryBlock();
2528 builder.setBuildPoint(functionBlock);
2529}
2530
Rex Xu04db3f52015-09-16 11:44:02 +08002531void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002532{
Rex Xufc618912015-09-09 16:42:49 +08002533 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002534
2535 glslang::TSampler sampler = {};
2536 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002537 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002538 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2539 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2540 }
2541
John Kessenich140f3df2015-06-26 16:58:36 -06002542 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2543 builder.clearAccessChain();
2544 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002545
2546 // Special case l-value operands
2547 bool lvalue = false;
2548 switch (node.getOp()) {
2549 case glslang::EOpImageAtomicAdd:
2550 case glslang::EOpImageAtomicMin:
2551 case glslang::EOpImageAtomicMax:
2552 case glslang::EOpImageAtomicAnd:
2553 case glslang::EOpImageAtomicOr:
2554 case glslang::EOpImageAtomicXor:
2555 case glslang::EOpImageAtomicExchange:
2556 case glslang::EOpImageAtomicCompSwap:
2557 if (i == 0)
2558 lvalue = true;
2559 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002560 case glslang::EOpSparseImageLoad:
2561 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2562 lvalue = true;
2563 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002564 case glslang::EOpSparseTexture:
2565 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2566 lvalue = true;
2567 break;
2568 case glslang::EOpSparseTextureClamp:
2569 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2570 lvalue = true;
2571 break;
2572 case glslang::EOpSparseTextureLod:
2573 case glslang::EOpSparseTextureOffset:
2574 if (i == 3)
2575 lvalue = true;
2576 break;
2577 case glslang::EOpSparseTextureFetch:
2578 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2579 lvalue = true;
2580 break;
2581 case glslang::EOpSparseTextureFetchOffset:
2582 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2583 lvalue = true;
2584 break;
2585 case glslang::EOpSparseTextureLodOffset:
2586 case glslang::EOpSparseTextureGrad:
2587 case glslang::EOpSparseTextureOffsetClamp:
2588 if (i == 4)
2589 lvalue = true;
2590 break;
2591 case glslang::EOpSparseTextureGradOffset:
2592 case glslang::EOpSparseTextureGradClamp:
2593 if (i == 5)
2594 lvalue = true;
2595 break;
2596 case glslang::EOpSparseTextureGradOffsetClamp:
2597 if (i == 6)
2598 lvalue = true;
2599 break;
2600 case glslang::EOpSparseTextureGather:
2601 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2602 lvalue = true;
2603 break;
2604 case glslang::EOpSparseTextureGatherOffset:
2605 case glslang::EOpSparseTextureGatherOffsets:
2606 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2607 lvalue = true;
2608 break;
Rex Xufc618912015-09-09 16:42:49 +08002609 default:
2610 break;
2611 }
2612
Rex Xu6b86d492015-09-16 17:48:22 +08002613 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002614 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002615 else
John Kessenich32cfd492016-02-02 12:37:46 -07002616 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002617 }
2618}
2619
John Kessenichfc51d282015-08-19 13:34:18 -06002620void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002621{
John Kessenichfc51d282015-08-19 13:34:18 -06002622 builder.clearAccessChain();
2623 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002624 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002625}
John Kessenich140f3df2015-06-26 16:58:36 -06002626
John Kessenichfc51d282015-08-19 13:34:18 -06002627spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2628{
Rex Xufc618912015-09-09 16:42:49 +08002629 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002630 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002631 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002632 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002633
John Kessenichfc51d282015-08-19 13:34:18 -06002634 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002635 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2636 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2637 std::vector<spv::Id> arguments;
2638 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002639 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002640 else
2641 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002642 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002643
2644 spv::Builder::TextureParameters params = { };
2645 params.sampler = arguments[0];
2646
Rex Xu04db3f52015-09-16 11:44:02 +08002647 glslang::TCrackedTextureOp cracked;
2648 node->crackTexture(sampler, cracked);
2649
John Kessenichfc51d282015-08-19 13:34:18 -06002650 // Check for queries
2651 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002652 // a sampled image needs to have the image extracted first
2653 if (builder.isSampledImage(params.sampler))
2654 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002655 switch (node->getOp()) {
2656 case glslang::EOpImageQuerySize:
2657 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002658 if (arguments.size() > 1) {
2659 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002660 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002661 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002662 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002663 case glslang::EOpImageQuerySamples:
2664 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002665 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002666 case glslang::EOpTextureQueryLod:
2667 params.coords = arguments[1];
2668 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2669 case glslang::EOpTextureQueryLevels:
2670 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002671 case glslang::EOpSparseTexelsResident:
2672 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002673 default:
2674 assert(0);
2675 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002676 }
John Kessenich140f3df2015-06-26 16:58:36 -06002677 }
2678
Rex Xufc618912015-09-09 16:42:49 +08002679 // Check for image functions other than queries
2680 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002681 std::vector<spv::Id> operands;
2682 auto opIt = arguments.begin();
2683 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002684
2685 // Handle subpass operations
2686 // TODO: GLSL should change to have the "MS" only on the type rather than the
2687 // built-in function.
2688 if (cracked.subpass) {
2689 // add on the (0,0) coordinate
2690 spv::Id zero = builder.makeIntConstant(0);
2691 std::vector<spv::Id> comps;
2692 comps.push_back(zero);
2693 comps.push_back(zero);
2694 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2695 if (sampler.ms) {
2696 operands.push_back(spv::ImageOperandsSampleMask);
2697 operands.push_back(*(opIt++));
2698 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002699 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002700 }
2701
John Kessenich56bab042015-09-16 10:54:31 -06002702 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002703 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002704 if (sampler.ms) {
2705 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002706 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002707 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002708 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2709 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002710 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002711 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002712 if (sampler.ms) {
2713 operands.push_back(*(opIt + 1));
2714 operands.push_back(spv::ImageOperandsSampleMask);
2715 operands.push_back(*opIt);
2716 } else
2717 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002718 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002719 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2720 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002721 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002722 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2723 builder.addCapability(spv::CapabilitySparseResidency);
2724 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2725 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2726
2727 if (sampler.ms) {
2728 operands.push_back(spv::ImageOperandsSampleMask);
2729 operands.push_back(*opIt++);
2730 }
2731
2732 // Create the return type that was a special structure
2733 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002734 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002735 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2736 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2737
2738 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2739
2740 // Decode the return type
2741 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2742 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002743 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002744 // Process image atomic operations
2745
2746 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2747 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002748 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002749
John Kessenich8c8505c2016-07-26 12:50:38 -06002750 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002751 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002752
2753 std::vector<spv::Id> operands;
2754 operands.push_back(pointer);
2755 for (; opIt != arguments.end(); ++opIt)
2756 operands.push_back(*opIt);
2757
John Kessenich8c8505c2016-07-26 12:50:38 -06002758 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002759 }
2760 }
2761
2762 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002763 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002764 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2765
John Kessenichfc51d282015-08-19 13:34:18 -06002766 // check for bias argument
2767 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002768 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002769 int nonBiasArgCount = 2;
2770 if (cracked.offset)
2771 ++nonBiasArgCount;
2772 if (cracked.grad)
2773 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002774 if (cracked.lodClamp)
2775 ++nonBiasArgCount;
2776 if (sparse)
2777 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002778
2779 if ((int)arguments.size() > nonBiasArgCount)
2780 bias = true;
2781 }
2782
John Kessenicha5c33d62016-06-02 23:45:21 -06002783 // See if the sampler param should really be just the SPV image part
2784 if (cracked.fetch) {
2785 // a fetch needs to have the image extracted first
2786 if (builder.isSampledImage(params.sampler))
2787 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2788 }
2789
John Kessenichfc51d282015-08-19 13:34:18 -06002790 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002791
John Kessenichfc51d282015-08-19 13:34:18 -06002792 params.coords = arguments[1];
2793 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002794 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002795
2796 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002797 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002798 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002799 ++extraArgs;
2800 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002801 params.Dref = arguments[2];
2802 ++extraArgs;
2803 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002804 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002805 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002806 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002807 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002808 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002809 dRefComp = builder.getNumComponents(params.coords) - 1;
2810 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002811 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2812 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002813
2814 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002815 if (cracked.lod) {
2816 params.lod = arguments[2];
2817 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002818 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2819 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2820 noImplicitLod = true;
2821 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002822
2823 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002824 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002825 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002826 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002827 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002828
2829 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002830 if (cracked.grad) {
2831 params.gradX = arguments[2 + extraArgs];
2832 params.gradY = arguments[3 + extraArgs];
2833 extraArgs += 2;
2834 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002835
2836 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002837 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002838 params.offset = arguments[2 + extraArgs];
2839 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002840 } else if (cracked.offsets) {
2841 params.offsets = arguments[2 + extraArgs];
2842 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002843 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002844
2845 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002846 if (cracked.lodClamp) {
2847 params.lodClamp = arguments[2 + extraArgs];
2848 ++extraArgs;
2849 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002850
2851 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002852 if (sparse) {
2853 params.texelOut = arguments[2 + extraArgs];
2854 ++extraArgs;
2855 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002856
2857 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002858 if (bias) {
2859 params.bias = arguments[2 + extraArgs];
2860 ++extraArgs;
2861 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002862
2863 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002864 if (cracked.gather && ! sampler.shadow) {
2865 // default component is 0, if missing, otherwise an argument
2866 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002867 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002868 ++extraArgs;
2869 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002870 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002871 }
2872 }
John Kessenichfc51d282015-08-19 13:34:18 -06002873
John Kessenich65336482016-06-16 14:06:26 -06002874 // projective component (might not to move)
2875 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2876 // are divided by the last component of P."
2877 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2878 // unused components will appear after all used components."
2879 if (cracked.proj) {
2880 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2881 int projTargetComp;
2882 switch (sampler.dim) {
2883 case glslang::Esd1D: projTargetComp = 1; break;
2884 case glslang::Esd2D: projTargetComp = 2; break;
2885 case glslang::EsdRect: projTargetComp = 2; break;
2886 default: projTargetComp = projSourceComp; break;
2887 }
2888 // copy the projective coordinate if we have to
2889 if (projTargetComp != projSourceComp) {
2890 spv::Id projComp = builder.createCompositeExtract(params.coords,
2891 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2892 projSourceComp);
2893 params.coords = builder.createCompositeInsert(projComp, params.coords,
2894 builder.getTypeId(params.coords), projTargetComp);
2895 }
2896 }
2897
John Kessenich8c8505c2016-07-26 12:50:38 -06002898 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002899}
2900
2901spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2902{
2903 // Grab the function's pointer from the previously created function
2904 spv::Function* function = functionMap[node->getName().c_str()];
2905 if (! function)
2906 return 0;
2907
2908 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2909 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2910
2911 // See comments in makeFunctions() for details about the semantics for parameter passing.
2912 //
2913 // These imply we need a four step process:
2914 // 1. Evaluate the arguments
2915 // 2. Allocate and make copies of in, out, and inout arguments
2916 // 3. Make the call
2917 // 4. Copy back the results
2918
2919 // 1. Evaluate the arguments
2920 std::vector<spv::Builder::AccessChain> lValues;
2921 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002922 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002923 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002924 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002925 // build l-value
2926 builder.clearAccessChain();
2927 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002928 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002929 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002930 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002931 // save l-value
2932 lValues.push_back(builder.getAccessChain());
2933 } else {
2934 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002935 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002936 }
2937 }
2938
2939 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2940 // copy the original into that space.
2941 //
2942 // Also, build up the list of actual arguments to pass in for the call
2943 int lValueCount = 0;
2944 int rValueCount = 0;
2945 std::vector<spv::Id> spvArgs;
2946 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002947 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002948 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002949 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002950 builder.setAccessChain(lValues[lValueCount]);
2951 arg = builder.accessChainGetLValue();
2952 ++lValueCount;
2953 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06002954 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06002955 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2956 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2957 // need to copy the input into output space
2958 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002959 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06002960 builder.clearAccessChain();
2961 builder.setAccessChainLValue(arg);
2962 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002963 }
2964 ++lValueCount;
2965 } else {
2966 arg = rValues[rValueCount];
2967 ++rValueCount;
2968 }
2969 spvArgs.push_back(arg);
2970 }
2971
2972 // 3. Make the call.
2973 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002974 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002975
2976 // 4. Copy back out an "out" arguments.
2977 lValueCount = 0;
2978 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06002979 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002980 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2981 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2982 spv::Id copy = builder.createLoad(spvArgs[a]);
2983 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06002984 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002985 }
2986 ++lValueCount;
2987 }
2988 }
2989
2990 return result;
2991}
2992
2993// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04002994spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2995 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06002996 spv::Id typeId, spv::Id left, spv::Id right,
2997 glslang::TBasicType typeProxy, bool reduceComparison)
2998{
Rex Xu8ff43de2016-04-22 16:51:45 +08002999 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003000 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08003001 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003002
3003 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003004 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003005 bool comparison = false;
3006
3007 switch (op) {
3008 case glslang::EOpAdd:
3009 case glslang::EOpAddAssign:
3010 if (isFloat)
3011 binOp = spv::OpFAdd;
3012 else
3013 binOp = spv::OpIAdd;
3014 break;
3015 case glslang::EOpSub:
3016 case glslang::EOpSubAssign:
3017 if (isFloat)
3018 binOp = spv::OpFSub;
3019 else
3020 binOp = spv::OpISub;
3021 break;
3022 case glslang::EOpMul:
3023 case glslang::EOpMulAssign:
3024 if (isFloat)
3025 binOp = spv::OpFMul;
3026 else
3027 binOp = spv::OpIMul;
3028 break;
3029 case glslang::EOpVectorTimesScalar:
3030 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003031 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003032 if (builder.isVector(right))
3033 std::swap(left, right);
3034 assert(builder.isScalar(right));
3035 needMatchingVectors = false;
3036 binOp = spv::OpVectorTimesScalar;
3037 } else
3038 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpVectorTimesMatrix:
3041 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003042 binOp = spv::OpVectorTimesMatrix;
3043 break;
3044 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003045 binOp = spv::OpMatrixTimesVector;
3046 break;
3047 case glslang::EOpMatrixTimesScalar:
3048 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003049 binOp = spv::OpMatrixTimesScalar;
3050 break;
3051 case glslang::EOpMatrixTimesMatrix:
3052 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003053 binOp = spv::OpMatrixTimesMatrix;
3054 break;
3055 case glslang::EOpOuterProduct:
3056 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003057 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003058 break;
3059
3060 case glslang::EOpDiv:
3061 case glslang::EOpDivAssign:
3062 if (isFloat)
3063 binOp = spv::OpFDiv;
3064 else if (isUnsigned)
3065 binOp = spv::OpUDiv;
3066 else
3067 binOp = spv::OpSDiv;
3068 break;
3069 case glslang::EOpMod:
3070 case glslang::EOpModAssign:
3071 if (isFloat)
3072 binOp = spv::OpFMod;
3073 else if (isUnsigned)
3074 binOp = spv::OpUMod;
3075 else
3076 binOp = spv::OpSMod;
3077 break;
3078 case glslang::EOpRightShift:
3079 case glslang::EOpRightShiftAssign:
3080 if (isUnsigned)
3081 binOp = spv::OpShiftRightLogical;
3082 else
3083 binOp = spv::OpShiftRightArithmetic;
3084 break;
3085 case glslang::EOpLeftShift:
3086 case glslang::EOpLeftShiftAssign:
3087 binOp = spv::OpShiftLeftLogical;
3088 break;
3089 case glslang::EOpAnd:
3090 case glslang::EOpAndAssign:
3091 binOp = spv::OpBitwiseAnd;
3092 break;
3093 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003094 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003095 binOp = spv::OpLogicalAnd;
3096 break;
3097 case glslang::EOpInclusiveOr:
3098 case glslang::EOpInclusiveOrAssign:
3099 binOp = spv::OpBitwiseOr;
3100 break;
3101 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003102 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003103 binOp = spv::OpLogicalOr;
3104 break;
3105 case glslang::EOpExclusiveOr:
3106 case glslang::EOpExclusiveOrAssign:
3107 binOp = spv::OpBitwiseXor;
3108 break;
3109 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003110 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003111 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003112 break;
3113
3114 case glslang::EOpLessThan:
3115 case glslang::EOpGreaterThan:
3116 case glslang::EOpLessThanEqual:
3117 case glslang::EOpGreaterThanEqual:
3118 case glslang::EOpEqual:
3119 case glslang::EOpNotEqual:
3120 case glslang::EOpVectorEqual:
3121 case glslang::EOpVectorNotEqual:
3122 comparison = true;
3123 break;
3124 default:
3125 break;
3126 }
3127
John Kessenich7c1aa102015-10-15 13:29:11 -06003128 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003129 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003130 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003131 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003132 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003133
3134 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003135 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003136 builder.promoteScalar(precision, left, right);
3137
qining25262b32016-05-06 17:25:16 -04003138 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3139 addDecoration(result, noContraction);
3140 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003141 }
3142
3143 if (! comparison)
3144 return 0;
3145
John Kessenich7c1aa102015-10-15 13:29:11 -06003146 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003147
John Kessenich4583b612016-08-07 19:14:22 -06003148 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3149 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003150 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003151
3152 switch (op) {
3153 case glslang::EOpLessThan:
3154 if (isFloat)
3155 binOp = spv::OpFOrdLessThan;
3156 else if (isUnsigned)
3157 binOp = spv::OpULessThan;
3158 else
3159 binOp = spv::OpSLessThan;
3160 break;
3161 case glslang::EOpGreaterThan:
3162 if (isFloat)
3163 binOp = spv::OpFOrdGreaterThan;
3164 else if (isUnsigned)
3165 binOp = spv::OpUGreaterThan;
3166 else
3167 binOp = spv::OpSGreaterThan;
3168 break;
3169 case glslang::EOpLessThanEqual:
3170 if (isFloat)
3171 binOp = spv::OpFOrdLessThanEqual;
3172 else if (isUnsigned)
3173 binOp = spv::OpULessThanEqual;
3174 else
3175 binOp = spv::OpSLessThanEqual;
3176 break;
3177 case glslang::EOpGreaterThanEqual:
3178 if (isFloat)
3179 binOp = spv::OpFOrdGreaterThanEqual;
3180 else if (isUnsigned)
3181 binOp = spv::OpUGreaterThanEqual;
3182 else
3183 binOp = spv::OpSGreaterThanEqual;
3184 break;
3185 case glslang::EOpEqual:
3186 case glslang::EOpVectorEqual:
3187 if (isFloat)
3188 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003189 else if (isBool)
3190 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 else
3192 binOp = spv::OpIEqual;
3193 break;
3194 case glslang::EOpNotEqual:
3195 case glslang::EOpVectorNotEqual:
3196 if (isFloat)
3197 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003198 else if (isBool)
3199 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003200 else
3201 binOp = spv::OpINotEqual;
3202 break;
3203 default:
3204 break;
3205 }
3206
qining25262b32016-05-06 17:25:16 -04003207 if (binOp != spv::OpNop) {
3208 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3209 addDecoration(result, noContraction);
3210 return builder.setPrecision(result, precision);
3211 }
John Kessenich140f3df2015-06-26 16:58:36 -06003212
3213 return 0;
3214}
3215
John Kessenich04bb8a02015-12-12 12:28:14 -07003216//
3217// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3218// These can be any of:
3219//
3220// matrix * scalar
3221// scalar * matrix
3222// matrix * matrix linear algebraic
3223// matrix * vector
3224// vector * matrix
3225// matrix * matrix componentwise
3226// matrix op matrix op in {+, -, /}
3227// matrix op scalar op in {+, -, /}
3228// scalar op matrix op in {+, -, /}
3229//
qining25262b32016-05-06 17:25:16 -04003230spv::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 -07003231{
3232 bool firstClass = true;
3233
3234 // First, handle first-class matrix operations (* and matrix/scalar)
3235 switch (op) {
3236 case spv::OpFDiv:
3237 if (builder.isMatrix(left) && builder.isScalar(right)) {
3238 // turn matrix / scalar into a multiply...
3239 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3240 op = spv::OpMatrixTimesScalar;
3241 } else
3242 firstClass = false;
3243 break;
3244 case spv::OpMatrixTimesScalar:
3245 if (builder.isMatrix(right))
3246 std::swap(left, right);
3247 assert(builder.isScalar(right));
3248 break;
3249 case spv::OpVectorTimesMatrix:
3250 assert(builder.isVector(left));
3251 assert(builder.isMatrix(right));
3252 break;
3253 case spv::OpMatrixTimesVector:
3254 assert(builder.isMatrix(left));
3255 assert(builder.isVector(right));
3256 break;
3257 case spv::OpMatrixTimesMatrix:
3258 assert(builder.isMatrix(left));
3259 assert(builder.isMatrix(right));
3260 break;
3261 default:
3262 firstClass = false;
3263 break;
3264 }
3265
qining25262b32016-05-06 17:25:16 -04003266 if (firstClass) {
3267 spv::Id result = builder.createBinOp(op, typeId, left, right);
3268 addDecoration(result, noContraction);
3269 return builder.setPrecision(result, precision);
3270 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003271
LoopDawg592860c2016-06-09 08:57:35 -06003272 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003273 // The result type of all of them is the same type as the (a) matrix operand.
3274 // The algorithm is to:
3275 // - break the matrix(es) into vectors
3276 // - smear any scalar to a vector
3277 // - do vector operations
3278 // - make a matrix out the vector results
3279 switch (op) {
3280 case spv::OpFAdd:
3281 case spv::OpFSub:
3282 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003283 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003284 case spv::OpFMul:
3285 {
3286 // one time set up...
3287 bool leftMat = builder.isMatrix(left);
3288 bool rightMat = builder.isMatrix(right);
3289 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3290 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3291 spv::Id scalarType = builder.getScalarTypeId(typeId);
3292 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3293 std::vector<spv::Id> results;
3294 spv::Id smearVec = spv::NoResult;
3295 if (builder.isScalar(left))
3296 smearVec = builder.smearScalar(precision, left, vecType);
3297 else if (builder.isScalar(right))
3298 smearVec = builder.smearScalar(precision, right, vecType);
3299
3300 // do each vector op
3301 for (unsigned int c = 0; c < numCols; ++c) {
3302 std::vector<unsigned int> indexes;
3303 indexes.push_back(c);
3304 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3305 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003306 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3307 addDecoration(result, noContraction);
3308 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003309 }
3310
3311 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003312 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003313 }
3314 default:
3315 assert(0);
3316 return spv::NoResult;
3317 }
3318}
3319
qining25262b32016-05-06 17:25:16 -04003320spv::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 -06003321{
3322 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003323 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003325 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003326 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003327
3328 switch (op) {
3329 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003330 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003331 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003332 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003333 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003334 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003335 unaryOp = spv::OpSNegate;
3336 break;
3337
3338 case glslang::EOpLogicalNot:
3339 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003340 unaryOp = spv::OpLogicalNot;
3341 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003342 case glslang::EOpBitwiseNot:
3343 unaryOp = spv::OpNot;
3344 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003345
John Kessenich140f3df2015-06-26 16:58:36 -06003346 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003347 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003348 break;
3349 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003350 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003351 break;
3352 case glslang::EOpTranspose:
3353 unaryOp = spv::OpTranspose;
3354 break;
3355
3356 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003357 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003358 break;
3359 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003360 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003361 break;
3362 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003363 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003364 break;
3365 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003366 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003367 break;
3368 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003369 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003370 break;
3371 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003372 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003373 break;
3374 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003375 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003376 break;
3377 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003378 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003379 break;
3380
3381 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003382 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003383 break;
3384 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003385 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003386 break;
3387 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003388 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003389 break;
3390 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003391 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003392 break;
3393 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003394 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003395 break;
3396 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003397 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003398 break;
3399
3400 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003401 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003402 break;
3403 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003404 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003405 break;
3406
3407 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003408 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003409 break;
3410 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003411 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003412 break;
3413 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003414 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003415 break;
3416 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003417 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 break;
3419 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003420 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003421 break;
3422 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003423 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003424 break;
3425
3426 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003428 break;
3429 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003430 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003431 break;
3432 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003433 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003434 break;
3435 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003436 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003437 break;
3438 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003439 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003440 break;
3441 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003442 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003443 break;
3444
3445 case glslang::EOpIsNan:
3446 unaryOp = spv::OpIsNan;
3447 break;
3448 case glslang::EOpIsInf:
3449 unaryOp = spv::OpIsInf;
3450 break;
LoopDawg592860c2016-06-09 08:57:35 -06003451 case glslang::EOpIsFinite:
3452 unaryOp = spv::OpIsFinite;
3453 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003454
Rex Xucbc426e2015-12-15 16:03:10 +08003455 case glslang::EOpFloatBitsToInt:
3456 case glslang::EOpFloatBitsToUint:
3457 case glslang::EOpIntBitsToFloat:
3458 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003459 case glslang::EOpDoubleBitsToInt64:
3460 case glslang::EOpDoubleBitsToUint64:
3461 case glslang::EOpInt64BitsToDouble:
3462 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003463 unaryOp = spv::OpBitcast;
3464 break;
3465
John Kessenich140f3df2015-06-26 16:58:36 -06003466 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003467 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003468 break;
3469 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003470 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003471 break;
3472 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003473 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003474 break;
3475 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003476 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003477 break;
3478 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003482 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003483 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003484 case glslang::EOpPackSnorm4x8:
3485 libCall = spv::GLSLstd450PackSnorm4x8;
3486 break;
3487 case glslang::EOpUnpackSnorm4x8:
3488 libCall = spv::GLSLstd450UnpackSnorm4x8;
3489 break;
3490 case glslang::EOpPackUnorm4x8:
3491 libCall = spv::GLSLstd450PackUnorm4x8;
3492 break;
3493 case glslang::EOpUnpackUnorm4x8:
3494 libCall = spv::GLSLstd450UnpackUnorm4x8;
3495 break;
3496 case glslang::EOpPackDouble2x32:
3497 libCall = spv::GLSLstd450PackDouble2x32;
3498 break;
3499 case glslang::EOpUnpackDouble2x32:
3500 libCall = spv::GLSLstd450UnpackDouble2x32;
3501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003502
Rex Xu8ff43de2016-04-22 16:51:45 +08003503 case glslang::EOpPackInt2x32:
3504 case glslang::EOpUnpackInt2x32:
3505 case glslang::EOpPackUint2x32:
3506 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003507 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003508 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3509 break;
3510
John Kessenich140f3df2015-06-26 16:58:36 -06003511 case glslang::EOpDPdx:
3512 unaryOp = spv::OpDPdx;
3513 break;
3514 case glslang::EOpDPdy:
3515 unaryOp = spv::OpDPdy;
3516 break;
3517 case glslang::EOpFwidth:
3518 unaryOp = spv::OpFwidth;
3519 break;
3520 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003521 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003522 unaryOp = spv::OpDPdxFine;
3523 break;
3524 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003525 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003526 unaryOp = spv::OpDPdyFine;
3527 break;
3528 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003529 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003530 unaryOp = spv::OpFwidthFine;
3531 break;
3532 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003533 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003534 unaryOp = spv::OpDPdxCoarse;
3535 break;
3536 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003537 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003538 unaryOp = spv::OpDPdyCoarse;
3539 break;
3540 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003541 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003542 unaryOp = spv::OpFwidthCoarse;
3543 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003544 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003545 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003546 libCall = spv::GLSLstd450InterpolateAtCentroid;
3547 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003548 case glslang::EOpAny:
3549 unaryOp = spv::OpAny;
3550 break;
3551 case glslang::EOpAll:
3552 unaryOp = spv::OpAll;
3553 break;
3554
3555 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003556 if (isFloat)
3557 libCall = spv::GLSLstd450FAbs;
3558 else
3559 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003560 break;
3561 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003562 if (isFloat)
3563 libCall = spv::GLSLstd450FSign;
3564 else
3565 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003566 break;
3567
John Kessenichfc51d282015-08-19 13:34:18 -06003568 case glslang::EOpAtomicCounterIncrement:
3569 case glslang::EOpAtomicCounterDecrement:
3570 case glslang::EOpAtomicCounter:
3571 {
3572 // Handle all of the atomics in one place, in createAtomicOperation()
3573 std::vector<spv::Id> operands;
3574 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003575 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003576 }
3577
John Kessenichfc51d282015-08-19 13:34:18 -06003578 case glslang::EOpBitFieldReverse:
3579 unaryOp = spv::OpBitReverse;
3580 break;
3581 case glslang::EOpBitCount:
3582 unaryOp = spv::OpBitCount;
3583 break;
3584 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003585 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003586 break;
3587 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003588 if (isUnsigned)
3589 libCall = spv::GLSLstd450FindUMsb;
3590 else
3591 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003592 break;
3593
Rex Xu574ab042016-04-14 16:53:07 +08003594 case glslang::EOpBallot:
3595 case glslang::EOpReadFirstInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06003596 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08003597 libCall = spv::GLSLstd450Bad;
3598 break;
3599
Rex Xu338b1852016-05-05 20:38:33 +08003600 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003601 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003602 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003603#ifdef AMD_EXTENSIONS
3604 case glslang::EOpMinInvocations:
3605 case glslang::EOpMaxInvocations:
3606 case glslang::EOpAddInvocations:
3607 case glslang::EOpMinInvocationsNonUniform:
3608 case glslang::EOpMaxInvocationsNonUniform:
3609 case glslang::EOpAddInvocationsNonUniform:
3610#endif
3611 return createInvocationsOperation(op, typeId, operand, typeProxy);
3612
3613#ifdef AMD_EXTENSIONS
3614 case glslang::EOpMbcnt:
3615 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3616 libCall = spv::MbcntAMD;
3617 break;
3618
3619 case glslang::EOpCubeFaceIndex:
3620 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3621 libCall = spv::CubeFaceIndexAMD;
3622 break;
3623
3624 case glslang::EOpCubeFaceCoord:
3625 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3626 libCall = spv::CubeFaceCoordAMD;
3627 break;
3628#endif
Rex Xu338b1852016-05-05 20:38:33 +08003629
John Kessenich140f3df2015-06-26 16:58:36 -06003630 default:
3631 return 0;
3632 }
3633
3634 spv::Id id;
3635 if (libCall >= 0) {
3636 std::vector<spv::Id> args;
3637 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003638 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003639 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003640 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003641 }
John Kessenich140f3df2015-06-26 16:58:36 -06003642
qining25262b32016-05-06 17:25:16 -04003643 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003644 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003645}
3646
John Kessenich7a53f762016-01-20 11:19:27 -07003647// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003648spv::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 -07003649{
3650 // Handle unary operations vector by vector.
3651 // The result type is the same type as the original type.
3652 // The algorithm is to:
3653 // - break the matrix into vectors
3654 // - apply the operation to each vector
3655 // - make a matrix out the vector results
3656
3657 // get the types sorted out
3658 int numCols = builder.getNumColumns(operand);
3659 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003660 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3661 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003662 std::vector<spv::Id> results;
3663
3664 // do each vector op
3665 for (int c = 0; c < numCols; ++c) {
3666 std::vector<unsigned int> indexes;
3667 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003668 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3669 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3670 addDecoration(destVec, noContraction);
3671 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003672 }
3673
3674 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003675 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003676}
3677
Rex Xu73e3ce72016-04-27 18:48:17 +08003678spv::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 -06003679{
3680 spv::Op convOp = spv::OpNop;
3681 spv::Id zero = 0;
3682 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003683 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003684
3685 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3686
3687 switch (op) {
3688 case glslang::EOpConvIntToBool:
3689 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003690 case glslang::EOpConvInt64ToBool:
3691 case glslang::EOpConvUint64ToBool:
3692 zero = (op == glslang::EOpConvInt64ToBool ||
3693 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003694 zero = makeSmearedConstant(zero, vectorSize);
3695 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3696
3697 case glslang::EOpConvFloatToBool:
3698 zero = builder.makeFloatConstant(0.0F);
3699 zero = makeSmearedConstant(zero, vectorSize);
3700 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3701
3702 case glslang::EOpConvDoubleToBool:
3703 zero = builder.makeDoubleConstant(0.0);
3704 zero = makeSmearedConstant(zero, vectorSize);
3705 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3706
3707 case glslang::EOpConvBoolToFloat:
3708 convOp = spv::OpSelect;
3709 zero = builder.makeFloatConstant(0.0);
3710 one = builder.makeFloatConstant(1.0);
3711 break;
3712 case glslang::EOpConvBoolToDouble:
3713 convOp = spv::OpSelect;
3714 zero = builder.makeDoubleConstant(0.0);
3715 one = builder.makeDoubleConstant(1.0);
3716 break;
3717 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003718 case glslang::EOpConvBoolToInt64:
3719 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3720 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003721 convOp = spv::OpSelect;
3722 break;
3723 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003724 case glslang::EOpConvBoolToUint64:
3725 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3726 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003727 convOp = spv::OpSelect;
3728 break;
3729
3730 case glslang::EOpConvIntToFloat:
3731 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003732 case glslang::EOpConvInt64ToFloat:
3733 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003734 convOp = spv::OpConvertSToF;
3735 break;
3736
3737 case glslang::EOpConvUintToFloat:
3738 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003739 case glslang::EOpConvUint64ToFloat:
3740 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003741 convOp = spv::OpConvertUToF;
3742 break;
3743
3744 case glslang::EOpConvDoubleToFloat:
3745 case glslang::EOpConvFloatToDouble:
3746 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003747 if (builder.isMatrixType(destType))
3748 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750
3751 case glslang::EOpConvFloatToInt:
3752 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003753 case glslang::EOpConvFloatToInt64:
3754 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003755 convOp = spv::OpConvertFToS;
3756 break;
3757
3758 case glslang::EOpConvUintToInt:
3759 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003760 case glslang::EOpConvUint64ToInt64:
3761 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003762 if (builder.isInSpecConstCodeGenMode()) {
3763 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003764 zero = (op == glslang::EOpConvUintToInt64 ||
3765 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003766 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003767 // Use OpIAdd, instead of OpBitcast to do the conversion when
3768 // generating for OpSpecConstantOp instruction.
3769 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3770 }
3771 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003772 convOp = spv::OpBitcast;
3773 break;
3774
3775 case glslang::EOpConvFloatToUint:
3776 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003777 case glslang::EOpConvFloatToUint64:
3778 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003779 convOp = spv::OpConvertFToU;
3780 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003781
3782 case glslang::EOpConvIntToInt64:
3783 case glslang::EOpConvInt64ToInt:
3784 convOp = spv::OpSConvert;
3785 break;
3786
3787 case glslang::EOpConvUintToUint64:
3788 case glslang::EOpConvUint64ToUint:
3789 convOp = spv::OpUConvert;
3790 break;
3791
3792 case glslang::EOpConvIntToUint64:
3793 case glslang::EOpConvInt64ToUint:
3794 case glslang::EOpConvUint64ToInt:
3795 case glslang::EOpConvUintToInt64:
3796 // OpSConvert/OpUConvert + OpBitCast
3797 switch (op) {
3798 case glslang::EOpConvIntToUint64:
3799 convOp = spv::OpSConvert;
3800 type = builder.makeIntType(64);
3801 break;
3802 case glslang::EOpConvInt64ToUint:
3803 convOp = spv::OpSConvert;
3804 type = builder.makeIntType(32);
3805 break;
3806 case glslang::EOpConvUint64ToInt:
3807 convOp = spv::OpUConvert;
3808 type = builder.makeUintType(32);
3809 break;
3810 case glslang::EOpConvUintToInt64:
3811 convOp = spv::OpUConvert;
3812 type = builder.makeUintType(64);
3813 break;
3814 default:
3815 assert(0);
3816 break;
3817 }
3818
3819 if (vectorSize > 0)
3820 type = builder.makeVectorType(type, vectorSize);
3821
3822 operand = builder.createUnaryOp(convOp, type, operand);
3823
3824 if (builder.isInSpecConstCodeGenMode()) {
3825 // Build zero scalar or vector for OpIAdd.
3826 zero = (op == glslang::EOpConvIntToUint64 ||
3827 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3828 zero = makeSmearedConstant(zero, vectorSize);
3829 // Use OpIAdd, instead of OpBitcast to do the conversion when
3830 // generating for OpSpecConstantOp instruction.
3831 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3832 }
3833 // For normal run-time conversion instruction, use OpBitcast.
3834 convOp = spv::OpBitcast;
3835 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003836 default:
3837 break;
3838 }
3839
3840 spv::Id result = 0;
3841 if (convOp == spv::OpNop)
3842 return result;
3843
3844 if (convOp == spv::OpSelect) {
3845 zero = makeSmearedConstant(zero, vectorSize);
3846 one = makeSmearedConstant(one, vectorSize);
3847 result = builder.createTriOp(convOp, destType, operand, one, zero);
3848 } else
3849 result = builder.createUnaryOp(convOp, destType, operand);
3850
John Kessenich32cfd492016-02-02 12:37:46 -07003851 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003852}
3853
3854spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3855{
3856 if (vectorSize == 0)
3857 return constant;
3858
3859 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3860 std::vector<spv::Id> components;
3861 for (int c = 0; c < vectorSize; ++c)
3862 components.push_back(constant);
3863 return builder.makeCompositeConstant(vectorTypeId, components);
3864}
3865
John Kessenich426394d2015-07-23 10:22:48 -06003866// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003867spv::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 -06003868{
3869 spv::Op opCode = spv::OpNop;
3870
3871 switch (op) {
3872 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003873 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003874 opCode = spv::OpAtomicIAdd;
3875 break;
3876 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003877 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003878 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003879 break;
3880 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003881 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003882 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003883 break;
3884 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003885 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003886 opCode = spv::OpAtomicAnd;
3887 break;
3888 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003889 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003890 opCode = spv::OpAtomicOr;
3891 break;
3892 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003893 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003894 opCode = spv::OpAtomicXor;
3895 break;
3896 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003897 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003898 opCode = spv::OpAtomicExchange;
3899 break;
3900 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003901 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003902 opCode = spv::OpAtomicCompareExchange;
3903 break;
3904 case glslang::EOpAtomicCounterIncrement:
3905 opCode = spv::OpAtomicIIncrement;
3906 break;
3907 case glslang::EOpAtomicCounterDecrement:
3908 opCode = spv::OpAtomicIDecrement;
3909 break;
3910 case glslang::EOpAtomicCounter:
3911 opCode = spv::OpAtomicLoad;
3912 break;
3913 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003914 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003915 break;
3916 }
3917
3918 // Sort out the operands
3919 // - mapping from glslang -> SPV
3920 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003921 // - compare-exchange swaps the value and comparator
3922 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003923 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3924 auto opIt = operands.begin(); // walk the glslang operands
3925 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003926 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3927 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3928 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003929 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3930 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003931 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003932 spvAtomicOperands.push_back(*(opIt + 1));
3933 spvAtomicOperands.push_back(*opIt);
3934 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003935 }
John Kessenich426394d2015-07-23 10:22:48 -06003936
John Kessenich3e60a6f2015-09-14 22:45:16 -06003937 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003938 for (; opIt != operands.end(); ++opIt)
3939 spvAtomicOperands.push_back(*opIt);
3940
3941 return builder.createOp(opCode, typeId, spvAtomicOperands);
3942}
3943
John Kessenich91cef522016-05-05 16:45:40 -06003944// Create group invocation operations.
Rex Xu9d93a232016-05-05 12:30:44 +08003945spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003946{
Rex Xu9d93a232016-05-05 12:30:44 +08003947 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3948 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3949
John Kessenich91cef522016-05-05 16:45:40 -06003950 builder.addCapability(spv::CapabilityGroups);
3951
3952 std::vector<spv::Id> operands;
3953 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08003954#ifdef AMD_EXTENSIONS
3955 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
3956 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
3957 operands.push_back(spv::GroupOperationReduce);
3958#endif
John Kessenich91cef522016-05-05 16:45:40 -06003959 operands.push_back(operand);
3960
3961 switch (op) {
3962 case glslang::EOpAnyInvocation:
3963 case glslang::EOpAllInvocations:
3964 return builder.createOp(op == glslang::EOpAnyInvocation ? spv::OpGroupAny : spv::OpGroupAll, typeId, operands);
3965
3966 case glslang::EOpAllInvocationsEqual:
3967 {
3968 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, operands);
3969 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, operands);
3970
3971 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
3972 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
3973 }
Rex Xu9d93a232016-05-05 12:30:44 +08003974#ifdef AMD_EXTENSIONS
3975 case glslang::EOpMinInvocations:
3976 case glslang::EOpMaxInvocations:
3977 case glslang::EOpAddInvocations:
3978 {
3979 spv::Op spvOp = spv::OpNop;
3980 if (op == glslang::EOpMinInvocations) {
3981 if (isFloat)
3982 spvOp = spv::OpGroupFMin;
3983 else {
3984 if (isUnsigned)
3985 spvOp = spv::OpGroupUMin;
3986 else
3987 spvOp = spv::OpGroupSMin;
3988 }
3989 } else if (op == glslang::EOpMaxInvocations) {
3990 if (isFloat)
3991 spvOp = spv::OpGroupFMax;
3992 else {
3993 if (isUnsigned)
3994 spvOp = spv::OpGroupUMax;
3995 else
3996 spvOp = spv::OpGroupSMax;
3997 }
3998 } else {
3999 if (isFloat)
4000 spvOp = spv::OpGroupFAdd;
4001 else
4002 spvOp = spv::OpGroupIAdd;
4003 }
4004
Rex Xu2bbbe062016-08-23 15:41:05 +08004005 if (builder.isVectorType(typeId))
4006 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
4007 else
4008 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08004009 }
4010 case glslang::EOpMinInvocationsNonUniform:
4011 case glslang::EOpMaxInvocationsNonUniform:
4012 case glslang::EOpAddInvocationsNonUniform:
4013 {
4014 spv::Op spvOp = spv::OpNop;
4015 if (op == glslang::EOpMinInvocationsNonUniform) {
4016 if (isFloat)
4017 spvOp = spv::OpGroupFMinNonUniformAMD;
4018 else {
4019 if (isUnsigned)
4020 spvOp = spv::OpGroupUMinNonUniformAMD;
4021 else
4022 spvOp = spv::OpGroupSMinNonUniformAMD;
4023 }
4024 }
4025 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4026 if (isFloat)
4027 spvOp = spv::OpGroupFMaxNonUniformAMD;
4028 else {
4029 if (isUnsigned)
4030 spvOp = spv::OpGroupUMaxNonUniformAMD;
4031 else
4032 spvOp = spv::OpGroupSMaxNonUniformAMD;
4033 }
4034 }
4035 else {
4036 if (isFloat)
4037 spvOp = spv::OpGroupFAddNonUniformAMD;
4038 else
4039 spvOp = spv::OpGroupIAddNonUniformAMD;
4040 }
4041
Rex Xu2bbbe062016-08-23 15:41:05 +08004042 if (builder.isVectorType(typeId))
4043 return CreateInvocationsVectorOperation(spvOp, typeId, operand);
4044 else
4045 return builder.createOp(spvOp, typeId, operands);
Rex Xu9d93a232016-05-05 12:30:44 +08004046 }
4047#endif
John Kessenich91cef522016-05-05 16:45:40 -06004048 default:
4049 logger->missingFunctionality("invocation operation");
4050 return spv::NoResult;
4051 }
4052}
4053
Rex Xu2bbbe062016-08-23 15:41:05 +08004054#ifdef AMD_EXTENSIONS
4055// Create group invocation operations on a vector
4056spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, spv::Id operand)
4057{
4058 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4059 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4060 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd ||
4061 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4062 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4063 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
4064
4065 // Handle group invocation operations scalar by scalar.
4066 // The result type is the same type as the original type.
4067 // The algorithm is to:
4068 // - break the vector into scalars
4069 // - apply the operation to each scalar
4070 // - make a vector out the scalar results
4071
4072 // get the types sorted out
4073 int numComponents = builder.getNumComponents(operand);
4074 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operand));
4075 std::vector<spv::Id> results;
4076
4077 // do each scalar op
4078 for (int comp = 0; comp < numComponents; ++comp) {
4079 std::vector<unsigned int> indexes;
4080 indexes.push_back(comp);
4081 spv::Id scalar = builder.createCompositeExtract(operand, scalarType, indexes);
4082
4083 std::vector<spv::Id> operands;
4084 operands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4085 operands.push_back(spv::GroupOperationReduce);
4086 operands.push_back(scalar);
4087
4088 results.push_back(builder.createOp(op, scalarType, operands));
4089 }
4090
4091 // put the pieces together
4092 return builder.createCompositeConstruct(typeId, results);
4093}
4094#endif
4095
John Kessenich5e4b1242015-08-06 22:53:06 -06004096spv::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 -06004097{
Rex Xu8ff43de2016-04-22 16:51:45 +08004098 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004099 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
4100
John Kessenich140f3df2015-06-26 16:58:36 -06004101 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004102 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004103 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004104 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004105 spv::Id typeId0 = 0;
4106 if (consumedOperands > 0)
4107 typeId0 = builder.getTypeId(operands[0]);
4108 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004109
4110 switch (op) {
4111 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004112 if (isFloat)
4113 libCall = spv::GLSLstd450FMin;
4114 else if (isUnsigned)
4115 libCall = spv::GLSLstd450UMin;
4116 else
4117 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004118 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
4120 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004121 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004122 break;
4123 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004124 if (isFloat)
4125 libCall = spv::GLSLstd450FMax;
4126 else if (isUnsigned)
4127 libCall = spv::GLSLstd450UMax;
4128 else
4129 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004130 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004131 break;
4132 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004133 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004134 break;
4135 case glslang::EOpDot:
4136 opCode = spv::OpDot;
4137 break;
4138 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004139 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141
4142 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004143 if (isFloat)
4144 libCall = spv::GLSLstd450FClamp;
4145 else if (isUnsigned)
4146 libCall = spv::GLSLstd450UClamp;
4147 else
4148 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004149 builder.promoteScalar(precision, operands.front(), operands[1]);
4150 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004151 break;
4152 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004153 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4154 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004155 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004156 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004157 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004158 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004159 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004160 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004161 break;
4162 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004163 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004164 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004165 break;
4166 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004167 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004168 builder.promoteScalar(precision, operands[0], operands[2]);
4169 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004170 break;
4171
4172 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004173 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004174 break;
4175 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004176 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004177 break;
4178 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004179 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004180 break;
4181 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004182 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004183 break;
4184 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004185 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004187 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004188 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004189 libCall = spv::GLSLstd450InterpolateAtSample;
4190 break;
4191 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004192 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004193 libCall = spv::GLSLstd450InterpolateAtOffset;
4194 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004195 case glslang::EOpAddCarry:
4196 opCode = spv::OpIAddCarry;
4197 typeId = builder.makeStructResultType(typeId0, typeId0);
4198 consumedOperands = 2;
4199 break;
4200 case glslang::EOpSubBorrow:
4201 opCode = spv::OpISubBorrow;
4202 typeId = builder.makeStructResultType(typeId0, typeId0);
4203 consumedOperands = 2;
4204 break;
4205 case glslang::EOpUMulExtended:
4206 opCode = spv::OpUMulExtended;
4207 typeId = builder.makeStructResultType(typeId0, typeId0);
4208 consumedOperands = 2;
4209 break;
4210 case glslang::EOpIMulExtended:
4211 opCode = spv::OpSMulExtended;
4212 typeId = builder.makeStructResultType(typeId0, typeId0);
4213 consumedOperands = 2;
4214 break;
4215 case glslang::EOpBitfieldExtract:
4216 if (isUnsigned)
4217 opCode = spv::OpBitFieldUExtract;
4218 else
4219 opCode = spv::OpBitFieldSExtract;
4220 break;
4221 case glslang::EOpBitfieldInsert:
4222 opCode = spv::OpBitFieldInsert;
4223 break;
4224
4225 case glslang::EOpFma:
4226 libCall = spv::GLSLstd450Fma;
4227 break;
4228 case glslang::EOpFrexp:
4229 libCall = spv::GLSLstd450FrexpStruct;
4230 if (builder.getNumComponents(operands[0]) == 1)
4231 frexpIntType = builder.makeIntegerType(32, true);
4232 else
4233 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4234 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4235 consumedOperands = 1;
4236 break;
4237 case glslang::EOpLdexp:
4238 libCall = spv::GLSLstd450Ldexp;
4239 break;
4240
Rex Xu574ab042016-04-14 16:53:07 +08004241 case glslang::EOpReadInvocation:
John Kessenichc8a56762016-05-05 12:04:22 -06004242 logger->missingFunctionality("shader ballot");
Rex Xu574ab042016-04-14 16:53:07 +08004243 libCall = spv::GLSLstd450Bad;
4244 break;
4245
Rex Xu9d93a232016-05-05 12:30:44 +08004246#ifdef AMD_EXTENSIONS
4247 case glslang::EOpSwizzleInvocations:
4248 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4249 libCall = spv::SwizzleInvocationsAMD;
4250 break;
4251 case glslang::EOpSwizzleInvocationsMasked:
4252 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4253 libCall = spv::SwizzleInvocationsMaskedAMD;
4254 break;
4255 case glslang::EOpWriteInvocation:
4256 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4257 libCall = spv::WriteInvocationAMD;
4258 break;
4259
4260 case glslang::EOpMin3:
4261 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4262 if (isFloat)
4263 libCall = spv::FMin3AMD;
4264 else {
4265 if (isUnsigned)
4266 libCall = spv::UMin3AMD;
4267 else
4268 libCall = spv::SMin3AMD;
4269 }
4270 break;
4271 case glslang::EOpMax3:
4272 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4273 if (isFloat)
4274 libCall = spv::FMax3AMD;
4275 else {
4276 if (isUnsigned)
4277 libCall = spv::UMax3AMD;
4278 else
4279 libCall = spv::SMax3AMD;
4280 }
4281 break;
4282 case glslang::EOpMid3:
4283 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4284 if (isFloat)
4285 libCall = spv::FMid3AMD;
4286 else {
4287 if (isUnsigned)
4288 libCall = spv::UMid3AMD;
4289 else
4290 libCall = spv::SMid3AMD;
4291 }
4292 break;
4293
4294 case glslang::EOpInterpolateAtVertex:
4295 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4296 libCall = spv::InterpolateAtVertexAMD;
4297 break;
4298#endif
4299
John Kessenich140f3df2015-06-26 16:58:36 -06004300 default:
4301 return 0;
4302 }
4303
4304 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004305 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004306 // Use an extended instruction from the standard library.
4307 // Construct the call arguments, without modifying the original operands vector.
4308 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4309 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004310 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004311 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004312 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004313 case 0:
4314 // should all be handled by visitAggregate and createNoArgOperation
4315 assert(0);
4316 return 0;
4317 case 1:
4318 // should all be handled by createUnaryOperation
4319 assert(0);
4320 return 0;
4321 case 2:
4322 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4323 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004324 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004325 // anything 3 or over doesn't have l-value operands, so all should be consumed
4326 assert(consumedOperands == operands.size());
4327 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004328 break;
4329 }
4330 }
4331
John Kessenich55e7d112015-11-15 21:33:39 -07004332 // Decode the return types that were structures
4333 switch (op) {
4334 case glslang::EOpAddCarry:
4335 case glslang::EOpSubBorrow:
4336 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4337 id = builder.createCompositeExtract(id, typeId0, 0);
4338 break;
4339 case glslang::EOpUMulExtended:
4340 case glslang::EOpIMulExtended:
4341 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4342 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4343 break;
4344 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004345 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004346 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4347 id = builder.createCompositeExtract(id, typeId0, 0);
4348 break;
4349 default:
4350 break;
4351 }
4352
John Kessenich32cfd492016-02-02 12:37:46 -07004353 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004354}
4355
Rex Xu9d93a232016-05-05 12:30:44 +08004356// Intrinsics with no arguments (or no return value, and no precision).
4357spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004358{
4359 // TODO: get the barrier operands correct
4360
4361 switch (op) {
4362 case glslang::EOpEmitVertex:
4363 builder.createNoResultOp(spv::OpEmitVertex);
4364 return 0;
4365 case glslang::EOpEndPrimitive:
4366 builder.createNoResultOp(spv::OpEndPrimitive);
4367 return 0;
4368 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004369 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004370 return 0;
4371 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004372 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004373 return 0;
4374 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004375 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004376 return 0;
4377 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004378 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004379 return 0;
4380 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004381 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004382 return 0;
4383 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004384 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004385 return 0;
4386 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004387 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004388 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004389 case glslang::EOpAllMemoryBarrierWithGroupSync:
4390 // Control barrier with non-"None" semantic is also a memory barrier.
4391 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4392 return 0;
4393 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4394 // Control barrier with non-"None" semantic is also a memory barrier.
4395 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4396 return 0;
4397 case glslang::EOpWorkgroupMemoryBarrier:
4398 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4399 return 0;
4400 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4401 // Control barrier with non-"None" semantic is also a memory barrier.
4402 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4403 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004404#ifdef AMD_EXTENSIONS
4405 case glslang::EOpTime:
4406 {
4407 std::vector<spv::Id> args; // Dummy arguments
4408 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4409 return builder.setPrecision(id, precision);
4410 }
4411#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004412 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004413 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004414 return 0;
4415 }
4416}
4417
4418spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4419{
John Kessenich2f273362015-07-18 22:34:27 -06004420 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004421 spv::Id id;
4422 if (symbolValues.end() != iter) {
4423 id = iter->second;
4424 return id;
4425 }
4426
4427 // it was not found, create it
4428 id = createSpvVariable(symbol);
4429 symbolValues[symbol->getId()] = id;
4430
Rex Xuc884b4a2016-06-29 15:03:44 +08004431 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004432 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004433 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004434 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004435 if (symbol->getType().getQualifier().hasSpecConstantId())
4436 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004437 if (symbol->getQualifier().hasIndex())
4438 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4439 if (symbol->getQualifier().hasComponent())
4440 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4441 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004442 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004443 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004444 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004445 if (symbol->getQualifier().hasXfbBuffer())
4446 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4447 if (symbol->getQualifier().hasXfbOffset())
4448 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4449 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004450 // atomic counters use this:
4451 if (symbol->getQualifier().hasOffset())
4452 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004453 }
4454
scygan2c864272016-05-18 18:09:17 +02004455 if (symbol->getQualifier().hasLocation())
4456 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004457 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004458 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004459 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004460 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004461 }
John Kessenich140f3df2015-06-26 16:58:36 -06004462 if (symbol->getQualifier().hasSet())
4463 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004464 else if (IsDescriptorResource(symbol->getType())) {
4465 // default to 0
4466 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4467 }
John Kessenich140f3df2015-06-26 16:58:36 -06004468 if (symbol->getQualifier().hasBinding())
4469 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004470 if (symbol->getQualifier().hasAttachment())
4471 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004472 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004473 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004474 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004476 if (symbol->getQualifier().hasXfbBuffer())
4477 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4478 }
4479
Rex Xu1da878f2016-02-21 20:59:01 +08004480 if (symbol->getType().isImage()) {
4481 std::vector<spv::Decoration> memory;
4482 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4483 for (unsigned int i = 0; i < memory.size(); ++i)
4484 addDecoration(id, memory[i]);
4485 }
4486
John Kessenich140f3df2015-06-26 16:58:36 -06004487 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004488 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004489 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004490 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004491
John Kessenich140f3df2015-06-26 16:58:36 -06004492 return id;
4493}
4494
John Kessenich55e7d112015-11-15 21:33:39 -07004495// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004496void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4497{
John Kessenich4016e382016-07-15 11:53:56 -06004498 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004499 builder.addDecoration(id, dec);
4500}
4501
John Kessenich55e7d112015-11-15 21:33:39 -07004502// If 'dec' is valid, add a one-operand decoration to an object
4503void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4504{
John Kessenich4016e382016-07-15 11:53:56 -06004505 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004506 builder.addDecoration(id, dec, value);
4507}
4508
4509// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004510void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4511{
John Kessenich4016e382016-07-15 11:53:56 -06004512 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004513 builder.addMemberDecoration(id, (unsigned)member, dec);
4514}
4515
John Kessenich92187592016-02-01 13:45:25 -07004516// If 'dec' is valid, add a one-operand decoration to a struct member
4517void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4518{
John Kessenich4016e382016-07-15 11:53:56 -06004519 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004520 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4521}
4522
John Kessenich55e7d112015-11-15 21:33:39 -07004523// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004524// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004525//
4526// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4527//
4528// Recursively walk the nodes. The nodes form a tree whose leaves are
4529// regular constants, which themselves are trees that createSpvConstant()
4530// recursively walks. So, this function walks the "top" of the tree:
4531// - emit specialization constant-building instructions for specConstant
4532// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004533spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004534{
John Kessenich7cc0e282016-03-20 00:46:02 -06004535 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004536
qining4f4bb812016-04-03 23:55:17 -04004537 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004538 if (! node.getQualifier().specConstant) {
4539 // hand off to the non-spec-constant path
4540 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4541 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004542 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004543 nextConst, false);
4544 }
4545
4546 // We now know we have a specialization constant to build
4547
John Kessenichd94c0032016-05-30 19:29:40 -06004548 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004549 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4550 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4551 std::vector<spv::Id> dimConstId;
4552 for (int dim = 0; dim < 3; ++dim) {
4553 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4554 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4555 if (specConst)
4556 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4557 }
4558 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4559 }
4560
4561 // An AST node labelled as specialization constant should be a symbol node.
4562 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4563 if (auto* sn = node.getAsSymbolNode()) {
4564 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004565 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4566 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4567 // will set the builder into spec constant op instruction generating mode.
4568 sub_tree->traverse(this);
4569 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004570 } else if (auto* const_union_array = &sn->getConstArray()){
4571 int nextConst = 0;
4572 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004573 }
4574 }
qining4f4bb812016-04-03 23:55:17 -04004575
4576 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4577 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004578 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004579 exit(1);
4580 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004581}
4582
John Kessenich140f3df2015-06-26 16:58:36 -06004583// Use 'consts' as the flattened glslang source of scalar constants to recursively
4584// build the aggregate SPIR-V constant.
4585//
4586// If there are not enough elements present in 'consts', 0 will be substituted;
4587// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4588//
qining08408382016-03-21 09:51:37 -04004589spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004590{
4591 // vector of constants for SPIR-V
4592 std::vector<spv::Id> spvConsts;
4593
4594 // Type is used for struct and array constants
4595 spv::Id typeId = convertGlslangToSpvType(glslangType);
4596
4597 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004598 glslang::TType elementType(glslangType, 0);
4599 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004600 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004601 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004602 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004603 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004604 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004605 } else if (glslangType.getStruct()) {
4606 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4607 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004608 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004609 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004610 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4611 bool zero = nextConst >= consts.size();
4612 switch (glslangType.getBasicType()) {
4613 case glslang::EbtInt:
4614 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4615 break;
4616 case glslang::EbtUint:
4617 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4618 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004619 case glslang::EbtInt64:
4620 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4621 break;
4622 case glslang::EbtUint64:
4623 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4624 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004625 case glslang::EbtFloat:
4626 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4627 break;
4628 case glslang::EbtDouble:
4629 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4630 break;
4631 case glslang::EbtBool:
4632 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4633 break;
4634 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004635 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004636 break;
4637 }
4638 ++nextConst;
4639 }
4640 } else {
4641 // we have a non-aggregate (scalar) constant
4642 bool zero = nextConst >= consts.size();
4643 spv::Id scalar = 0;
4644 switch (glslangType.getBasicType()) {
4645 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004646 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004647 break;
4648 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004649 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004650 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004651 case glslang::EbtInt64:
4652 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4653 break;
4654 case glslang::EbtUint64:
4655 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4656 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004657 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004658 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004659 break;
4660 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004661 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004662 break;
4663 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004664 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004665 break;
4666 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004667 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004668 break;
4669 }
4670 ++nextConst;
4671 return scalar;
4672 }
4673
4674 return builder.makeCompositeConstant(typeId, spvConsts);
4675}
4676
John Kessenich7c1aa102015-10-15 13:29:11 -06004677// Return true if the node is a constant or symbol whose reading has no
4678// non-trivial observable cost or effect.
4679bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4680{
4681 // don't know what this is
4682 if (node == nullptr)
4683 return false;
4684
4685 // a constant is safe
4686 if (node->getAsConstantUnion() != nullptr)
4687 return true;
4688
4689 // not a symbol means non-trivial
4690 if (node->getAsSymbolNode() == nullptr)
4691 return false;
4692
4693 // a symbol, depends on what's being read
4694 switch (node->getType().getQualifier().storage) {
4695 case glslang::EvqTemporary:
4696 case glslang::EvqGlobal:
4697 case glslang::EvqIn:
4698 case glslang::EvqInOut:
4699 case glslang::EvqConst:
4700 case glslang::EvqConstReadOnly:
4701 case glslang::EvqUniform:
4702 return true;
4703 default:
4704 return false;
4705 }
qining25262b32016-05-06 17:25:16 -04004706}
John Kessenich7c1aa102015-10-15 13:29:11 -06004707
4708// A node is trivial if it is a single operation with no side effects.
4709// Error on the side of saying non-trivial.
4710// Return true if trivial.
4711bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4712{
4713 if (node == nullptr)
4714 return false;
4715
4716 // symbols and constants are trivial
4717 if (isTrivialLeaf(node))
4718 return true;
4719
4720 // otherwise, it needs to be a simple operation or one or two leaf nodes
4721
4722 // not a simple operation
4723 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4724 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4725 if (binaryNode == nullptr && unaryNode == nullptr)
4726 return false;
4727
4728 // not on leaf nodes
4729 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4730 return false;
4731
4732 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4733 return false;
4734 }
4735
4736 switch (node->getAsOperator()->getOp()) {
4737 case glslang::EOpLogicalNot:
4738 case glslang::EOpConvIntToBool:
4739 case glslang::EOpConvUintToBool:
4740 case glslang::EOpConvFloatToBool:
4741 case glslang::EOpConvDoubleToBool:
4742 case glslang::EOpEqual:
4743 case glslang::EOpNotEqual:
4744 case glslang::EOpLessThan:
4745 case glslang::EOpGreaterThan:
4746 case glslang::EOpLessThanEqual:
4747 case glslang::EOpGreaterThanEqual:
4748 case glslang::EOpIndexDirect:
4749 case glslang::EOpIndexDirectStruct:
4750 case glslang::EOpLogicalXor:
4751 case glslang::EOpAny:
4752 case glslang::EOpAll:
4753 return true;
4754 default:
4755 return false;
4756 }
4757}
4758
4759// Emit short-circuiting code, where 'right' is never evaluated unless
4760// the left side is true (for &&) or false (for ||).
4761spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4762{
4763 spv::Id boolTypeId = builder.makeBoolType();
4764
4765 // emit left operand
4766 builder.clearAccessChain();
4767 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004768 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004769
4770 // Operands to accumulate OpPhi operands
4771 std::vector<spv::Id> phiOperands;
4772 // accumulate left operand's phi information
4773 phiOperands.push_back(leftId);
4774 phiOperands.push_back(builder.getBuildPoint()->getId());
4775
4776 // Make the two kinds of operation symmetric with a "!"
4777 // || => emit "if (! left) result = right"
4778 // && => emit "if ( left) result = right"
4779 //
4780 // TODO: this runtime "not" for || could be avoided by adding functionality
4781 // to 'builder' to have an "else" without an "then"
4782 if (op == glslang::EOpLogicalOr)
4783 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4784
4785 // make an "if" based on the left value
4786 spv::Builder::If ifBuilder(leftId, builder);
4787
4788 // emit right operand as the "then" part of the "if"
4789 builder.clearAccessChain();
4790 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004791 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004792
4793 // accumulate left operand's phi information
4794 phiOperands.push_back(rightId);
4795 phiOperands.push_back(builder.getBuildPoint()->getId());
4796
4797 // finish the "if"
4798 ifBuilder.makeEndIf();
4799
4800 // phi together the two results
4801 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4802}
4803
Rex Xu9d93a232016-05-05 12:30:44 +08004804// Return type Id of the imported set of extended instructions corresponds to the name.
4805// Import this set if it has not been imported yet.
4806spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4807{
4808 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4809 return extBuiltinMap[name];
4810 else {
4811 builder.addExtensions(name);
4812 spv::Id extBuiltins = builder.import(name);
4813 extBuiltinMap[name] = extBuiltins;
4814 return extBuiltins;
4815 }
4816}
4817
John Kessenich140f3df2015-06-26 16:58:36 -06004818}; // end anonymous namespace
4819
4820namespace glslang {
4821
John Kessenich68d78fd2015-07-12 19:28:10 -06004822void GetSpirvVersion(std::string& version)
4823{
John Kessenich9e55f632015-07-15 10:03:39 -06004824 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004825 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004826 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004827 version = buf;
4828}
4829
John Kessenich140f3df2015-06-26 16:58:36 -06004830// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004831void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004832{
4833 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004834 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004835 for (int i = 0; i < (int)spirv.size(); ++i) {
4836 unsigned int word = spirv[i];
4837 out.write((const char*)&word, 4);
4838 }
4839 out.close();
4840}
4841
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004842// Write SPIR-V out to a text file with 32-bit hexadecimal words
4843void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4844{
4845 std::ofstream out;
4846 out.open(baseName, std::ios::binary | std::ios::out);
4847 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4848 const int WORDS_PER_LINE = 8;
4849 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4850 out << "\t";
4851 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4852 const unsigned int word = spirv[i + j];
4853 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4854 if (i + j + 1 < (int)spirv.size()) {
4855 out << ",";
4856 }
4857 }
4858 out << std::endl;
4859 }
4860 out.close();
4861}
4862
John Kessenich140f3df2015-06-26 16:58:36 -06004863//
4864// Set up the glslang traversal
4865//
4866void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4867{
Lei Zhang17535f72016-05-04 15:55:59 -04004868 spv::SpvBuildLogger logger;
4869 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004870}
4871
Lei Zhang17535f72016-05-04 15:55:59 -04004872void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004873{
John Kessenich140f3df2015-06-26 16:58:36 -06004874 TIntermNode* root = intermediate.getTreeRoot();
4875
4876 if (root == 0)
4877 return;
4878
4879 glslang::GetThreadPoolAllocator().push();
4880
Lei Zhang17535f72016-05-04 15:55:59 -04004881 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004882
4883 root->traverse(&it);
4884
4885 it.dumpSpv(spirv);
4886
4887 glslang::GetThreadPoolAllocator().pop();
4888}
4889
4890}; // end namespace glslang