blob: 9c8b8b932c93a7b786052f4b31b44cb94f809b7f [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 {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060050}
John Kessenich140f3df2015-06-26 16:58:36 -060051
52// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020053#include "../glslang/MachineIndependent/localintermediate.h"
54#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060055#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050056#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060057
John Kessenich140f3df2015-06-26 16:58:36 -060058#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040060#include <list>
61#include <map>
62#include <stack>
63#include <string>
64#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060065
66namespace {
67
John Kessenich55e7d112015-11-15 21:33:39 -070068// For low-order part of the generator's magic number. Bump up
69// when there is a change in the style (e.g., if SSA form changes,
70// or a different instruction sequence to do something gets used).
71const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060072
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
92}
93
John Kessenich140f3df2015-06-26 16:58:36 -060094//
95// The main holder of information for translating glslang to SPIR-V.
96//
97// Derives from the AST walking base class.
98//
99class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
100public:
Lei Zhang17535f72016-05-04 15:55:59 -0400101 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -0600102 virtual ~TGlslangToSpvTraverser();
103
104 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
105 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
106 void visitConstantUnion(glslang::TIntermConstantUnion*);
107 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
108 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
109 void visitSymbol(glslang::TIntermSymbol* symbol);
110 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
111 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
112 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
113
John Kessenich7ba63412015-12-20 17:37:07 -0700114 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600115
116protected:
Rex Xubbceed72016-05-21 09:40:44 +0800117 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100118 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700119 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
121 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600122 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
123 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
124 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700126 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600127 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
128 glslang::TLayoutPacking, const glslang::TQualifier&);
129 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
130 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700131 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700132 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800133 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600134 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700135 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700136 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
137 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
138 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 +0100139 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600140
John Kessenich6fccb3c2016-09-19 16:01:41 -0600141 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 void makeFunctions(const glslang::TIntermSequence&);
143 void makeGlobalInitializers(const glslang::TIntermSequence&);
144 void visitFunctions(const glslang::TIntermSequence&);
145 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800146 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600147 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
148 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600149 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
150
qining25262b32016-05-06 17:25:16 -0400151 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);
152 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
153 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 +0800154 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 +0800155 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 -0600156 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800157 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800158 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xub7072052016-09-26 15:53:40 +0800159 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600160 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800161 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
163 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700164 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600165 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700166 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400167 spv::Id createSpvConstant(const glslang::TIntermTyped&);
168 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600169 bool isTrivialLeaf(const glslang::TIntermTyped* node);
170 bool isTrivial(const glslang::TIntermTyped* node);
171 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800172 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600173
174 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600175 spv::Function* currentFunction;
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;
Rex Xuf3b27472016-07-22 18:15:31 +0800501
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800503 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
504 builder.addCapability(spv::CapabilityDrawParameters);
505 return spv::BuiltInBaseVertex;
506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
517 case glslang::EbvPrimitiveId:
518 if (glslangIntermediate->getStage() == EShLangFragment)
519 builder.addCapability(spv::CapabilityGeometry);
520 return spv::BuiltInPrimitiveId;
521
John Kessenich140f3df2015-06-26 16:58:36 -0600522 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
524 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
525 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
526 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
527 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
528 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
529 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
531 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
532 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
533 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
534 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
535 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
536 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
537 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800538
Rex Xu574ab042016-04-14 16:53:07 +0800539 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800541 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
542 return spv::BuiltInSubgroupSize;
543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupLocalInvocationId;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupEqMaskKHR;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupGeMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGtMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupLeMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLtMaskKHR;
573
Rex Xu9d93a232016-05-05 12:30:44 +0800574#ifdef AMD_EXTENSIONS
575 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
576 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
577 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
578 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
579 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
580 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
581 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
582#endif
John Kessenich4016e382016-07-15 11:53:56 -0600583 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600584 }
585}
586
Rex Xufc618912015-09-09 16:42:49 +0800587// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700588spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800589{
590 assert(type.getBasicType() == glslang::EbtSampler);
591
John Kessenich5d0fa972016-02-15 11:57:00 -0700592 // Check for capabilities
593 switch (type.getQualifier().layoutFormat) {
594 case glslang::ElfRg32f:
595 case glslang::ElfRg16f:
596 case glslang::ElfR11fG11fB10f:
597 case glslang::ElfR16f:
598 case glslang::ElfRgba16:
599 case glslang::ElfRgb10A2:
600 case glslang::ElfRg16:
601 case glslang::ElfRg8:
602 case glslang::ElfR16:
603 case glslang::ElfR8:
604 case glslang::ElfRgba16Snorm:
605 case glslang::ElfRg16Snorm:
606 case glslang::ElfRg8Snorm:
607 case glslang::ElfR16Snorm:
608 case glslang::ElfR8Snorm:
609
610 case glslang::ElfRg32i:
611 case glslang::ElfRg16i:
612 case glslang::ElfRg8i:
613 case glslang::ElfR16i:
614 case glslang::ElfR8i:
615
616 case glslang::ElfRgb10a2ui:
617 case glslang::ElfRg32ui:
618 case glslang::ElfRg16ui:
619 case glslang::ElfRg8ui:
620 case glslang::ElfR16ui:
621 case glslang::ElfR8ui:
622 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
623 break;
624
625 default:
626 break;
627 }
628
629 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800630 switch (type.getQualifier().layoutFormat) {
631 case glslang::ElfNone: return spv::ImageFormatUnknown;
632 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
633 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
634 case glslang::ElfR32f: return spv::ImageFormatR32f;
635 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
636 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
637 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
638 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
639 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
640 case glslang::ElfR16f: return spv::ImageFormatR16f;
641 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
642 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
643 case glslang::ElfRg16: return spv::ImageFormatRg16;
644 case glslang::ElfRg8: return spv::ImageFormatRg8;
645 case glslang::ElfR16: return spv::ImageFormatR16;
646 case glslang::ElfR8: return spv::ImageFormatR8;
647 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
648 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
649 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
650 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
651 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
652 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
653 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
654 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
655 case glslang::ElfR32i: return spv::ImageFormatR32i;
656 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
657 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
658 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
659 case glslang::ElfR16i: return spv::ImageFormatR16i;
660 case glslang::ElfR8i: return spv::ImageFormatR8i;
661 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
662 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
663 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
664 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
665 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
666 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
667 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
668 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
669 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
670 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600671 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800672 }
673}
674
qining25262b32016-05-06 17:25:16 -0400675// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700676// descriptor set.
677bool IsDescriptorResource(const glslang::TType& type)
678{
John Kessenichf7497e22016-03-08 21:36:22 -0700679 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700680 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700681 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700682
683 // non block...
684 // basically samplerXXX/subpass/sampler/texture are all included
685 // if they are the global-scope-class, not the function parameter
686 // (or local, if they ever exist) class.
687 if (type.getBasicType() == glslang::EbtSampler)
688 return type.getQualifier().isUniformOrBuffer();
689
690 // None of the above.
691 return false;
692}
693
John Kesseniche0b6cad2015-12-24 10:30:13 -0700694void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
695{
696 if (child.layoutMatrix == glslang::ElmNone)
697 child.layoutMatrix = parent.layoutMatrix;
698
699 if (parent.invariant)
700 child.invariant = true;
701 if (parent.nopersp)
702 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800703#ifdef AMD_EXTENSIONS
704 if (parent.explicitInterp)
705 child.explicitInterp = true;
706#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700707 if (parent.flat)
708 child.flat = true;
709 if (parent.centroid)
710 child.centroid = true;
711 if (parent.patch)
712 child.patch = true;
713 if (parent.sample)
714 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800715 if (parent.coherent)
716 child.coherent = true;
717 if (parent.volatil)
718 child.volatil = true;
719 if (parent.restrict)
720 child.restrict = true;
721 if (parent.readonly)
722 child.readonly = true;
723 if (parent.writeonly)
724 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700725}
726
John Kessenichf2b7f332016-09-01 17:05:23 -0600727bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700728{
John Kessenich7b9fa252016-01-21 18:56:57 -0700729 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600730 // - struct members might inherit from a struct declaration
731 // (note that non-block structs don't explicitly inherit,
732 // only implicitly, meaning no decoration involved)
733 // - affect decorations on the struct members
734 // (note smooth does not, and expecting something like volatile
735 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700736 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600737 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700738}
739
John Kessenich140f3df2015-06-26 16:58:36 -0600740//
741// Implement the TGlslangToSpvTraverser class.
742//
743
Lei Zhang17535f72016-05-04 15:55:59 -0400744TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600745 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
746 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400747 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600748 inMain(false), mainTerminated(false), linkageOnly(false),
749 glslangIntermediate(glslangIntermediate)
750{
751 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
752
753 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700754 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600755 stdBuiltins = builder.import("GLSL.std.450");
756 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600757 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
758 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600759
760 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600761 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
762 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600763 builder.addSourceExtension(it->c_str());
764
765 // Add the top-level modes for this shader.
766
John Kessenich92187592016-02-01 13:45:25 -0700767 if (glslangIntermediate->getXfbMode()) {
768 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600769 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700770 }
John Kessenich140f3df2015-06-26 16:58:36 -0600771
772 unsigned int mode;
773 switch (glslangIntermediate->getStage()) {
774 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600775 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600776 break;
777
778 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600779 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600780 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
781 break;
782
783 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600784 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600785 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700786 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
787 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
788 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600789 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600790 }
John Kessenich4016e382016-07-15 11:53:56 -0600791 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600792 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
793
John Kesseniche6903322015-10-13 16:29:02 -0600794 switch (glslangIntermediate->getVertexSpacing()) {
795 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
796 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
797 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600798 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600799 }
John Kessenich4016e382016-07-15 11:53:56 -0600800 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600801 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
802
803 switch (glslangIntermediate->getVertexOrder()) {
804 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
805 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600806 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600807 }
John Kessenich4016e382016-07-15 11:53:56 -0600808 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600809 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
810
811 if (glslangIntermediate->getPointMode())
812 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600813 break;
814
815 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600816 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600817 switch (glslangIntermediate->getInputPrimitive()) {
818 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
819 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
820 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700821 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600822 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600823 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600824 }
John Kessenich4016e382016-07-15 11:53:56 -0600825 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600826 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600827
John Kessenich140f3df2015-06-26 16:58:36 -0600828 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
829
830 switch (glslangIntermediate->getOutputPrimitive()) {
831 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
832 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
833 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600834 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600835 }
John Kessenich4016e382016-07-15 11:53:56 -0600836 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600837 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
838 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
839 break;
840
841 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600842 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600843 if (glslangIntermediate->getPixelCenterInteger())
844 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600845
John Kessenich140f3df2015-06-26 16:58:36 -0600846 if (glslangIntermediate->getOriginUpperLeft())
847 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600848 else
849 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600850
851 if (glslangIntermediate->getEarlyFragmentTests())
852 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
853
854 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600855 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
856 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600857 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600858 }
John Kessenich4016e382016-07-15 11:53:56 -0600859 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600860 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
861
862 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
863 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600864 break;
865
866 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600867 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600868 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
869 glslangIntermediate->getLocalSize(1),
870 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600871 break;
872
873 default:
874 break;
875 }
876
877}
878
John Kessenich7ba63412015-12-20 17:37:07 -0700879// Finish everything and dump
880void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
881{
882 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100883 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
884 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700885
qiningda397332016-03-09 19:54:03 -0500886 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700887 builder.dump(out);
888}
889
John Kessenich140f3df2015-06-26 16:58:36 -0600890TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
891{
892 if (! mainTerminated) {
893 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
894 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600895 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600896 }
897}
898
899//
900// Implement the traversal functions.
901//
902// Return true from interior nodes to have the external traversal
903// continue on to children. Return false if children were
904// already processed.
905//
906
907//
qining25262b32016-05-06 17:25:16 -0400908// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600909// - uniform/input reads
910// - output writes
911// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
912// - something simple that degenerates into the last bullet
913//
914void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
915{
qining75d1d802016-04-06 14:42:01 -0400916 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
917 if (symbol->getType().getQualifier().isSpecConstant())
918 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
919
John Kessenich140f3df2015-06-26 16:58:36 -0600920 // getSymbolId() will set up all the IO decorations on the first call.
921 // Formal function parameters were mapped during makeFunctions().
922 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700923
924 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
925 if (builder.isPointer(id)) {
926 spv::StorageClass sc = builder.getStorageClass(id);
927 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
928 iOSet.insert(id);
929 }
930
931 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700932 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600933 // Prepare to generate code for the access
934
935 // L-value chains will be computed left to right. We're on the symbol now,
936 // which is the left-most part of the access chain, so now is "clear" time,
937 // followed by setting the base.
938 builder.clearAccessChain();
939
940 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700941 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600942 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700943 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600944 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700945 // These are also pure R-values.
946 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600947 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600948 builder.setAccessChainRValue(id);
949 else
950 builder.setAccessChainLValue(id);
951 }
952}
953
954bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
955{
qining40887662016-04-03 22:20:42 -0400956 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
957 if (node->getType().getQualifier().isSpecConstant())
958 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
959
John Kessenich140f3df2015-06-26 16:58:36 -0600960 // First, handle special cases
961 switch (node->getOp()) {
962 case glslang::EOpAssign:
963 case glslang::EOpAddAssign:
964 case glslang::EOpSubAssign:
965 case glslang::EOpMulAssign:
966 case glslang::EOpVectorTimesMatrixAssign:
967 case glslang::EOpVectorTimesScalarAssign:
968 case glslang::EOpMatrixTimesScalarAssign:
969 case glslang::EOpMatrixTimesMatrixAssign:
970 case glslang::EOpDivAssign:
971 case glslang::EOpModAssign:
972 case glslang::EOpAndAssign:
973 case glslang::EOpInclusiveOrAssign:
974 case glslang::EOpExclusiveOrAssign:
975 case glslang::EOpLeftShiftAssign:
976 case glslang::EOpRightShiftAssign:
977 // A bin-op assign "a += b" means the same thing as "a = a + b"
978 // where a is evaluated before b. For a simple assignment, GLSL
979 // says to evaluate the left before the right. So, always, left
980 // node then right node.
981 {
982 // get the left l-value, save it away
983 builder.clearAccessChain();
984 node->getLeft()->traverse(this);
985 spv::Builder::AccessChain lValue = builder.getAccessChain();
986
987 // evaluate the right
988 builder.clearAccessChain();
989 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700990 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600991
992 if (node->getOp() != glslang::EOpAssign) {
993 // the left is also an r-value
994 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700995 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600996
997 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600998 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400999 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001000 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1001 node->getType().getBasicType());
1002
1003 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001004 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001005 }
1006
1007 // store the result
1008 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001009 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001010
1011 // assignments are expressions having an rValue after they are evaluated...
1012 builder.clearAccessChain();
1013 builder.setAccessChainRValue(rValue);
1014 }
1015 return false;
1016 case glslang::EOpIndexDirect:
1017 case glslang::EOpIndexDirectStruct:
1018 {
1019 // Get the left part of the access chain.
1020 node->getLeft()->traverse(this);
1021
1022 // Add the next element in the chain
1023
David Netoa901ffe2016-06-08 14:11:40 +01001024 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001025 if (! node->getLeft()->getType().isArray() &&
1026 node->getLeft()->getType().isVector() &&
1027 node->getOp() == glslang::EOpIndexDirect) {
1028 // This is essentially a hard-coded vector swizzle of size 1,
1029 // so short circuit the access-chain stuff with a swizzle.
1030 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001031 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001032 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001033 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001034 int spvIndex = glslangIndex;
1035 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1036 node->getOp() == glslang::EOpIndexDirectStruct)
1037 {
1038 // This may be, e.g., an anonymous block-member selection, which generally need
1039 // index remapping due to hidden members in anonymous blocks.
1040 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1041 assert(remapper.size() > 0);
1042 spvIndex = remapper[glslangIndex];
1043 }
John Kessenichebb50532016-05-16 19:22:05 -06001044
David Netoa901ffe2016-06-08 14:11:40 +01001045 // normal case for indexing array or structure or block
1046 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1047
1048 // Add capabilities here for accessing PointSize and clip/cull distance.
1049 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001050 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001051 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001052 }
1053 }
1054 return false;
1055 case glslang::EOpIndexIndirect:
1056 {
1057 // Structure or array or vector indirection.
1058 // Will use native SPIR-V access-chain for struct and array indirection;
1059 // matrices are arrays of vectors, so will also work for a matrix.
1060 // Will use the access chain's 'component' for variable index into a vector.
1061
1062 // This adapter is building access chains left to right.
1063 // Set up the access chain to the left.
1064 node->getLeft()->traverse(this);
1065
1066 // save it so that computing the right side doesn't trash it
1067 spv::Builder::AccessChain partial = builder.getAccessChain();
1068
1069 // compute the next index in the chain
1070 builder.clearAccessChain();
1071 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001072 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001073
1074 // restore the saved access chain
1075 builder.setAccessChain(partial);
1076
1077 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001078 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001079 else
John Kessenichfa668da2015-09-13 14:46:30 -06001080 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001081 }
1082 return false;
1083 case glslang::EOpVectorSwizzle:
1084 {
1085 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001086 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001087 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001088 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001089 }
1090 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001091 case glslang::EOpLogicalOr:
1092 case glslang::EOpLogicalAnd:
1093 {
1094
1095 // These may require short circuiting, but can sometimes be done as straight
1096 // binary operations. The right operand must be short circuited if it has
1097 // side effects, and should probably be if it is complex.
1098 if (isTrivial(node->getRight()->getAsTyped()))
1099 break; // handle below as a normal binary operation
1100 // otherwise, we need to do dynamic short circuiting on the right operand
1101 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1102 builder.clearAccessChain();
1103 builder.setAccessChainRValue(result);
1104 }
1105 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001106 default:
1107 break;
1108 }
1109
1110 // Assume generic binary op...
1111
John Kessenich32cfd492016-02-02 12:37:46 -07001112 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001113 builder.clearAccessChain();
1114 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001115 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001116
John Kessenich32cfd492016-02-02 12:37:46 -07001117 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001118 builder.clearAccessChain();
1119 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001120 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001121
John Kessenich32cfd492016-02-02 12:37:46 -07001122 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001123 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001124 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001125 convertGlslangToSpvType(node->getType()), left, right,
1126 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001127
John Kessenich50e57562015-12-21 21:21:11 -07001128 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001129 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001130 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001131 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001132 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001133 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001134 return false;
1135 }
John Kessenich140f3df2015-06-26 16:58:36 -06001136}
1137
1138bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1139{
qining40887662016-04-03 22:20:42 -04001140 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1141 if (node->getType().getQualifier().isSpecConstant())
1142 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1143
John Kessenichfc51d282015-08-19 13:34:18 -06001144 spv::Id result = spv::NoResult;
1145
1146 // try texturing first
1147 result = createImageTextureFunctionCall(node);
1148 if (result != spv::NoResult) {
1149 builder.clearAccessChain();
1150 builder.setAccessChainRValue(result);
1151
1152 return false; // done with this node
1153 }
1154
1155 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001156
1157 if (node->getOp() == glslang::EOpArrayLength) {
1158 // Quite special; won't want to evaluate the operand.
1159
1160 // Normal .length() would have been constant folded by the front-end.
1161 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001162 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001163 assert(node->getOperand()->getType().isRuntimeSizedArray());
1164 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1165 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001166 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1167 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001168
1169 builder.clearAccessChain();
1170 builder.setAccessChainRValue(length);
1171
1172 return false;
1173 }
1174
John Kessenichfc51d282015-08-19 13:34:18 -06001175 // Start by evaluating the operand
1176
John Kessenich8c8505c2016-07-26 12:50:38 -06001177 // Does it need a swizzle inversion? If so, evaluation is inverted;
1178 // operate first on the swizzle base, then apply the swizzle.
1179 spv::Id invertedType = spv::NoType;
1180 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1181 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1182 invertedType = getInvertedSwizzleType(*node->getOperand());
1183
John Kessenich140f3df2015-06-26 16:58:36 -06001184 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001185 if (invertedType != spv::NoType)
1186 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1187 else
1188 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001189
Rex Xufc618912015-09-09 16:42:49 +08001190 spv::Id operand = spv::NoResult;
1191
1192 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1193 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001194 node->getOp() == glslang::EOpAtomicCounter ||
1195 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001196 operand = builder.accessChainGetLValue(); // Special case l-value operands
1197 else
John Kessenich32cfd492016-02-02 12:37:46 -07001198 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001199
John Kessenichf6640762016-08-01 19:44:00 -06001200 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001201 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001202
1203 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001204 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001205 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001206
1207 // if not, then possibly an operation
1208 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001209 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001210
1211 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001212 if (invertedType)
1213 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1214
John Kessenich140f3df2015-06-26 16:58:36 -06001215 builder.clearAccessChain();
1216 builder.setAccessChainRValue(result);
1217
1218 return false; // done with this node
1219 }
1220
1221 // it must be a special case, check...
1222 switch (node->getOp()) {
1223 case glslang::EOpPostIncrement:
1224 case glslang::EOpPostDecrement:
1225 case glslang::EOpPreIncrement:
1226 case glslang::EOpPreDecrement:
1227 {
1228 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001229 spv::Id one = 0;
1230 if (node->getBasicType() == glslang::EbtFloat)
1231 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001232 else if (node->getBasicType() == glslang::EbtDouble)
1233 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001234#ifdef AMD_EXTENSIONS
1235 else if (node->getBasicType() == glslang::EbtFloat16)
1236 one = builder.makeFloat16Constant(1.0F);
1237#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001238 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1239 one = builder.makeInt64Constant(1);
1240 else
1241 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001242 glslang::TOperator op;
1243 if (node->getOp() == glslang::EOpPreIncrement ||
1244 node->getOp() == glslang::EOpPostIncrement)
1245 op = glslang::EOpAdd;
1246 else
1247 op = glslang::EOpSub;
1248
John Kessenichf6640762016-08-01 19:44:00 -06001249 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001250 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001251 convertGlslangToSpvType(node->getType()), operand, one,
1252 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001253 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001254
1255 // The result of operation is always stored, but conditionally the
1256 // consumed result. The consumed result is always an r-value.
1257 builder.accessChainStore(result);
1258 builder.clearAccessChain();
1259 if (node->getOp() == glslang::EOpPreIncrement ||
1260 node->getOp() == glslang::EOpPreDecrement)
1261 builder.setAccessChainRValue(result);
1262 else
1263 builder.setAccessChainRValue(operand);
1264 }
1265
1266 return false;
1267
1268 case glslang::EOpEmitStreamVertex:
1269 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1270 return false;
1271 case glslang::EOpEndStreamPrimitive:
1272 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1273 return false;
1274
1275 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001276 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001277 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001278 }
John Kessenich140f3df2015-06-26 16:58:36 -06001279}
1280
1281bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1282{
qining27e04a02016-04-14 16:40:20 -04001283 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1284 if (node->getType().getQualifier().isSpecConstant())
1285 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1286
John Kessenichfc51d282015-08-19 13:34:18 -06001287 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001288 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1289 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001290
1291 // try texturing
1292 result = createImageTextureFunctionCall(node);
1293 if (result != spv::NoResult) {
1294 builder.clearAccessChain();
1295 builder.setAccessChainRValue(result);
1296
1297 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001298 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001299 // "imageStore" is a special case, which has no result
1300 return false;
1301 }
John Kessenichfc51d282015-08-19 13:34:18 -06001302
John Kessenich140f3df2015-06-26 16:58:36 -06001303 glslang::TOperator binOp = glslang::EOpNull;
1304 bool reduceComparison = true;
1305 bool isMatrix = false;
1306 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001307 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001308
1309 assert(node->getOp());
1310
John Kessenichf6640762016-08-01 19:44:00 -06001311 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001312
1313 switch (node->getOp()) {
1314 case glslang::EOpSequence:
1315 {
1316 if (preVisit)
1317 ++sequenceDepth;
1318 else
1319 --sequenceDepth;
1320
1321 if (sequenceDepth == 1) {
1322 // If this is the parent node of all the functions, we want to see them
1323 // early, so all call points have actual SPIR-V functions to reference.
1324 // In all cases, still let the traverser visit the children for us.
1325 makeFunctions(node->getAsAggregate()->getSequence());
1326
John Kessenich6fccb3c2016-09-19 16:01:41 -06001327 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001328 // anything else gets there, so visit out of order, doing them all now.
1329 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1330
1331 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1332 // so do them manually.
1333 visitFunctions(node->getAsAggregate()->getSequence());
1334
1335 return false;
1336 }
1337
1338 return true;
1339 }
1340 case glslang::EOpLinkerObjects:
1341 {
1342 if (visit == glslang::EvPreVisit)
1343 linkageOnly = true;
1344 else
1345 linkageOnly = false;
1346
1347 return true;
1348 }
1349 case glslang::EOpComma:
1350 {
1351 // processing from left to right naturally leaves the right-most
1352 // lying around in the access chain
1353 glslang::TIntermSequence& glslangOperands = node->getSequence();
1354 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1355 glslangOperands[i]->traverse(this);
1356
1357 return false;
1358 }
1359 case glslang::EOpFunction:
1360 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001361 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001362 inMain = true;
1363 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001364 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001365 } else {
1366 handleFunctionEntry(node);
1367 }
1368 } else {
1369 if (inMain)
1370 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001371 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001372 inMain = false;
1373 }
1374
1375 return true;
1376 case glslang::EOpParameters:
1377 // Parameters will have been consumed by EOpFunction processing, but not
1378 // the body, so we still visited the function node's children, making this
1379 // child redundant.
1380 return false;
1381 case glslang::EOpFunctionCall:
1382 {
1383 if (node->isUserDefined())
1384 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001385 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1386 if (result) {
1387 builder.clearAccessChain();
1388 builder.setAccessChainRValue(result);
1389 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001390 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001391
1392 return false;
1393 }
1394 case glslang::EOpConstructMat2x2:
1395 case glslang::EOpConstructMat2x3:
1396 case glslang::EOpConstructMat2x4:
1397 case glslang::EOpConstructMat3x2:
1398 case glslang::EOpConstructMat3x3:
1399 case glslang::EOpConstructMat3x4:
1400 case glslang::EOpConstructMat4x2:
1401 case glslang::EOpConstructMat4x3:
1402 case glslang::EOpConstructMat4x4:
1403 case glslang::EOpConstructDMat2x2:
1404 case glslang::EOpConstructDMat2x3:
1405 case glslang::EOpConstructDMat2x4:
1406 case glslang::EOpConstructDMat3x2:
1407 case glslang::EOpConstructDMat3x3:
1408 case glslang::EOpConstructDMat3x4:
1409 case glslang::EOpConstructDMat4x2:
1410 case glslang::EOpConstructDMat4x3:
1411 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001412#ifdef AMD_EXTENSIONS
1413 case glslang::EOpConstructF16Mat2x2:
1414 case glslang::EOpConstructF16Mat2x3:
1415 case glslang::EOpConstructF16Mat2x4:
1416 case glslang::EOpConstructF16Mat3x2:
1417 case glslang::EOpConstructF16Mat3x3:
1418 case glslang::EOpConstructF16Mat3x4:
1419 case glslang::EOpConstructF16Mat4x2:
1420 case glslang::EOpConstructF16Mat4x3:
1421 case glslang::EOpConstructF16Mat4x4:
1422#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001423 isMatrix = true;
1424 // fall through
1425 case glslang::EOpConstructFloat:
1426 case glslang::EOpConstructVec2:
1427 case glslang::EOpConstructVec3:
1428 case glslang::EOpConstructVec4:
1429 case glslang::EOpConstructDouble:
1430 case glslang::EOpConstructDVec2:
1431 case glslang::EOpConstructDVec3:
1432 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001433#ifdef AMD_EXTENSIONS
1434 case glslang::EOpConstructFloat16:
1435 case glslang::EOpConstructF16Vec2:
1436 case glslang::EOpConstructF16Vec3:
1437 case glslang::EOpConstructF16Vec4:
1438#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001439 case glslang::EOpConstructBool:
1440 case glslang::EOpConstructBVec2:
1441 case glslang::EOpConstructBVec3:
1442 case glslang::EOpConstructBVec4:
1443 case glslang::EOpConstructInt:
1444 case glslang::EOpConstructIVec2:
1445 case glslang::EOpConstructIVec3:
1446 case glslang::EOpConstructIVec4:
1447 case glslang::EOpConstructUint:
1448 case glslang::EOpConstructUVec2:
1449 case glslang::EOpConstructUVec3:
1450 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001451 case glslang::EOpConstructInt64:
1452 case glslang::EOpConstructI64Vec2:
1453 case glslang::EOpConstructI64Vec3:
1454 case glslang::EOpConstructI64Vec4:
1455 case glslang::EOpConstructUint64:
1456 case glslang::EOpConstructU64Vec2:
1457 case glslang::EOpConstructU64Vec3:
1458 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001459 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001460 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001461 {
1462 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001463 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001464 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001465 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001466 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001467 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001468 std::vector<spv::Id> constituents;
1469 for (int c = 0; c < (int)arguments.size(); ++c)
1470 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001471 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001472 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001473 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001474 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001475 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001476
1477 builder.clearAccessChain();
1478 builder.setAccessChainRValue(constructed);
1479
1480 return false;
1481 }
1482
1483 // These six are component-wise compares with component-wise results.
1484 // Forward on to createBinaryOperation(), requesting a vector result.
1485 case glslang::EOpLessThan:
1486 case glslang::EOpGreaterThan:
1487 case glslang::EOpLessThanEqual:
1488 case glslang::EOpGreaterThanEqual:
1489 case glslang::EOpVectorEqual:
1490 case glslang::EOpVectorNotEqual:
1491 {
1492 // Map the operation to a binary
1493 binOp = node->getOp();
1494 reduceComparison = false;
1495 switch (node->getOp()) {
1496 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1497 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1498 default: binOp = node->getOp(); break;
1499 }
1500
1501 break;
1502 }
1503 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001504 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001505 binOp = glslang::EOpMul;
1506 break;
1507 case glslang::EOpOuterProduct:
1508 // two vectors multiplied to make a matrix
1509 binOp = glslang::EOpOuterProduct;
1510 break;
1511 case glslang::EOpDot:
1512 {
qining25262b32016-05-06 17:25:16 -04001513 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001514 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001515 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001516 binOp = glslang::EOpMul;
1517 break;
1518 }
1519 case glslang::EOpMod:
1520 // when an aggregate, this is the floating-point mod built-in function,
1521 // which can be emitted by the one in createBinaryOperation()
1522 binOp = glslang::EOpMod;
1523 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001524 case glslang::EOpEmitVertex:
1525 case glslang::EOpEndPrimitive:
1526 case glslang::EOpBarrier:
1527 case glslang::EOpMemoryBarrier:
1528 case glslang::EOpMemoryBarrierAtomicCounter:
1529 case glslang::EOpMemoryBarrierBuffer:
1530 case glslang::EOpMemoryBarrierImage:
1531 case glslang::EOpMemoryBarrierShared:
1532 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001533 case glslang::EOpAllMemoryBarrierWithGroupSync:
1534 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1535 case glslang::EOpWorkgroupMemoryBarrier:
1536 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001537 noReturnValue = true;
1538 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1539 break;
1540
John Kessenich426394d2015-07-23 10:22:48 -06001541 case glslang::EOpAtomicAdd:
1542 case glslang::EOpAtomicMin:
1543 case glslang::EOpAtomicMax:
1544 case glslang::EOpAtomicAnd:
1545 case glslang::EOpAtomicOr:
1546 case glslang::EOpAtomicXor:
1547 case glslang::EOpAtomicExchange:
1548 case glslang::EOpAtomicCompSwap:
1549 atomic = true;
1550 break;
1551
John Kessenich140f3df2015-06-26 16:58:36 -06001552 default:
1553 break;
1554 }
1555
1556 //
1557 // See if it maps to a regular operation.
1558 //
John Kessenich140f3df2015-06-26 16:58:36 -06001559 if (binOp != glslang::EOpNull) {
1560 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1561 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1562 assert(left && right);
1563
1564 builder.clearAccessChain();
1565 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001566 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001567
1568 builder.clearAccessChain();
1569 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001570 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001571
qining25262b32016-05-06 17:25:16 -04001572 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001573 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001574 left->getType().getBasicType(), reduceComparison);
1575
1576 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001577 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001578 builder.clearAccessChain();
1579 builder.setAccessChainRValue(result);
1580
1581 return false;
1582 }
1583
John Kessenich426394d2015-07-23 10:22:48 -06001584 //
1585 // Create the list of operands.
1586 //
John Kessenich140f3df2015-06-26 16:58:36 -06001587 glslang::TIntermSequence& glslangOperands = node->getSequence();
1588 std::vector<spv::Id> operands;
1589 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001590 // special case l-value operands; there are just a few
1591 bool lvalue = false;
1592 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001593 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001594 case glslang::EOpModf:
1595 if (arg == 1)
1596 lvalue = true;
1597 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001598 case glslang::EOpInterpolateAtSample:
1599 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001600#ifdef AMD_EXTENSIONS
1601 case glslang::EOpInterpolateAtVertex:
1602#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001603 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001604 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001605
1606 // Does it need a swizzle inversion? If so, evaluation is inverted;
1607 // operate first on the swizzle base, then apply the swizzle.
1608 if (glslangOperands[0]->getAsOperator() &&
1609 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1610 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1611 }
Rex Xu7a26c172015-12-08 17:12:09 +08001612 break;
Rex Xud4782c12015-09-06 16:30:11 +08001613 case glslang::EOpAtomicAdd:
1614 case glslang::EOpAtomicMin:
1615 case glslang::EOpAtomicMax:
1616 case glslang::EOpAtomicAnd:
1617 case glslang::EOpAtomicOr:
1618 case glslang::EOpAtomicXor:
1619 case glslang::EOpAtomicExchange:
1620 case glslang::EOpAtomicCompSwap:
1621 if (arg == 0)
1622 lvalue = true;
1623 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001624 case glslang::EOpAddCarry:
1625 case glslang::EOpSubBorrow:
1626 if (arg == 2)
1627 lvalue = true;
1628 break;
1629 case glslang::EOpUMulExtended:
1630 case glslang::EOpIMulExtended:
1631 if (arg >= 2)
1632 lvalue = true;
1633 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001634 default:
1635 break;
1636 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001637 builder.clearAccessChain();
1638 if (invertedType != spv::NoType && arg == 0)
1639 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1640 else
1641 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001642 if (lvalue)
1643 operands.push_back(builder.accessChainGetLValue());
1644 else
John Kessenich32cfd492016-02-02 12:37:46 -07001645 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001646 }
John Kessenich426394d2015-07-23 10:22:48 -06001647
1648 if (atomic) {
1649 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001650 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001651 } else {
1652 // Pass through to generic operations.
1653 switch (glslangOperands.size()) {
1654 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001655 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001656 break;
1657 case 1:
qining25262b32016-05-06 17:25:16 -04001658 result = createUnaryOperation(
1659 node->getOp(), precision,
1660 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001661 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001662 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001663 break;
1664 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001665 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001666 break;
1667 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001668 if (invertedType)
1669 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001670 }
1671
1672 if (noReturnValue)
1673 return false;
1674
1675 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001676 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001677 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001678 } else {
1679 builder.clearAccessChain();
1680 builder.setAccessChainRValue(result);
1681 return false;
1682 }
1683}
1684
1685bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1686{
1687 // This path handles both if-then-else and ?:
1688 // The if-then-else has a node type of void, while
1689 // ?: has a non-void node type
1690 spv::Id result = 0;
1691 if (node->getBasicType() != glslang::EbtVoid) {
1692 // don't handle this as just on-the-fly temporaries, because there will be two names
1693 // and better to leave SSA to later passes
1694 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1695 }
1696
1697 // emit the condition before doing anything with selection
1698 node->getCondition()->traverse(this);
1699
1700 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001701 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001702
1703 if (node->getTrueBlock()) {
1704 // emit the "then" statement
1705 node->getTrueBlock()->traverse(this);
1706 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001707 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001708 }
1709
1710 if (node->getFalseBlock()) {
1711 ifBuilder.makeBeginElse();
1712 // emit the "else" statement
1713 node->getFalseBlock()->traverse(this);
1714 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001715 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001716 }
1717
1718 ifBuilder.makeEndIf();
1719
1720 if (result) {
1721 // GLSL only has r-values as the result of a :?, but
1722 // if we have an l-value, that can be more efficient if it will
1723 // become the base of a complex r-value expression, because the
1724 // next layer copies r-values into memory to use the access-chain mechanism
1725 builder.clearAccessChain();
1726 builder.setAccessChainLValue(result);
1727 }
1728
1729 return false;
1730}
1731
1732bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1733{
1734 // emit and get the condition before doing anything with switch
1735 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001736 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001737
1738 // browse the children to sort out code segments
1739 int defaultSegment = -1;
1740 std::vector<TIntermNode*> codeSegments;
1741 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1742 std::vector<int> caseValues;
1743 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1744 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1745 TIntermNode* child = *c;
1746 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001747 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001748 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001749 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001750 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1751 } else
1752 codeSegments.push_back(child);
1753 }
1754
qining25262b32016-05-06 17:25:16 -04001755 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001756 // statements between the last case and the end of the switch statement
1757 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1758 (int)codeSegments.size() == defaultSegment)
1759 codeSegments.push_back(nullptr);
1760
1761 // make the switch statement
1762 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001763 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001764
1765 // emit all the code in the segments
1766 breakForLoop.push(false);
1767 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1768 builder.nextSwitchSegment(segmentBlocks, s);
1769 if (codeSegments[s])
1770 codeSegments[s]->traverse(this);
1771 else
1772 builder.addSwitchBreak();
1773 }
1774 breakForLoop.pop();
1775
1776 builder.endSwitch(segmentBlocks);
1777
1778 return false;
1779}
1780
1781void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1782{
1783 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001784 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001785
1786 builder.clearAccessChain();
1787 builder.setAccessChainRValue(constant);
1788}
1789
1790bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1791{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001792 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001793 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001794 // Spec requires back edges to target header blocks, and every header block
1795 // must dominate its merge block. Make a header block first to ensure these
1796 // conditions are met. By definition, it will contain OpLoopMerge, followed
1797 // by a block-ending branch. But we don't want to put any other body/test
1798 // instructions in it, since the body/test may have arbitrary instructions,
1799 // including merges of its own.
1800 builder.setBuildPoint(&blocks.head);
1801 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001802 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001803 spv::Block& test = builder.makeNewBlock();
1804 builder.createBranch(&test);
1805
1806 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001807 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001808 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001809 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001810 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1811
1812 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001813 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001814 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001815 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001816 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001817 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001818
1819 builder.setBuildPoint(&blocks.continue_target);
1820 if (node->getTerminal())
1821 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001822 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001823 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001824 builder.createBranch(&blocks.body);
1825
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001826 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001827 builder.setBuildPoint(&blocks.body);
1828 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001829 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001830 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001831 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001832
1833 builder.setBuildPoint(&blocks.continue_target);
1834 if (node->getTerminal())
1835 node->getTerminal()->traverse(this);
1836 if (node->getTest()) {
1837 node->getTest()->traverse(this);
1838 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001839 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001840 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001841 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001842 // TODO: unless there was a break/return/discard instruction
1843 // somewhere in the body, this is an infinite loop, so we should
1844 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001845 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001846 }
John Kessenich140f3df2015-06-26 16:58:36 -06001847 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001848 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001849 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001850 return false;
1851}
1852
1853bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1854{
1855 if (node->getExpression())
1856 node->getExpression()->traverse(this);
1857
1858 switch (node->getFlowOp()) {
1859 case glslang::EOpKill:
1860 builder.makeDiscard();
1861 break;
1862 case glslang::EOpBreak:
1863 if (breakForLoop.top())
1864 builder.createLoopExit();
1865 else
1866 builder.addSwitchBreak();
1867 break;
1868 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001869 builder.createLoopContinue();
1870 break;
1871 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001872 if (node->getExpression()) {
1873 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1874 spv::Id returnId = accessChainLoad(glslangReturnType);
1875 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1876 builder.clearAccessChain();
1877 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1878 builder.setAccessChainLValue(copyId);
1879 multiTypeStore(glslangReturnType, returnId);
1880 returnId = builder.createLoad(copyId);
1881 }
1882 builder.makeReturn(false, returnId);
1883 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06001884 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001885
1886 builder.clearAccessChain();
1887 break;
1888
1889 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001890 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001891 break;
1892 }
1893
1894 return false;
1895}
1896
1897spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1898{
qining25262b32016-05-06 17:25:16 -04001899 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001900 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001901 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001902 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001903 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001904 }
1905
1906 // Now, handle actual variables
1907 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1908 spv::Id spvType = convertGlslangToSpvType(node->getType());
1909
1910 const char* name = node->getName().c_str();
1911 if (glslang::IsAnonymous(name))
1912 name = "";
1913
1914 return builder.createVariable(storageClass, spvType, name);
1915}
1916
1917// Return type Id of the sampled type.
1918spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1919{
1920 switch (sampler.type) {
1921 case glslang::EbtFloat: return builder.makeFloatType(32);
1922 case glslang::EbtInt: return builder.makeIntType(32);
1923 case glslang::EbtUint: return builder.makeUintType(32);
1924 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001925 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001926 return builder.makeFloatType(32);
1927 }
1928}
1929
John Kessenich8c8505c2016-07-26 12:50:38 -06001930// If node is a swizzle operation, return the type that should be used if
1931// the swizzle base is first consumed by another operation, before the swizzle
1932// is applied.
1933spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1934{
1935 if (node.getAsOperator() &&
1936 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1937 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1938 else
1939 return spv::NoType;
1940}
1941
1942// When inverting a swizzle with a parent op, this function
1943// will apply the swizzle operation to a completed parent operation.
1944spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1945{
1946 std::vector<unsigned> swizzle;
1947 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1948 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1949}
1950
John Kessenich8c8505c2016-07-26 12:50:38 -06001951// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1952void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1953{
1954 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1955 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1956 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1957}
1958
John Kessenich3ac051e2015-12-20 11:29:16 -07001959// Convert from a glslang type to an SPV type, by calling into a
1960// recursive version of this function. This establishes the inherited
1961// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001962spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1963{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001964 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001965}
1966
1967// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001968// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001969// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001970spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001971{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001972 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001973
1974 switch (type.getBasicType()) {
1975 case glslang::EbtVoid:
1976 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001977 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001978 break;
1979 case glslang::EbtFloat:
1980 spvType = builder.makeFloatType(32);
1981 break;
1982 case glslang::EbtDouble:
1983 spvType = builder.makeFloatType(64);
1984 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001985#ifdef AMD_EXTENSIONS
1986 case glslang::EbtFloat16:
1987 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
1988 builder.addCapability(spv::CapabilityFloat16);
1989 spvType = builder.makeFloatType(16);
1990 break;
1991#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001992 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001993 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1994 // a 32-bit int where non-0 means true.
1995 if (explicitLayout != glslang::ElpNone)
1996 spvType = builder.makeUintType(32);
1997 else
1998 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001999 break;
2000 case glslang::EbtInt:
2001 spvType = builder.makeIntType(32);
2002 break;
2003 case glslang::EbtUint:
2004 spvType = builder.makeUintType(32);
2005 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002006 case glslang::EbtInt64:
2007 builder.addCapability(spv::CapabilityInt64);
2008 spvType = builder.makeIntType(64);
2009 break;
2010 case glslang::EbtUint64:
2011 builder.addCapability(spv::CapabilityInt64);
2012 spvType = builder.makeUintType(64);
2013 break;
John Kessenich426394d2015-07-23 10:22:48 -06002014 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002015 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002016 spvType = builder.makeUintType(32);
2017 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002018 case glslang::EbtSampler:
2019 {
2020 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002021 if (sampler.sampler) {
2022 // pure sampler
2023 spvType = builder.makeSamplerType();
2024 } else {
2025 // an image is present, make its type
2026 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2027 sampler.image ? 2 : 1, TranslateImageFormat(type));
2028 if (sampler.combined) {
2029 // already has both image and sampler, make the combined type
2030 spvType = builder.makeSampledImageType(spvType);
2031 }
John Kessenich55e7d112015-11-15 21:33:39 -07002032 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002033 }
John Kessenich140f3df2015-06-26 16:58:36 -06002034 break;
2035 case glslang::EbtStruct:
2036 case glslang::EbtBlock:
2037 {
2038 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002039 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002040
2041 // Try to share structs for different layouts, but not yet for other
2042 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002043 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002044 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002045 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002046 break;
2047
2048 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002049 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002050 memberRemapper[glslangMembers].resize(glslangMembers->size());
2051 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002052 }
2053 break;
2054 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002055 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 break;
2057 }
2058
2059 if (type.isMatrix())
2060 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2061 else {
2062 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2063 if (type.getVectorSize() > 1)
2064 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2065 }
2066
2067 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002068 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2069
John Kessenichc9a80832015-09-12 12:17:44 -06002070 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002071 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002072 // We need to decorate array strides for types needing explicit layout, except blocks.
2073 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002074 // Use a dummy glslang type for querying internal strides of
2075 // arrays of arrays, but using just a one-dimensional array.
2076 glslang::TType simpleArrayType(type, 0); // deference type of the array
2077 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2078 simpleArrayType.getArraySizes().dereference();
2079
2080 // Will compute the higher-order strides here, rather than making a whole
2081 // pile of types and doing repetitive recursion on their contents.
2082 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2083 }
John Kessenichf8842e52016-01-04 19:22:56 -07002084
2085 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002086 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002087 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002088 if (stride > 0)
2089 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002090 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002091 }
2092 } else {
2093 // single-dimensional array, and don't yet have stride
2094
John Kessenichf8842e52016-01-04 19:22:56 -07002095 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002096 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2097 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002098 }
John Kessenich31ed4832015-09-09 17:51:38 -06002099
John Kessenichc9a80832015-09-12 12:17:44 -06002100 // Do the outer dimension, which might not be known for a runtime-sized array
2101 if (type.isRuntimeSizedArray()) {
2102 spvType = builder.makeRuntimeArray(spvType);
2103 } else {
2104 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002105 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002106 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002107 if (stride > 0)
2108 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002109 }
2110
2111 return spvType;
2112}
2113
John Kessenich6090df02016-06-30 21:18:02 -06002114
2115// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2116// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2117// Mutually recursive with convertGlslangToSpvType().
2118spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2119 const glslang::TTypeList* glslangMembers,
2120 glslang::TLayoutPacking explicitLayout,
2121 const glslang::TQualifier& qualifier)
2122{
2123 // Create a vector of struct types for SPIR-V to consume
2124 std::vector<spv::Id> spvMembers;
2125 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2126 int locationOffset = 0; // for use across struct members, when they are called recursively
2127 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2128 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2129 if (glslangMember.hiddenMember()) {
2130 ++memberDelta;
2131 if (type.getBasicType() == glslang::EbtBlock)
2132 memberRemapper[glslangMembers][i] = -1;
2133 } else {
2134 if (type.getBasicType() == glslang::EbtBlock)
2135 memberRemapper[glslangMembers][i] = i - memberDelta;
2136 // modify just this child's view of the qualifier
2137 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2138 InheritQualifiers(memberQualifier, qualifier);
2139
2140 // manually inherit location; it's more complex
2141 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2142 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2143 if (qualifier.hasLocation())
2144 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2145
2146 // recurse
2147 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2148 }
2149 }
2150
2151 // Make the SPIR-V type
2152 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002153 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002154 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2155
2156 // Decorate it
2157 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2158
2159 return spvType;
2160}
2161
2162void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2163 const glslang::TTypeList* glslangMembers,
2164 glslang::TLayoutPacking explicitLayout,
2165 const glslang::TQualifier& qualifier,
2166 spv::Id spvType)
2167{
2168 // Name and decorate the non-hidden members
2169 int offset = -1;
2170 int locationOffset = 0; // for use within the members of this struct
2171 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2172 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2173 int member = i;
2174 if (type.getBasicType() == glslang::EbtBlock)
2175 member = memberRemapper[glslangMembers][i];
2176
2177 // modify just this child's view of the qualifier
2178 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2179 InheritQualifiers(memberQualifier, qualifier);
2180
2181 // using -1 above to indicate a hidden member
2182 if (member >= 0) {
2183 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2184 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2185 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2186 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2187 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2188 if (type.getBasicType() == glslang::EbtBlock) {
2189 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2190 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2191 }
2192 }
2193 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2194
2195 if (qualifier.storage == glslang::EvqBuffer) {
2196 std::vector<spv::Decoration> memory;
2197 TranslateMemoryDecoration(memberQualifier, memory);
2198 for (unsigned int i = 0; i < memory.size(); ++i)
2199 addMemberDecoration(spvType, member, memory[i]);
2200 }
2201
John Kessenich2f47bc92016-06-30 21:47:35 -06002202 // Compute location decoration; tricky based on whether inheritance is at play and
2203 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002204 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2205 // probably move to the linker stage of the front end proper, and just have the
2206 // answer sitting already distributed throughout the individual member locations.
2207 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002208 // Ignore member locations if the container is an array, as that's
2209 // ill-specified and decisions have been made to not allow this anyway.
2210 // The object itself must have a location, and that comes out from decorating the object,
2211 // not the type (this code decorates types).
2212 if (! type.isArray()) {
2213 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2214 // struct members should not have explicit locations
2215 assert(type.getBasicType() != glslang::EbtStruct);
2216 location = memberQualifier.layoutLocation;
2217 } else if (type.getBasicType() != glslang::EbtBlock) {
2218 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2219 // The members, and their nested types, must not themselves have Location decorations.
2220 } else if (qualifier.hasLocation()) // inheritance
2221 location = qualifier.layoutLocation + locationOffset;
2222 }
John Kessenich6090df02016-06-30 21:18:02 -06002223 if (location >= 0)
2224 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2225
John Kessenich2f47bc92016-06-30 21:47:35 -06002226 if (qualifier.hasLocation()) // track for upcoming inheritance
2227 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2228
John Kessenich6090df02016-06-30 21:18:02 -06002229 // component, XFB, others
2230 if (glslangMember.getQualifier().hasComponent())
2231 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2232 if (glslangMember.getQualifier().hasXfbOffset())
2233 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2234 else if (explicitLayout != glslang::ElpNone) {
2235 // figure out what to do with offset, which is accumulating
2236 int nextOffset;
2237 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2238 if (offset >= 0)
2239 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2240 offset = nextOffset;
2241 }
2242
2243 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2244 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2245
2246 // built-in variable decorations
2247 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002248 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002249 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2250 }
2251 }
2252
2253 // Decorate the structure
2254 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2255 addDecoration(spvType, TranslateBlockDecoration(type));
2256 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2257 builder.addCapability(spv::CapabilityGeometryStreams);
2258 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2259 }
2260 if (glslangIntermediate->getXfbMode()) {
2261 builder.addCapability(spv::CapabilityTransformFeedback);
2262 if (type.getQualifier().hasXfbStride())
2263 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2264 if (type.getQualifier().hasXfbBuffer())
2265 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2266 }
2267}
2268
John Kessenich6c292d32016-02-15 20:58:50 -07002269// Turn the expression forming the array size into an id.
2270// This is not quite trivial, because of specialization constants.
2271// Sometimes, a raw constant is turned into an Id, and sometimes
2272// a specialization constant expression is.
2273spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2274{
2275 // First, see if this is sized with a node, meaning a specialization constant:
2276 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2277 if (specNode != nullptr) {
2278 builder.clearAccessChain();
2279 specNode->traverse(this);
2280 return accessChainLoad(specNode->getAsTyped()->getType());
2281 }
qining25262b32016-05-06 17:25:16 -04002282
John Kessenich6c292d32016-02-15 20:58:50 -07002283 // Otherwise, need a compile-time (front end) size, get it:
2284 int size = arraySizes.getDimSize(dim);
2285 assert(size > 0);
2286 return builder.makeUintConstant(size);
2287}
2288
John Kessenich103bef92016-02-08 21:38:15 -07002289// Wrap the builder's accessChainLoad to:
2290// - localize handling of RelaxedPrecision
2291// - use the SPIR-V inferred type instead of another conversion of the glslang type
2292// (avoids unnecessary work and possible type punning for structures)
2293// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002294spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2295{
John Kessenich103bef92016-02-08 21:38:15 -07002296 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2297 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2298
2299 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002300 if (type.getBasicType() == glslang::EbtBool) {
2301 if (builder.isScalarType(nominalTypeId)) {
2302 // Conversion for bool
2303 spv::Id boolType = builder.makeBoolType();
2304 if (nominalTypeId != boolType)
2305 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2306 } else if (builder.isVectorType(nominalTypeId)) {
2307 // Conversion for bvec
2308 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2309 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2310 if (nominalTypeId != bvecType)
2311 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2312 }
2313 }
John Kessenich103bef92016-02-08 21:38:15 -07002314
2315 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002316}
2317
Rex Xu27253232016-02-23 17:51:09 +08002318// Wrap the builder's accessChainStore to:
2319// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002320//
2321// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002322void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2323{
2324 // Need to convert to abstract types when necessary
2325 if (type.getBasicType() == glslang::EbtBool) {
2326 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2327
2328 if (builder.isScalarType(nominalTypeId)) {
2329 // Conversion for bool
2330 spv::Id boolType = builder.makeBoolType();
2331 if (nominalTypeId != boolType) {
2332 spv::Id zero = builder.makeUintConstant(0);
2333 spv::Id one = builder.makeUintConstant(1);
2334 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2335 }
2336 } else if (builder.isVectorType(nominalTypeId)) {
2337 // Conversion for bvec
2338 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2339 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2340 if (nominalTypeId != bvecType) {
2341 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2342 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2343 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2344 }
2345 }
2346 }
2347
2348 builder.accessChainStore(rvalue);
2349}
2350
John Kessenich4bf71552016-09-02 11:20:21 -06002351// For storing when types match at the glslang level, but not might match at the
2352// SPIR-V level.
2353//
2354// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002355// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002356// as in a member-decorated way.
2357//
2358// NOTE: This function can handle any store request; if it's not special it
2359// simplifies to a simple OpStore.
2360//
2361// Implicitly uses the existing builder.accessChain as the storage target.
2362void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2363{
John Kessenichb3e24e42016-09-11 12:33:43 -06002364 // we only do the complex path here if it's an aggregate
2365 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002366 accessChainStore(type, rValue);
2367 return;
2368 }
2369
John Kessenichb3e24e42016-09-11 12:33:43 -06002370 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002371 spv::Id rType = builder.getTypeId(rValue);
2372 spv::Id lValue = builder.accessChainGetLValue();
2373 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2374 if (lType == rType) {
2375 accessChainStore(type, rValue);
2376 return;
2377 }
2378
John Kessenichb3e24e42016-09-11 12:33:43 -06002379 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002380 // where the two types were the same type in GLSL. This requires member
2381 // by member copy, recursively.
2382
John Kessenichb3e24e42016-09-11 12:33:43 -06002383 // If an array, copy element by element.
2384 if (type.isArray()) {
2385 glslang::TType glslangElementType(type, 0);
2386 spv::Id elementRType = builder.getContainedTypeId(rType);
2387 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2388 // get the source member
2389 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002390
John Kessenichb3e24e42016-09-11 12:33:43 -06002391 // set up the target storage
2392 builder.clearAccessChain();
2393 builder.setAccessChainLValue(lValue);
2394 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002395
John Kessenichb3e24e42016-09-11 12:33:43 -06002396 // store the member
2397 multiTypeStore(glslangElementType, elementRValue);
2398 }
2399 } else {
2400 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002401
John Kessenichb3e24e42016-09-11 12:33:43 -06002402 // loop over structure members
2403 const glslang::TTypeList& members = *type.getStruct();
2404 for (int m = 0; m < (int)members.size(); ++m) {
2405 const glslang::TType& glslangMemberType = *members[m].type;
2406
2407 // get the source member
2408 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2409 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2410
2411 // set up the target storage
2412 builder.clearAccessChain();
2413 builder.setAccessChainLValue(lValue);
2414 builder.accessChainPush(builder.makeIntConstant(m));
2415
2416 // store the member
2417 multiTypeStore(glslangMemberType, memberRValue);
2418 }
John Kessenich4bf71552016-09-02 11:20:21 -06002419 }
2420}
2421
John Kessenichf85e8062015-12-19 13:57:10 -07002422// Decide whether or not this type should be
2423// decorated with offsets and strides, and if so
2424// whether std140 or std430 rules should be applied.
2425glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002426{
John Kessenichf85e8062015-12-19 13:57:10 -07002427 // has to be a block
2428 if (type.getBasicType() != glslang::EbtBlock)
2429 return glslang::ElpNone;
2430
2431 // has to be a uniform or buffer block
2432 if (type.getQualifier().storage != glslang::EvqUniform &&
2433 type.getQualifier().storage != glslang::EvqBuffer)
2434 return glslang::ElpNone;
2435
2436 // return the layout to use
2437 switch (type.getQualifier().layoutPacking) {
2438 case glslang::ElpStd140:
2439 case glslang::ElpStd430:
2440 return type.getQualifier().layoutPacking;
2441 default:
2442 return glslang::ElpNone;
2443 }
John Kessenich31ed4832015-09-09 17:51:38 -06002444}
2445
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002446// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002447int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002448{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002449 int size;
John Kessenich49987892015-12-29 17:11:44 -07002450 int stride;
2451 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002452
2453 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002454}
2455
John Kessenich49987892015-12-29 17:11:44 -07002456// 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 -07002457// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002458int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002459{
John Kessenich49987892015-12-29 17:11:44 -07002460 glslang::TType elementType;
2461 elementType.shallowCopy(matrixType);
2462 elementType.clearArraySizes();
2463
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002464 int size;
John Kessenich49987892015-12-29 17:11:44 -07002465 int stride;
2466 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2467
2468 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002469}
2470
John Kessenich5e4b1242015-08-06 22:53:06 -06002471// Given a member type of a struct, realign the current offset for it, and compute
2472// the next (not yet aligned) offset for the next member, which will get aligned
2473// on the next call.
2474// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2475// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2476// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002477void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002478 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002479{
2480 // this will get a positive value when deemed necessary
2481 nextOffset = -1;
2482
John Kessenich5e4b1242015-08-06 22:53:06 -06002483 // override anything in currentOffset with user-set offset
2484 if (memberType.getQualifier().hasOffset())
2485 currentOffset = memberType.getQualifier().layoutOffset;
2486
2487 // It could be that current linker usage in glslang updated all the layoutOffset,
2488 // in which case the following code does not matter. But, that's not quite right
2489 // once cross-compilation unit GLSL validation is done, as the original user
2490 // settings are needed in layoutOffset, and then the following will come into play.
2491
John Kessenichf85e8062015-12-19 13:57:10 -07002492 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002493 if (! memberType.getQualifier().hasOffset())
2494 currentOffset = -1;
2495
2496 return;
2497 }
2498
John Kessenichf85e8062015-12-19 13:57:10 -07002499 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002500 if (currentOffset < 0)
2501 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002502
John Kessenich5e4b1242015-08-06 22:53:06 -06002503 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2504 // but possibly not yet correctly aligned.
2505
2506 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002507 int dummyStride;
2508 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002509 glslang::RoundToPow2(currentOffset, memberAlignment);
2510 nextOffset = currentOffset + memberSize;
2511}
2512
David Netoa901ffe2016-06-08 14:11:40 +01002513void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002514{
David Netoa901ffe2016-06-08 14:11:40 +01002515 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2516 switch (glslangBuiltIn)
2517 {
2518 case glslang::EbvClipDistance:
2519 case glslang::EbvCullDistance:
2520 case glslang::EbvPointSize:
2521 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2522 // Alternately, we could just call this for any glslang built-in, since the
2523 // capability already guards against duplicates.
2524 TranslateBuiltInDecoration(glslangBuiltIn, false);
2525 break;
2526 default:
2527 // Capabilities were already generated when the struct was declared.
2528 break;
2529 }
John Kessenichebb50532016-05-16 19:22:05 -06002530}
2531
John Kessenich6fccb3c2016-09-19 16:01:41 -06002532bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002533{
John Kessenicheee9d532016-09-19 18:09:30 -06002534 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002535}
2536
2537// Make all the functions, skeletally, without actually visiting their bodies.
2538void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2539{
2540 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2541 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002542 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002543 continue;
2544
2545 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002546 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002547 //
qining25262b32016-05-06 17:25:16 -04002548 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002549 // function. What it is an address of varies:
2550 //
John Kessenich4bf71552016-09-02 11:20:21 -06002551 // - "in" parameters not marked as "const" can be written to without modifying the calling
2552 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002553 //
2554 // - "const in" parameters can just be the r-value, as no writes need occur.
2555 //
John Kessenich4bf71552016-09-02 11:20:21 -06002556 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2557 // 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 -06002558
2559 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002560 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002561 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2562
2563 for (int p = 0; p < (int)parameters.size(); ++p) {
2564 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2565 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002566 if (paramType.isOpaque())
2567 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2568 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002569 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2570 else
John Kessenich4bf71552016-09-02 11:20:21 -06002571 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002572 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002573 paramTypes.push_back(typeId);
2574 }
2575
2576 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002577 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2578 convertGlslangToSpvType(glslFunction->getType()),
2579 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002580
2581 // Track function to emit/call later
2582 functionMap[glslFunction->getName().c_str()] = function;
2583
2584 // Set the parameter id's
2585 for (int p = 0; p < (int)parameters.size(); ++p) {
2586 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2587 // give a name too
2588 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2589 }
2590 }
2591}
2592
2593// Process all the initializers, while skipping the functions and link objects
2594void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2595{
2596 builder.setBuildPoint(shaderEntry->getLastBlock());
2597 for (int i = 0; i < (int)initializers.size(); ++i) {
2598 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2599 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2600
2601 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002602 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002603 initializer->traverse(this);
2604 }
2605 }
2606}
2607
2608// Process all the functions, while skipping initializers.
2609void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2610{
2611 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2612 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2613 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2614 node->traverse(this);
2615 }
2616}
2617
2618void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2619{
qining25262b32016-05-06 17:25:16 -04002620 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002621 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002622 currentFunction = functionMap[node->getName().c_str()];
2623 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002624 builder.setBuildPoint(functionBlock);
2625}
2626
Rex Xu04db3f52015-09-16 11:44:02 +08002627void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002628{
Rex Xufc618912015-09-09 16:42:49 +08002629 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002630
2631 glslang::TSampler sampler = {};
2632 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002633 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002634 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2635 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2636 }
2637
John Kessenich140f3df2015-06-26 16:58:36 -06002638 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2639 builder.clearAccessChain();
2640 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002641
2642 // Special case l-value operands
2643 bool lvalue = false;
2644 switch (node.getOp()) {
2645 case glslang::EOpImageAtomicAdd:
2646 case glslang::EOpImageAtomicMin:
2647 case glslang::EOpImageAtomicMax:
2648 case glslang::EOpImageAtomicAnd:
2649 case glslang::EOpImageAtomicOr:
2650 case glslang::EOpImageAtomicXor:
2651 case glslang::EOpImageAtomicExchange:
2652 case glslang::EOpImageAtomicCompSwap:
2653 if (i == 0)
2654 lvalue = true;
2655 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002656 case glslang::EOpSparseImageLoad:
2657 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2658 lvalue = true;
2659 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002660 case glslang::EOpSparseTexture:
2661 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2662 lvalue = true;
2663 break;
2664 case glslang::EOpSparseTextureClamp:
2665 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2666 lvalue = true;
2667 break;
2668 case glslang::EOpSparseTextureLod:
2669 case glslang::EOpSparseTextureOffset:
2670 if (i == 3)
2671 lvalue = true;
2672 break;
2673 case glslang::EOpSparseTextureFetch:
2674 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2675 lvalue = true;
2676 break;
2677 case glslang::EOpSparseTextureFetchOffset:
2678 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2679 lvalue = true;
2680 break;
2681 case glslang::EOpSparseTextureLodOffset:
2682 case glslang::EOpSparseTextureGrad:
2683 case glslang::EOpSparseTextureOffsetClamp:
2684 if (i == 4)
2685 lvalue = true;
2686 break;
2687 case glslang::EOpSparseTextureGradOffset:
2688 case glslang::EOpSparseTextureGradClamp:
2689 if (i == 5)
2690 lvalue = true;
2691 break;
2692 case glslang::EOpSparseTextureGradOffsetClamp:
2693 if (i == 6)
2694 lvalue = true;
2695 break;
2696 case glslang::EOpSparseTextureGather:
2697 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2698 lvalue = true;
2699 break;
2700 case glslang::EOpSparseTextureGatherOffset:
2701 case glslang::EOpSparseTextureGatherOffsets:
2702 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2703 lvalue = true;
2704 break;
Rex Xufc618912015-09-09 16:42:49 +08002705 default:
2706 break;
2707 }
2708
Rex Xu6b86d492015-09-16 17:48:22 +08002709 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002710 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002711 else
John Kessenich32cfd492016-02-02 12:37:46 -07002712 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002713 }
2714}
2715
John Kessenichfc51d282015-08-19 13:34:18 -06002716void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002717{
John Kessenichfc51d282015-08-19 13:34:18 -06002718 builder.clearAccessChain();
2719 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002720 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002721}
John Kessenich140f3df2015-06-26 16:58:36 -06002722
John Kessenichfc51d282015-08-19 13:34:18 -06002723spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2724{
Rex Xufc618912015-09-09 16:42:49 +08002725 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002726 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002727 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002728 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002729
John Kessenichfc51d282015-08-19 13:34:18 -06002730 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002731 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2732 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2733 std::vector<spv::Id> arguments;
2734 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002735 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002736 else
2737 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002738 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002739
2740 spv::Builder::TextureParameters params = { };
2741 params.sampler = arguments[0];
2742
Rex Xu04db3f52015-09-16 11:44:02 +08002743 glslang::TCrackedTextureOp cracked;
2744 node->crackTexture(sampler, cracked);
2745
John Kessenichfc51d282015-08-19 13:34:18 -06002746 // Check for queries
2747 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002748 // a sampled image needs to have the image extracted first
2749 if (builder.isSampledImage(params.sampler))
2750 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002751 switch (node->getOp()) {
2752 case glslang::EOpImageQuerySize:
2753 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002754 if (arguments.size() > 1) {
2755 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002756 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002757 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002758 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002759 case glslang::EOpImageQuerySamples:
2760 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002761 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002762 case glslang::EOpTextureQueryLod:
2763 params.coords = arguments[1];
2764 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2765 case glslang::EOpTextureQueryLevels:
2766 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002767 case glslang::EOpSparseTexelsResident:
2768 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002769 default:
2770 assert(0);
2771 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002772 }
John Kessenich140f3df2015-06-26 16:58:36 -06002773 }
2774
Rex Xufc618912015-09-09 16:42:49 +08002775 // Check for image functions other than queries
2776 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002777 std::vector<spv::Id> operands;
2778 auto opIt = arguments.begin();
2779 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002780
2781 // Handle subpass operations
2782 // TODO: GLSL should change to have the "MS" only on the type rather than the
2783 // built-in function.
2784 if (cracked.subpass) {
2785 // add on the (0,0) coordinate
2786 spv::Id zero = builder.makeIntConstant(0);
2787 std::vector<spv::Id> comps;
2788 comps.push_back(zero);
2789 comps.push_back(zero);
2790 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2791 if (sampler.ms) {
2792 operands.push_back(spv::ImageOperandsSampleMask);
2793 operands.push_back(*(opIt++));
2794 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002795 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002796 }
2797
John Kessenich56bab042015-09-16 10:54:31 -06002798 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002799 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002800 if (sampler.ms) {
2801 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002802 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002803 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002804 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2805 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002806 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002807 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002808 if (sampler.ms) {
2809 operands.push_back(*(opIt + 1));
2810 operands.push_back(spv::ImageOperandsSampleMask);
2811 operands.push_back(*opIt);
2812 } else
2813 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002814 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002815 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2816 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002817 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002818 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2819 builder.addCapability(spv::CapabilitySparseResidency);
2820 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2821 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2822
2823 if (sampler.ms) {
2824 operands.push_back(spv::ImageOperandsSampleMask);
2825 operands.push_back(*opIt++);
2826 }
2827
2828 // Create the return type that was a special structure
2829 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002830 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002831 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2832 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2833
2834 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2835
2836 // Decode the return type
2837 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2838 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002839 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002840 // Process image atomic operations
2841
2842 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2843 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002844 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002845
John Kessenich8c8505c2016-07-26 12:50:38 -06002846 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002847 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002848
2849 std::vector<spv::Id> operands;
2850 operands.push_back(pointer);
2851 for (; opIt != arguments.end(); ++opIt)
2852 operands.push_back(*opIt);
2853
John Kessenich8c8505c2016-07-26 12:50:38 -06002854 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002855 }
2856 }
2857
2858 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002859 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002860 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2861
John Kessenichfc51d282015-08-19 13:34:18 -06002862 // check for bias argument
2863 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002864 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002865 int nonBiasArgCount = 2;
2866 if (cracked.offset)
2867 ++nonBiasArgCount;
2868 if (cracked.grad)
2869 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002870 if (cracked.lodClamp)
2871 ++nonBiasArgCount;
2872 if (sparse)
2873 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002874
2875 if ((int)arguments.size() > nonBiasArgCount)
2876 bias = true;
2877 }
2878
John Kessenicha5c33d62016-06-02 23:45:21 -06002879 // See if the sampler param should really be just the SPV image part
2880 if (cracked.fetch) {
2881 // a fetch needs to have the image extracted first
2882 if (builder.isSampledImage(params.sampler))
2883 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2884 }
2885
John Kessenichfc51d282015-08-19 13:34:18 -06002886 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002887
John Kessenichfc51d282015-08-19 13:34:18 -06002888 params.coords = arguments[1];
2889 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002890 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002891
2892 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002893 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002894 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002895 ++extraArgs;
2896 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002897 params.Dref = arguments[2];
2898 ++extraArgs;
2899 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002900 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002901 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002902 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002903 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002904 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002905 dRefComp = builder.getNumComponents(params.coords) - 1;
2906 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002907 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2908 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002909
2910 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002911 if (cracked.lod) {
2912 params.lod = arguments[2];
2913 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002914 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2915 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2916 noImplicitLod = true;
2917 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002918
2919 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002920 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002921 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002922 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002923 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002924
2925 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002926 if (cracked.grad) {
2927 params.gradX = arguments[2 + extraArgs];
2928 params.gradY = arguments[3 + extraArgs];
2929 extraArgs += 2;
2930 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002931
2932 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002933 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002934 params.offset = arguments[2 + extraArgs];
2935 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002936 } else if (cracked.offsets) {
2937 params.offsets = arguments[2 + extraArgs];
2938 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002939 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002940
2941 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002942 if (cracked.lodClamp) {
2943 params.lodClamp = arguments[2 + extraArgs];
2944 ++extraArgs;
2945 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002946
2947 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002948 if (sparse) {
2949 params.texelOut = arguments[2 + extraArgs];
2950 ++extraArgs;
2951 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002952
2953 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002954 if (bias) {
2955 params.bias = arguments[2 + extraArgs];
2956 ++extraArgs;
2957 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002958
2959 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002960 if (cracked.gather && ! sampler.shadow) {
2961 // default component is 0, if missing, otherwise an argument
2962 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002963 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002964 ++extraArgs;
2965 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002966 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002967 }
2968 }
John Kessenichfc51d282015-08-19 13:34:18 -06002969
John Kessenich65336482016-06-16 14:06:26 -06002970 // projective component (might not to move)
2971 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2972 // are divided by the last component of P."
2973 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2974 // unused components will appear after all used components."
2975 if (cracked.proj) {
2976 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2977 int projTargetComp;
2978 switch (sampler.dim) {
2979 case glslang::Esd1D: projTargetComp = 1; break;
2980 case glslang::Esd2D: projTargetComp = 2; break;
2981 case glslang::EsdRect: projTargetComp = 2; break;
2982 default: projTargetComp = projSourceComp; break;
2983 }
2984 // copy the projective coordinate if we have to
2985 if (projTargetComp != projSourceComp) {
2986 spv::Id projComp = builder.createCompositeExtract(params.coords,
2987 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2988 projSourceComp);
2989 params.coords = builder.createCompositeInsert(projComp, params.coords,
2990 builder.getTypeId(params.coords), projTargetComp);
2991 }
2992 }
2993
John Kessenich8c8505c2016-07-26 12:50:38 -06002994 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002995}
2996
2997spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2998{
2999 // Grab the function's pointer from the previously created function
3000 spv::Function* function = functionMap[node->getName().c_str()];
3001 if (! function)
3002 return 0;
3003
3004 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3005 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3006
3007 // See comments in makeFunctions() for details about the semantics for parameter passing.
3008 //
3009 // These imply we need a four step process:
3010 // 1. Evaluate the arguments
3011 // 2. Allocate and make copies of in, out, and inout arguments
3012 // 3. Make the call
3013 // 4. Copy back the results
3014
3015 // 1. Evaluate the arguments
3016 std::vector<spv::Builder::AccessChain> lValues;
3017 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003018 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003019 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003020 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003021 // build l-value
3022 builder.clearAccessChain();
3023 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003024 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003025 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003026 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003027 // save l-value
3028 lValues.push_back(builder.getAccessChain());
3029 } else {
3030 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003031 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003032 }
3033 }
3034
3035 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3036 // copy the original into that space.
3037 //
3038 // Also, build up the list of actual arguments to pass in for the call
3039 int lValueCount = 0;
3040 int rValueCount = 0;
3041 std::vector<spv::Id> spvArgs;
3042 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003043 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003044 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003045 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003046 builder.setAccessChain(lValues[lValueCount]);
3047 arg = builder.accessChainGetLValue();
3048 ++lValueCount;
3049 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003050 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003051 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3052 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3053 // need to copy the input into output space
3054 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003055 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003056 builder.clearAccessChain();
3057 builder.setAccessChainLValue(arg);
3058 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003059 }
3060 ++lValueCount;
3061 } else {
3062 arg = rValues[rValueCount];
3063 ++rValueCount;
3064 }
3065 spvArgs.push_back(arg);
3066 }
3067
3068 // 3. Make the call.
3069 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003070 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003071
3072 // 4. Copy back out an "out" arguments.
3073 lValueCount = 0;
3074 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003075 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003076 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3077 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3078 spv::Id copy = builder.createLoad(spvArgs[a]);
3079 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003080 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003081 }
3082 ++lValueCount;
3083 }
3084 }
3085
3086 return result;
3087}
3088
3089// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003090spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3091 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003092 spv::Id typeId, spv::Id left, spv::Id right,
3093 glslang::TBasicType typeProxy, bool reduceComparison)
3094{
Rex Xu8ff43de2016-04-22 16:51:45 +08003095 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003096#ifdef AMD_EXTENSIONS
3097 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3098#else
John Kessenich140f3df2015-06-26 16:58:36 -06003099 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003100#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003101 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003102
3103 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003104 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003105 bool comparison = false;
3106
3107 switch (op) {
3108 case glslang::EOpAdd:
3109 case glslang::EOpAddAssign:
3110 if (isFloat)
3111 binOp = spv::OpFAdd;
3112 else
3113 binOp = spv::OpIAdd;
3114 break;
3115 case glslang::EOpSub:
3116 case glslang::EOpSubAssign:
3117 if (isFloat)
3118 binOp = spv::OpFSub;
3119 else
3120 binOp = spv::OpISub;
3121 break;
3122 case glslang::EOpMul:
3123 case glslang::EOpMulAssign:
3124 if (isFloat)
3125 binOp = spv::OpFMul;
3126 else
3127 binOp = spv::OpIMul;
3128 break;
3129 case glslang::EOpVectorTimesScalar:
3130 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003131 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003132 if (builder.isVector(right))
3133 std::swap(left, right);
3134 assert(builder.isScalar(right));
3135 needMatchingVectors = false;
3136 binOp = spv::OpVectorTimesScalar;
3137 } else
3138 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003139 break;
3140 case glslang::EOpVectorTimesMatrix:
3141 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003142 binOp = spv::OpVectorTimesMatrix;
3143 break;
3144 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003145 binOp = spv::OpMatrixTimesVector;
3146 break;
3147 case glslang::EOpMatrixTimesScalar:
3148 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003149 binOp = spv::OpMatrixTimesScalar;
3150 break;
3151 case glslang::EOpMatrixTimesMatrix:
3152 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003153 binOp = spv::OpMatrixTimesMatrix;
3154 break;
3155 case glslang::EOpOuterProduct:
3156 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003157 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003158 break;
3159
3160 case glslang::EOpDiv:
3161 case glslang::EOpDivAssign:
3162 if (isFloat)
3163 binOp = spv::OpFDiv;
3164 else if (isUnsigned)
3165 binOp = spv::OpUDiv;
3166 else
3167 binOp = spv::OpSDiv;
3168 break;
3169 case glslang::EOpMod:
3170 case glslang::EOpModAssign:
3171 if (isFloat)
3172 binOp = spv::OpFMod;
3173 else if (isUnsigned)
3174 binOp = spv::OpUMod;
3175 else
3176 binOp = spv::OpSMod;
3177 break;
3178 case glslang::EOpRightShift:
3179 case glslang::EOpRightShiftAssign:
3180 if (isUnsigned)
3181 binOp = spv::OpShiftRightLogical;
3182 else
3183 binOp = spv::OpShiftRightArithmetic;
3184 break;
3185 case glslang::EOpLeftShift:
3186 case glslang::EOpLeftShiftAssign:
3187 binOp = spv::OpShiftLeftLogical;
3188 break;
3189 case glslang::EOpAnd:
3190 case glslang::EOpAndAssign:
3191 binOp = spv::OpBitwiseAnd;
3192 break;
3193 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003194 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003195 binOp = spv::OpLogicalAnd;
3196 break;
3197 case glslang::EOpInclusiveOr:
3198 case glslang::EOpInclusiveOrAssign:
3199 binOp = spv::OpBitwiseOr;
3200 break;
3201 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003202 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 binOp = spv::OpLogicalOr;
3204 break;
3205 case glslang::EOpExclusiveOr:
3206 case glslang::EOpExclusiveOrAssign:
3207 binOp = spv::OpBitwiseXor;
3208 break;
3209 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003210 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003211 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003212 break;
3213
3214 case glslang::EOpLessThan:
3215 case glslang::EOpGreaterThan:
3216 case glslang::EOpLessThanEqual:
3217 case glslang::EOpGreaterThanEqual:
3218 case glslang::EOpEqual:
3219 case glslang::EOpNotEqual:
3220 case glslang::EOpVectorEqual:
3221 case glslang::EOpVectorNotEqual:
3222 comparison = true;
3223 break;
3224 default:
3225 break;
3226 }
3227
John Kessenich7c1aa102015-10-15 13:29:11 -06003228 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003229 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003230 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003231 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003232 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003233
3234 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003235 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003236 builder.promoteScalar(precision, left, right);
3237
qining25262b32016-05-06 17:25:16 -04003238 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3239 addDecoration(result, noContraction);
3240 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003241 }
3242
3243 if (! comparison)
3244 return 0;
3245
John Kessenich7c1aa102015-10-15 13:29:11 -06003246 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003247
John Kessenich4583b612016-08-07 19:14:22 -06003248 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3249 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003250 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003251
3252 switch (op) {
3253 case glslang::EOpLessThan:
3254 if (isFloat)
3255 binOp = spv::OpFOrdLessThan;
3256 else if (isUnsigned)
3257 binOp = spv::OpULessThan;
3258 else
3259 binOp = spv::OpSLessThan;
3260 break;
3261 case glslang::EOpGreaterThan:
3262 if (isFloat)
3263 binOp = spv::OpFOrdGreaterThan;
3264 else if (isUnsigned)
3265 binOp = spv::OpUGreaterThan;
3266 else
3267 binOp = spv::OpSGreaterThan;
3268 break;
3269 case glslang::EOpLessThanEqual:
3270 if (isFloat)
3271 binOp = spv::OpFOrdLessThanEqual;
3272 else if (isUnsigned)
3273 binOp = spv::OpULessThanEqual;
3274 else
3275 binOp = spv::OpSLessThanEqual;
3276 break;
3277 case glslang::EOpGreaterThanEqual:
3278 if (isFloat)
3279 binOp = spv::OpFOrdGreaterThanEqual;
3280 else if (isUnsigned)
3281 binOp = spv::OpUGreaterThanEqual;
3282 else
3283 binOp = spv::OpSGreaterThanEqual;
3284 break;
3285 case glslang::EOpEqual:
3286 case glslang::EOpVectorEqual:
3287 if (isFloat)
3288 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003289 else if (isBool)
3290 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003291 else
3292 binOp = spv::OpIEqual;
3293 break;
3294 case glslang::EOpNotEqual:
3295 case glslang::EOpVectorNotEqual:
3296 if (isFloat)
3297 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003298 else if (isBool)
3299 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003300 else
3301 binOp = spv::OpINotEqual;
3302 break;
3303 default:
3304 break;
3305 }
3306
qining25262b32016-05-06 17:25:16 -04003307 if (binOp != spv::OpNop) {
3308 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3309 addDecoration(result, noContraction);
3310 return builder.setPrecision(result, precision);
3311 }
John Kessenich140f3df2015-06-26 16:58:36 -06003312
3313 return 0;
3314}
3315
John Kessenich04bb8a02015-12-12 12:28:14 -07003316//
3317// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3318// These can be any of:
3319//
3320// matrix * scalar
3321// scalar * matrix
3322// matrix * matrix linear algebraic
3323// matrix * vector
3324// vector * matrix
3325// matrix * matrix componentwise
3326// matrix op matrix op in {+, -, /}
3327// matrix op scalar op in {+, -, /}
3328// scalar op matrix op in {+, -, /}
3329//
qining25262b32016-05-06 17:25:16 -04003330spv::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 -07003331{
3332 bool firstClass = true;
3333
3334 // First, handle first-class matrix operations (* and matrix/scalar)
3335 switch (op) {
3336 case spv::OpFDiv:
3337 if (builder.isMatrix(left) && builder.isScalar(right)) {
3338 // turn matrix / scalar into a multiply...
3339 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3340 op = spv::OpMatrixTimesScalar;
3341 } else
3342 firstClass = false;
3343 break;
3344 case spv::OpMatrixTimesScalar:
3345 if (builder.isMatrix(right))
3346 std::swap(left, right);
3347 assert(builder.isScalar(right));
3348 break;
3349 case spv::OpVectorTimesMatrix:
3350 assert(builder.isVector(left));
3351 assert(builder.isMatrix(right));
3352 break;
3353 case spv::OpMatrixTimesVector:
3354 assert(builder.isMatrix(left));
3355 assert(builder.isVector(right));
3356 break;
3357 case spv::OpMatrixTimesMatrix:
3358 assert(builder.isMatrix(left));
3359 assert(builder.isMatrix(right));
3360 break;
3361 default:
3362 firstClass = false;
3363 break;
3364 }
3365
qining25262b32016-05-06 17:25:16 -04003366 if (firstClass) {
3367 spv::Id result = builder.createBinOp(op, typeId, left, right);
3368 addDecoration(result, noContraction);
3369 return builder.setPrecision(result, precision);
3370 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003371
LoopDawg592860c2016-06-09 08:57:35 -06003372 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003373 // The result type of all of them is the same type as the (a) matrix operand.
3374 // The algorithm is to:
3375 // - break the matrix(es) into vectors
3376 // - smear any scalar to a vector
3377 // - do vector operations
3378 // - make a matrix out the vector results
3379 switch (op) {
3380 case spv::OpFAdd:
3381 case spv::OpFSub:
3382 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003383 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003384 case spv::OpFMul:
3385 {
3386 // one time set up...
3387 bool leftMat = builder.isMatrix(left);
3388 bool rightMat = builder.isMatrix(right);
3389 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3390 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3391 spv::Id scalarType = builder.getScalarTypeId(typeId);
3392 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3393 std::vector<spv::Id> results;
3394 spv::Id smearVec = spv::NoResult;
3395 if (builder.isScalar(left))
3396 smearVec = builder.smearScalar(precision, left, vecType);
3397 else if (builder.isScalar(right))
3398 smearVec = builder.smearScalar(precision, right, vecType);
3399
3400 // do each vector op
3401 for (unsigned int c = 0; c < numCols; ++c) {
3402 std::vector<unsigned int> indexes;
3403 indexes.push_back(c);
3404 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3405 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003406 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3407 addDecoration(result, noContraction);
3408 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003409 }
3410
3411 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003412 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003413 }
3414 default:
3415 assert(0);
3416 return spv::NoResult;
3417 }
3418}
3419
qining25262b32016-05-06 17:25:16 -04003420spv::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 -06003421{
3422 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003423 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003424 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003425 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003426#ifdef AMD_EXTENSIONS
3427 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3428#else
Rex Xu04db3f52015-09-16 11:44:02 +08003429 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003430#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003431
3432 switch (op) {
3433 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003434 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003435 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003436 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003437 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003438 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003439 unaryOp = spv::OpSNegate;
3440 break;
3441
3442 case glslang::EOpLogicalNot:
3443 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003444 unaryOp = spv::OpLogicalNot;
3445 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003446 case glslang::EOpBitwiseNot:
3447 unaryOp = spv::OpNot;
3448 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003449
John Kessenich140f3df2015-06-26 16:58:36 -06003450 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003451 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003452 break;
3453 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003454 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003455 break;
3456 case glslang::EOpTranspose:
3457 unaryOp = spv::OpTranspose;
3458 break;
3459
3460 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003461 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003462 break;
3463 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003464 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003465 break;
3466 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003467 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003468 break;
3469 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003470 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003471 break;
3472 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003473 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003474 break;
3475 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003476 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003477 break;
3478 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003482 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003483 break;
3484
3485 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003486 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003487 break;
3488 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003489 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003490 break;
3491 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003492 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003493 break;
3494 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003495 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003496 break;
3497 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003498 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003501 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 break;
3503
3504 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003505 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003506 break;
3507 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003508 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003509 break;
3510
3511 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003512 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003513 break;
3514 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003515 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003516 break;
3517 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003518 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003519 break;
3520 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003521 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003522 break;
3523 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003524 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003525 break;
3526 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003527 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003528 break;
3529
3530 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003531 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003532 break;
3533 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003534 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003535 break;
3536 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003537 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003538 break;
3539 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003540 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003541 break;
3542 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003543 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003544 break;
3545 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003546 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003547 break;
3548
3549 case glslang::EOpIsNan:
3550 unaryOp = spv::OpIsNan;
3551 break;
3552 case glslang::EOpIsInf:
3553 unaryOp = spv::OpIsInf;
3554 break;
LoopDawg592860c2016-06-09 08:57:35 -06003555 case glslang::EOpIsFinite:
3556 unaryOp = spv::OpIsFinite;
3557 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003558
Rex Xucbc426e2015-12-15 16:03:10 +08003559 case glslang::EOpFloatBitsToInt:
3560 case glslang::EOpFloatBitsToUint:
3561 case glslang::EOpIntBitsToFloat:
3562 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003563 case glslang::EOpDoubleBitsToInt64:
3564 case glslang::EOpDoubleBitsToUint64:
3565 case glslang::EOpInt64BitsToDouble:
3566 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003567 unaryOp = spv::OpBitcast;
3568 break;
3569
John Kessenich140f3df2015-06-26 16:58:36 -06003570 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003571 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003572 break;
3573 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003574 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003575 break;
3576 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003577 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003578 break;
3579 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003580 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003581 break;
3582 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003583 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003584 break;
3585 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003586 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003587 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003588 case glslang::EOpPackSnorm4x8:
3589 libCall = spv::GLSLstd450PackSnorm4x8;
3590 break;
3591 case glslang::EOpUnpackSnorm4x8:
3592 libCall = spv::GLSLstd450UnpackSnorm4x8;
3593 break;
3594 case glslang::EOpPackUnorm4x8:
3595 libCall = spv::GLSLstd450PackUnorm4x8;
3596 break;
3597 case glslang::EOpUnpackUnorm4x8:
3598 libCall = spv::GLSLstd450UnpackUnorm4x8;
3599 break;
3600 case glslang::EOpPackDouble2x32:
3601 libCall = spv::GLSLstd450PackDouble2x32;
3602 break;
3603 case glslang::EOpUnpackDouble2x32:
3604 libCall = spv::GLSLstd450UnpackDouble2x32;
3605 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003606
Rex Xu8ff43de2016-04-22 16:51:45 +08003607 case glslang::EOpPackInt2x32:
3608 case glslang::EOpUnpackInt2x32:
3609 case glslang::EOpPackUint2x32:
3610 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003611 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003612 break;
3613
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003614#ifdef AMD_EXTENSIONS
3615 case glslang::EOpPackFloat2x16:
3616 case glslang::EOpUnpackFloat2x16:
3617 unaryOp = spv::OpBitcast;
3618 break;
3619#endif
3620
John Kessenich140f3df2015-06-26 16:58:36 -06003621 case glslang::EOpDPdx:
3622 unaryOp = spv::OpDPdx;
3623 break;
3624 case glslang::EOpDPdy:
3625 unaryOp = spv::OpDPdy;
3626 break;
3627 case glslang::EOpFwidth:
3628 unaryOp = spv::OpFwidth;
3629 break;
3630 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003631 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003632 unaryOp = spv::OpDPdxFine;
3633 break;
3634 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003635 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003636 unaryOp = spv::OpDPdyFine;
3637 break;
3638 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003639 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003640 unaryOp = spv::OpFwidthFine;
3641 break;
3642 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003643 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003644 unaryOp = spv::OpDPdxCoarse;
3645 break;
3646 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003647 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003648 unaryOp = spv::OpDPdyCoarse;
3649 break;
3650 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003651 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003652 unaryOp = spv::OpFwidthCoarse;
3653 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003654 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003655 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003656 libCall = spv::GLSLstd450InterpolateAtCentroid;
3657 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003658 case glslang::EOpAny:
3659 unaryOp = spv::OpAny;
3660 break;
3661 case glslang::EOpAll:
3662 unaryOp = spv::OpAll;
3663 break;
3664
3665 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003666 if (isFloat)
3667 libCall = spv::GLSLstd450FAbs;
3668 else
3669 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003670 break;
3671 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003672 if (isFloat)
3673 libCall = spv::GLSLstd450FSign;
3674 else
3675 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003676 break;
3677
John Kessenichfc51d282015-08-19 13:34:18 -06003678 case glslang::EOpAtomicCounterIncrement:
3679 case glslang::EOpAtomicCounterDecrement:
3680 case glslang::EOpAtomicCounter:
3681 {
3682 // Handle all of the atomics in one place, in createAtomicOperation()
3683 std::vector<spv::Id> operands;
3684 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003685 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003686 }
3687
John Kessenichfc51d282015-08-19 13:34:18 -06003688 case glslang::EOpBitFieldReverse:
3689 unaryOp = spv::OpBitReverse;
3690 break;
3691 case glslang::EOpBitCount:
3692 unaryOp = spv::OpBitCount;
3693 break;
3694 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003695 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003696 break;
3697 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003698 if (isUnsigned)
3699 libCall = spv::GLSLstd450FindUMsb;
3700 else
3701 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003702 break;
3703
Rex Xu574ab042016-04-14 16:53:07 +08003704 case glslang::EOpBallot:
3705 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003706 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003707 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003708 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003709#ifdef AMD_EXTENSIONS
3710 case glslang::EOpMinInvocations:
3711 case glslang::EOpMaxInvocations:
3712 case glslang::EOpAddInvocations:
3713 case glslang::EOpMinInvocationsNonUniform:
3714 case glslang::EOpMaxInvocationsNonUniform:
3715 case glslang::EOpAddInvocationsNonUniform:
3716#endif
Rex Xu51596642016-09-21 18:56:12 +08003717 {
3718 std::vector<spv::Id> operands;
3719 operands.push_back(operand);
3720 return createInvocationsOperation(op, typeId, operands, typeProxy);
3721 }
Rex Xu9d93a232016-05-05 12:30:44 +08003722
3723#ifdef AMD_EXTENSIONS
3724 case glslang::EOpMbcnt:
3725 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3726 libCall = spv::MbcntAMD;
3727 break;
3728
3729 case glslang::EOpCubeFaceIndex:
3730 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3731 libCall = spv::CubeFaceIndexAMD;
3732 break;
3733
3734 case glslang::EOpCubeFaceCoord:
3735 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3736 libCall = spv::CubeFaceCoordAMD;
3737 break;
3738#endif
Rex Xu338b1852016-05-05 20:38:33 +08003739
John Kessenich140f3df2015-06-26 16:58:36 -06003740 default:
3741 return 0;
3742 }
3743
3744 spv::Id id;
3745 if (libCall >= 0) {
3746 std::vector<spv::Id> args;
3747 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003748 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003749 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003750 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003751 }
John Kessenich140f3df2015-06-26 16:58:36 -06003752
qining25262b32016-05-06 17:25:16 -04003753 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003754 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003755}
3756
John Kessenich7a53f762016-01-20 11:19:27 -07003757// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003758spv::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 -07003759{
3760 // Handle unary operations vector by vector.
3761 // The result type is the same type as the original type.
3762 // The algorithm is to:
3763 // - break the matrix into vectors
3764 // - apply the operation to each vector
3765 // - make a matrix out the vector results
3766
3767 // get the types sorted out
3768 int numCols = builder.getNumColumns(operand);
3769 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003770 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3771 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003772 std::vector<spv::Id> results;
3773
3774 // do each vector op
3775 for (int c = 0; c < numCols; ++c) {
3776 std::vector<unsigned int> indexes;
3777 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003778 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3779 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3780 addDecoration(destVec, noContraction);
3781 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003782 }
3783
3784 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003785 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003786}
3787
Rex Xu73e3ce72016-04-27 18:48:17 +08003788spv::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 -06003789{
3790 spv::Op convOp = spv::OpNop;
3791 spv::Id zero = 0;
3792 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003793 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003794
3795 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3796
3797 switch (op) {
3798 case glslang::EOpConvIntToBool:
3799 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003800 case glslang::EOpConvInt64ToBool:
3801 case glslang::EOpConvUint64ToBool:
3802 zero = (op == glslang::EOpConvInt64ToBool ||
3803 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003804 zero = makeSmearedConstant(zero, vectorSize);
3805 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3806
3807 case glslang::EOpConvFloatToBool:
3808 zero = builder.makeFloatConstant(0.0F);
3809 zero = makeSmearedConstant(zero, vectorSize);
3810 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3811
3812 case glslang::EOpConvDoubleToBool:
3813 zero = builder.makeDoubleConstant(0.0);
3814 zero = makeSmearedConstant(zero, vectorSize);
3815 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3816
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003817#ifdef AMD_EXTENSIONS
3818 case glslang::EOpConvFloat16ToBool:
3819 zero = builder.makeFloat16Constant(0.0F);
3820 zero = makeSmearedConstant(zero, vectorSize);
3821 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3822#endif
3823
John Kessenich140f3df2015-06-26 16:58:36 -06003824 case glslang::EOpConvBoolToFloat:
3825 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003826 zero = builder.makeFloatConstant(0.0F);
3827 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003828 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003829
John Kessenich140f3df2015-06-26 16:58:36 -06003830 case glslang::EOpConvBoolToDouble:
3831 convOp = spv::OpSelect;
3832 zero = builder.makeDoubleConstant(0.0);
3833 one = builder.makeDoubleConstant(1.0);
3834 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003835
3836#ifdef AMD_EXTENSIONS
3837 case glslang::EOpConvBoolToFloat16:
3838 convOp = spv::OpSelect;
3839 zero = builder.makeFloat16Constant(0.0F);
3840 one = builder.makeFloat16Constant(1.0F);
3841 break;
3842#endif
3843
John Kessenich140f3df2015-06-26 16:58:36 -06003844 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003845 case glslang::EOpConvBoolToInt64:
3846 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3847 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003848 convOp = spv::OpSelect;
3849 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003850
John Kessenich140f3df2015-06-26 16:58:36 -06003851 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003852 case glslang::EOpConvBoolToUint64:
3853 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3854 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 convOp = spv::OpSelect;
3856 break;
3857
3858 case glslang::EOpConvIntToFloat:
3859 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003860 case glslang::EOpConvInt64ToFloat:
3861 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003862#ifdef AMD_EXTENSIONS
3863 case glslang::EOpConvIntToFloat16:
3864 case glslang::EOpConvInt64ToFloat16:
3865#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003866 convOp = spv::OpConvertSToF;
3867 break;
3868
3869 case glslang::EOpConvUintToFloat:
3870 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003871 case glslang::EOpConvUint64ToFloat:
3872 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003873#ifdef AMD_EXTENSIONS
3874 case glslang::EOpConvUintToFloat16:
3875 case glslang::EOpConvUint64ToFloat16:
3876#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003877 convOp = spv::OpConvertUToF;
3878 break;
3879
3880 case glslang::EOpConvDoubleToFloat:
3881 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003882#ifdef AMD_EXTENSIONS
3883 case glslang::EOpConvDoubleToFloat16:
3884 case glslang::EOpConvFloat16ToDouble:
3885 case glslang::EOpConvFloatToFloat16:
3886 case glslang::EOpConvFloat16ToFloat:
3887#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003888 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003889 if (builder.isMatrixType(destType))
3890 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003891 break;
3892
3893 case glslang::EOpConvFloatToInt:
3894 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003895 case glslang::EOpConvFloatToInt64:
3896 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003897#ifdef AMD_EXTENSIONS
3898 case glslang::EOpConvFloat16ToInt:
3899 case glslang::EOpConvFloat16ToInt64:
3900#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003901 convOp = spv::OpConvertFToS;
3902 break;
3903
3904 case glslang::EOpConvUintToInt:
3905 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003906 case glslang::EOpConvUint64ToInt64:
3907 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003908 if (builder.isInSpecConstCodeGenMode()) {
3909 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003910 zero = (op == glslang::EOpConvUint64ToInt64 ||
3911 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003912 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003913 // Use OpIAdd, instead of OpBitcast to do the conversion when
3914 // generating for OpSpecConstantOp instruction.
3915 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3916 }
3917 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003918 convOp = spv::OpBitcast;
3919 break;
3920
3921 case glslang::EOpConvFloatToUint:
3922 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003923 case glslang::EOpConvFloatToUint64:
3924 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003925#ifdef AMD_EXTENSIONS
3926 case glslang::EOpConvFloat16ToUint:
3927 case glslang::EOpConvFloat16ToUint64:
3928#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003929 convOp = spv::OpConvertFToU;
3930 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003931
3932 case glslang::EOpConvIntToInt64:
3933 case glslang::EOpConvInt64ToInt:
3934 convOp = spv::OpSConvert;
3935 break;
3936
3937 case glslang::EOpConvUintToUint64:
3938 case glslang::EOpConvUint64ToUint:
3939 convOp = spv::OpUConvert;
3940 break;
3941
3942 case glslang::EOpConvIntToUint64:
3943 case glslang::EOpConvInt64ToUint:
3944 case glslang::EOpConvUint64ToInt:
3945 case glslang::EOpConvUintToInt64:
3946 // OpSConvert/OpUConvert + OpBitCast
3947 switch (op) {
3948 case glslang::EOpConvIntToUint64:
3949 convOp = spv::OpSConvert;
3950 type = builder.makeIntType(64);
3951 break;
3952 case glslang::EOpConvInt64ToUint:
3953 convOp = spv::OpSConvert;
3954 type = builder.makeIntType(32);
3955 break;
3956 case glslang::EOpConvUint64ToInt:
3957 convOp = spv::OpUConvert;
3958 type = builder.makeUintType(32);
3959 break;
3960 case glslang::EOpConvUintToInt64:
3961 convOp = spv::OpUConvert;
3962 type = builder.makeUintType(64);
3963 break;
3964 default:
3965 assert(0);
3966 break;
3967 }
3968
3969 if (vectorSize > 0)
3970 type = builder.makeVectorType(type, vectorSize);
3971
3972 operand = builder.createUnaryOp(convOp, type, operand);
3973
3974 if (builder.isInSpecConstCodeGenMode()) {
3975 // Build zero scalar or vector for OpIAdd.
3976 zero = (op == glslang::EOpConvIntToUint64 ||
3977 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3978 zero = makeSmearedConstant(zero, vectorSize);
3979 // Use OpIAdd, instead of OpBitcast to do the conversion when
3980 // generating for OpSpecConstantOp instruction.
3981 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3982 }
3983 // For normal run-time conversion instruction, use OpBitcast.
3984 convOp = spv::OpBitcast;
3985 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003986 default:
3987 break;
3988 }
3989
3990 spv::Id result = 0;
3991 if (convOp == spv::OpNop)
3992 return result;
3993
3994 if (convOp == spv::OpSelect) {
3995 zero = makeSmearedConstant(zero, vectorSize);
3996 one = makeSmearedConstant(one, vectorSize);
3997 result = builder.createTriOp(convOp, destType, operand, one, zero);
3998 } else
3999 result = builder.createUnaryOp(convOp, destType, operand);
4000
John Kessenich32cfd492016-02-02 12:37:46 -07004001 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004002}
4003
4004spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4005{
4006 if (vectorSize == 0)
4007 return constant;
4008
4009 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4010 std::vector<spv::Id> components;
4011 for (int c = 0; c < vectorSize; ++c)
4012 components.push_back(constant);
4013 return builder.makeCompositeConstant(vectorTypeId, components);
4014}
4015
John Kessenich426394d2015-07-23 10:22:48 -06004016// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004017spv::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 -06004018{
4019 spv::Op opCode = spv::OpNop;
4020
4021 switch (op) {
4022 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004023 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004024 opCode = spv::OpAtomicIAdd;
4025 break;
4026 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004027 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004028 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004029 break;
4030 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004031 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004032 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004033 break;
4034 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004035 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004036 opCode = spv::OpAtomicAnd;
4037 break;
4038 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004039 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004040 opCode = spv::OpAtomicOr;
4041 break;
4042 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004043 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004044 opCode = spv::OpAtomicXor;
4045 break;
4046 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004047 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004048 opCode = spv::OpAtomicExchange;
4049 break;
4050 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004051 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004052 opCode = spv::OpAtomicCompareExchange;
4053 break;
4054 case glslang::EOpAtomicCounterIncrement:
4055 opCode = spv::OpAtomicIIncrement;
4056 break;
4057 case glslang::EOpAtomicCounterDecrement:
4058 opCode = spv::OpAtomicIDecrement;
4059 break;
4060 case glslang::EOpAtomicCounter:
4061 opCode = spv::OpAtomicLoad;
4062 break;
4063 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004064 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004065 break;
4066 }
4067
4068 // Sort out the operands
4069 // - mapping from glslang -> SPV
4070 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004071 // - compare-exchange swaps the value and comparator
4072 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004073 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4074 auto opIt = operands.begin(); // walk the glslang operands
4075 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004076 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4077 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4078 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004079 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4080 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004081 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004082 spvAtomicOperands.push_back(*(opIt + 1));
4083 spvAtomicOperands.push_back(*opIt);
4084 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004085 }
John Kessenich426394d2015-07-23 10:22:48 -06004086
John Kessenich3e60a6f2015-09-14 22:45:16 -06004087 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004088 for (; opIt != operands.end(); ++opIt)
4089 spvAtomicOperands.push_back(*opIt);
4090
4091 return builder.createOp(opCode, typeId, spvAtomicOperands);
4092}
4093
John Kessenich91cef522016-05-05 16:45:40 -06004094// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004095spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004096{
Rex Xu9d93a232016-05-05 12:30:44 +08004097 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004098#ifdef AMD_EXTENSIONS
4099 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4100#else
Rex Xu9d93a232016-05-05 12:30:44 +08004101 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004102#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004103
Rex Xu51596642016-09-21 18:56:12 +08004104 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004105
Rex Xu51596642016-09-21 18:56:12 +08004106 std::vector<spv::Id> spvGroupOperands;
4107 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4108 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4109 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4110 } else {
4111 builder.addCapability(spv::CapabilityGroups);
4112
4113 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004114#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004115 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4116 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4117 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004118#endif
Rex Xu51596642016-09-21 18:56:12 +08004119 }
4120
4121 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4122 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004123
4124 switch (op) {
4125 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004126 opCode = spv::OpGroupAny;
4127 break;
John Kessenich91cef522016-05-05 16:45:40 -06004128 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004129 opCode = spv::OpGroupAll;
4130 break;
John Kessenich91cef522016-05-05 16:45:40 -06004131 case glslang::EOpAllInvocationsEqual:
4132 {
Rex Xu51596642016-09-21 18:56:12 +08004133 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4134 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004135
4136 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4137 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4138 }
Rex Xu51596642016-09-21 18:56:12 +08004139
4140 case glslang::EOpReadInvocation:
4141 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004142 if (builder.isVectorType(typeId))
4143 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004144 break;
4145 case glslang::EOpReadFirstInvocation:
4146 opCode = spv::OpSubgroupFirstInvocationKHR;
4147 break;
4148 case glslang::EOpBallot:
4149 {
4150 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4151 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4152 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4153 //
4154 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4155 //
4156 spv::Id uintType = builder.makeUintType(32);
4157 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4158 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4159
4160 std::vector<spv::Id> components;
4161 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4162 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4163
4164 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4165 return builder.createUnaryOp(spv::OpBitcast, typeId,
4166 builder.createCompositeConstruct(uvec2Type, components));
4167 }
4168
Rex Xu9d93a232016-05-05 12:30:44 +08004169#ifdef AMD_EXTENSIONS
4170 case glslang::EOpMinInvocations:
4171 case glslang::EOpMaxInvocations:
4172 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004173 if (op == glslang::EOpMinInvocations) {
4174 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004175 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004176 else {
4177 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004178 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004179 else
Rex Xu51596642016-09-21 18:56:12 +08004180 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004181 }
4182 } else if (op == glslang::EOpMaxInvocations) {
4183 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004184 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004185 else {
4186 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004187 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004188 else
Rex Xu51596642016-09-21 18:56:12 +08004189 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004190 }
4191 } else {
4192 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004193 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004194 else
Rex Xu51596642016-09-21 18:56:12 +08004195 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004196 }
4197
Rex Xu2bbbe062016-08-23 15:41:05 +08004198 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004199 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004200
4201 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004202 case glslang::EOpMinInvocationsNonUniform:
4203 case glslang::EOpMaxInvocationsNonUniform:
4204 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004205 if (op == glslang::EOpMinInvocationsNonUniform) {
4206 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004207 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004208 else {
4209 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004210 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004211 else
Rex Xu51596642016-09-21 18:56:12 +08004212 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004213 }
4214 }
4215 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4216 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004217 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004218 else {
4219 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004220 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004221 else
Rex Xu51596642016-09-21 18:56:12 +08004222 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004223 }
4224 }
4225 else {
4226 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004227 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004228 else
Rex Xu51596642016-09-21 18:56:12 +08004229 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004230 }
4231
Rex Xu2bbbe062016-08-23 15:41:05 +08004232 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004233 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004234
4235 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004236#endif
John Kessenich91cef522016-05-05 16:45:40 -06004237 default:
4238 logger->missingFunctionality("invocation operation");
4239 return spv::NoResult;
4240 }
Rex Xu51596642016-09-21 18:56:12 +08004241
4242 assert(opCode != spv::OpNop);
4243 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004244}
4245
Rex Xu2bbbe062016-08-23 15:41:05 +08004246// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004247spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004248{
Rex Xub7072052016-09-26 15:53:40 +08004249#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004250 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4251 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004252 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004253 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4254 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4255 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004256#else
4257 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4258 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4259 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4260#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004261
4262 // Handle group invocation operations scalar by scalar.
4263 // The result type is the same type as the original type.
4264 // The algorithm is to:
4265 // - break the vector into scalars
4266 // - apply the operation to each scalar
4267 // - make a vector out the scalar results
4268
4269 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004270 int numComponents = builder.getNumComponents(operands[0]);
4271 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004272 std::vector<spv::Id> results;
4273
4274 // do each scalar op
4275 for (int comp = 0; comp < numComponents; ++comp) {
4276 std::vector<unsigned int> indexes;
4277 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004278 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004279
Rex Xub7072052016-09-26 15:53:40 +08004280 std::vector<spv::Id> spvGroupOperands;
4281 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4282 if (op == spv::OpGroupBroadcast) {
4283 spvGroupOperands.push_back(scalar);
4284 spvGroupOperands.push_back(operands[1]);
4285 } else {
4286 spvGroupOperands.push_back(spv::GroupOperationReduce);
4287 spvGroupOperands.push_back(scalar);
4288 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004289
Rex Xub7072052016-09-26 15:53:40 +08004290 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004291 }
4292
4293 // put the pieces together
4294 return builder.createCompositeConstruct(typeId, results);
4295}
Rex Xu2bbbe062016-08-23 15:41:05 +08004296
John Kessenich5e4b1242015-08-06 22:53:06 -06004297spv::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 -06004298{
Rex Xu8ff43de2016-04-22 16:51:45 +08004299 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004300#ifdef AMD_EXTENSIONS
4301 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4302#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004303 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004304#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004305
John Kessenich140f3df2015-06-26 16:58:36 -06004306 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004307 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004308 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004309 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004310 spv::Id typeId0 = 0;
4311 if (consumedOperands > 0)
4312 typeId0 = builder.getTypeId(operands[0]);
4313 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004314
4315 switch (op) {
4316 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004317 if (isFloat)
4318 libCall = spv::GLSLstd450FMin;
4319 else if (isUnsigned)
4320 libCall = spv::GLSLstd450UMin;
4321 else
4322 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004323 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004324 break;
4325 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004326 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004327 break;
4328 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004329 if (isFloat)
4330 libCall = spv::GLSLstd450FMax;
4331 else if (isUnsigned)
4332 libCall = spv::GLSLstd450UMax;
4333 else
4334 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004335 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004336 break;
4337 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004338 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004339 break;
4340 case glslang::EOpDot:
4341 opCode = spv::OpDot;
4342 break;
4343 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004344 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004345 break;
4346
4347 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004348 if (isFloat)
4349 libCall = spv::GLSLstd450FClamp;
4350 else if (isUnsigned)
4351 libCall = spv::GLSLstd450UClamp;
4352 else
4353 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004354 builder.promoteScalar(precision, operands.front(), operands[1]);
4355 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004356 break;
4357 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004358 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4359 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004360 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004361 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004362 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004363 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004364 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004365 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004366 break;
4367 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004368 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004369 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004370 break;
4371 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004372 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004373 builder.promoteScalar(precision, operands[0], operands[2]);
4374 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004375 break;
4376
4377 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004378 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004379 break;
4380 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004381 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004382 break;
4383 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004384 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004385 break;
4386 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004387 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004388 break;
4389 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004390 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004391 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004392 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004393 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004394 libCall = spv::GLSLstd450InterpolateAtSample;
4395 break;
4396 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004397 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004398 libCall = spv::GLSLstd450InterpolateAtOffset;
4399 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004400 case glslang::EOpAddCarry:
4401 opCode = spv::OpIAddCarry;
4402 typeId = builder.makeStructResultType(typeId0, typeId0);
4403 consumedOperands = 2;
4404 break;
4405 case glslang::EOpSubBorrow:
4406 opCode = spv::OpISubBorrow;
4407 typeId = builder.makeStructResultType(typeId0, typeId0);
4408 consumedOperands = 2;
4409 break;
4410 case glslang::EOpUMulExtended:
4411 opCode = spv::OpUMulExtended;
4412 typeId = builder.makeStructResultType(typeId0, typeId0);
4413 consumedOperands = 2;
4414 break;
4415 case glslang::EOpIMulExtended:
4416 opCode = spv::OpSMulExtended;
4417 typeId = builder.makeStructResultType(typeId0, typeId0);
4418 consumedOperands = 2;
4419 break;
4420 case glslang::EOpBitfieldExtract:
4421 if (isUnsigned)
4422 opCode = spv::OpBitFieldUExtract;
4423 else
4424 opCode = spv::OpBitFieldSExtract;
4425 break;
4426 case glslang::EOpBitfieldInsert:
4427 opCode = spv::OpBitFieldInsert;
4428 break;
4429
4430 case glslang::EOpFma:
4431 libCall = spv::GLSLstd450Fma;
4432 break;
4433 case glslang::EOpFrexp:
4434 libCall = spv::GLSLstd450FrexpStruct;
4435 if (builder.getNumComponents(operands[0]) == 1)
4436 frexpIntType = builder.makeIntegerType(32, true);
4437 else
4438 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4439 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4440 consumedOperands = 1;
4441 break;
4442 case glslang::EOpLdexp:
4443 libCall = spv::GLSLstd450Ldexp;
4444 break;
4445
Rex Xu574ab042016-04-14 16:53:07 +08004446 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004447 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004448
Rex Xu9d93a232016-05-05 12:30:44 +08004449#ifdef AMD_EXTENSIONS
4450 case glslang::EOpSwizzleInvocations:
4451 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4452 libCall = spv::SwizzleInvocationsAMD;
4453 break;
4454 case glslang::EOpSwizzleInvocationsMasked:
4455 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4456 libCall = spv::SwizzleInvocationsMaskedAMD;
4457 break;
4458 case glslang::EOpWriteInvocation:
4459 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4460 libCall = spv::WriteInvocationAMD;
4461 break;
4462
4463 case glslang::EOpMin3:
4464 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4465 if (isFloat)
4466 libCall = spv::FMin3AMD;
4467 else {
4468 if (isUnsigned)
4469 libCall = spv::UMin3AMD;
4470 else
4471 libCall = spv::SMin3AMD;
4472 }
4473 break;
4474 case glslang::EOpMax3:
4475 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4476 if (isFloat)
4477 libCall = spv::FMax3AMD;
4478 else {
4479 if (isUnsigned)
4480 libCall = spv::UMax3AMD;
4481 else
4482 libCall = spv::SMax3AMD;
4483 }
4484 break;
4485 case glslang::EOpMid3:
4486 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4487 if (isFloat)
4488 libCall = spv::FMid3AMD;
4489 else {
4490 if (isUnsigned)
4491 libCall = spv::UMid3AMD;
4492 else
4493 libCall = spv::SMid3AMD;
4494 }
4495 break;
4496
4497 case glslang::EOpInterpolateAtVertex:
4498 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4499 libCall = spv::InterpolateAtVertexAMD;
4500 break;
4501#endif
4502
John Kessenich140f3df2015-06-26 16:58:36 -06004503 default:
4504 return 0;
4505 }
4506
4507 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004508 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004509 // Use an extended instruction from the standard library.
4510 // Construct the call arguments, without modifying the original operands vector.
4511 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4512 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004513 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004514 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004515 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004516 case 0:
4517 // should all be handled by visitAggregate and createNoArgOperation
4518 assert(0);
4519 return 0;
4520 case 1:
4521 // should all be handled by createUnaryOperation
4522 assert(0);
4523 return 0;
4524 case 2:
4525 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4526 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004527 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004528 // anything 3 or over doesn't have l-value operands, so all should be consumed
4529 assert(consumedOperands == operands.size());
4530 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004531 break;
4532 }
4533 }
4534
John Kessenich55e7d112015-11-15 21:33:39 -07004535 // Decode the return types that were structures
4536 switch (op) {
4537 case glslang::EOpAddCarry:
4538 case glslang::EOpSubBorrow:
4539 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4540 id = builder.createCompositeExtract(id, typeId0, 0);
4541 break;
4542 case glslang::EOpUMulExtended:
4543 case glslang::EOpIMulExtended:
4544 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4545 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4546 break;
4547 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004548 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004549 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4550 id = builder.createCompositeExtract(id, typeId0, 0);
4551 break;
4552 default:
4553 break;
4554 }
4555
John Kessenich32cfd492016-02-02 12:37:46 -07004556 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004557}
4558
Rex Xu9d93a232016-05-05 12:30:44 +08004559// Intrinsics with no arguments (or no return value, and no precision).
4560spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004561{
4562 // TODO: get the barrier operands correct
4563
4564 switch (op) {
4565 case glslang::EOpEmitVertex:
4566 builder.createNoResultOp(spv::OpEmitVertex);
4567 return 0;
4568 case glslang::EOpEndPrimitive:
4569 builder.createNoResultOp(spv::OpEndPrimitive);
4570 return 0;
4571 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004572 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004573 return 0;
4574 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004575 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004576 return 0;
4577 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004578 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004579 return 0;
4580 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004581 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004582 return 0;
4583 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004584 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004585 return 0;
4586 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004587 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004588 return 0;
4589 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004590 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004591 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004592 case glslang::EOpAllMemoryBarrierWithGroupSync:
4593 // Control barrier with non-"None" semantic is also a memory barrier.
4594 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4595 return 0;
4596 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4597 // Control barrier with non-"None" semantic is also a memory barrier.
4598 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4599 return 0;
4600 case glslang::EOpWorkgroupMemoryBarrier:
4601 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4602 return 0;
4603 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4604 // Control barrier with non-"None" semantic is also a memory barrier.
4605 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4606 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004607#ifdef AMD_EXTENSIONS
4608 case glslang::EOpTime:
4609 {
4610 std::vector<spv::Id> args; // Dummy arguments
4611 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4612 return builder.setPrecision(id, precision);
4613 }
4614#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004615 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004616 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004617 return 0;
4618 }
4619}
4620
4621spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4622{
John Kessenich2f273362015-07-18 22:34:27 -06004623 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004624 spv::Id id;
4625 if (symbolValues.end() != iter) {
4626 id = iter->second;
4627 return id;
4628 }
4629
4630 // it was not found, create it
4631 id = createSpvVariable(symbol);
4632 symbolValues[symbol->getId()] = id;
4633
Rex Xuc884b4a2016-06-29 15:03:44 +08004634 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004635 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004636 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004637 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004638 if (symbol->getType().getQualifier().hasSpecConstantId())
4639 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004640 if (symbol->getQualifier().hasIndex())
4641 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4642 if (symbol->getQualifier().hasComponent())
4643 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4644 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004645 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004646 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004647 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004648 if (symbol->getQualifier().hasXfbBuffer())
4649 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4650 if (symbol->getQualifier().hasXfbOffset())
4651 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4652 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004653 // atomic counters use this:
4654 if (symbol->getQualifier().hasOffset())
4655 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004656 }
4657
scygan2c864272016-05-18 18:09:17 +02004658 if (symbol->getQualifier().hasLocation())
4659 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004660 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004661 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004662 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004663 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004664 }
John Kessenich140f3df2015-06-26 16:58:36 -06004665 if (symbol->getQualifier().hasSet())
4666 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004667 else if (IsDescriptorResource(symbol->getType())) {
4668 // default to 0
4669 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4670 }
John Kessenich140f3df2015-06-26 16:58:36 -06004671 if (symbol->getQualifier().hasBinding())
4672 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004673 if (symbol->getQualifier().hasAttachment())
4674 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004675 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004676 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004677 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004678 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004679 if (symbol->getQualifier().hasXfbBuffer())
4680 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4681 }
4682
Rex Xu1da878f2016-02-21 20:59:01 +08004683 if (symbol->getType().isImage()) {
4684 std::vector<spv::Decoration> memory;
4685 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4686 for (unsigned int i = 0; i < memory.size(); ++i)
4687 addDecoration(id, memory[i]);
4688 }
4689
John Kessenich140f3df2015-06-26 16:58:36 -06004690 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004691 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004692 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004693 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004694
John Kessenich140f3df2015-06-26 16:58:36 -06004695 return id;
4696}
4697
John Kessenich55e7d112015-11-15 21:33:39 -07004698// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004699void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4700{
John Kessenich4016e382016-07-15 11:53:56 -06004701 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004702 builder.addDecoration(id, dec);
4703}
4704
John Kessenich55e7d112015-11-15 21:33:39 -07004705// If 'dec' is valid, add a one-operand decoration to an object
4706void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4707{
John Kessenich4016e382016-07-15 11:53:56 -06004708 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004709 builder.addDecoration(id, dec, value);
4710}
4711
4712// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004713void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4714{
John Kessenich4016e382016-07-15 11:53:56 -06004715 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004716 builder.addMemberDecoration(id, (unsigned)member, dec);
4717}
4718
John Kessenich92187592016-02-01 13:45:25 -07004719// If 'dec' is valid, add a one-operand decoration to a struct member
4720void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4721{
John Kessenich4016e382016-07-15 11:53:56 -06004722 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004723 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4724}
4725
John Kessenich55e7d112015-11-15 21:33:39 -07004726// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004727// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004728//
4729// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4730//
4731// Recursively walk the nodes. The nodes form a tree whose leaves are
4732// regular constants, which themselves are trees that createSpvConstant()
4733// recursively walks. So, this function walks the "top" of the tree:
4734// - emit specialization constant-building instructions for specConstant
4735// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004736spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004737{
John Kessenich7cc0e282016-03-20 00:46:02 -06004738 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004739
qining4f4bb812016-04-03 23:55:17 -04004740 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004741 if (! node.getQualifier().specConstant) {
4742 // hand off to the non-spec-constant path
4743 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4744 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004745 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004746 nextConst, false);
4747 }
4748
4749 // We now know we have a specialization constant to build
4750
John Kessenichd94c0032016-05-30 19:29:40 -06004751 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004752 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4753 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4754 std::vector<spv::Id> dimConstId;
4755 for (int dim = 0; dim < 3; ++dim) {
4756 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4757 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4758 if (specConst)
4759 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4760 }
4761 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4762 }
4763
4764 // An AST node labelled as specialization constant should be a symbol node.
4765 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4766 if (auto* sn = node.getAsSymbolNode()) {
4767 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004768 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4769 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4770 // will set the builder into spec constant op instruction generating mode.
4771 sub_tree->traverse(this);
4772 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004773 } else if (auto* const_union_array = &sn->getConstArray()){
4774 int nextConst = 0;
4775 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004776 }
4777 }
qining4f4bb812016-04-03 23:55:17 -04004778
4779 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4780 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004781 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004782 exit(1);
4783 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004784}
4785
John Kessenich140f3df2015-06-26 16:58:36 -06004786// Use 'consts' as the flattened glslang source of scalar constants to recursively
4787// build the aggregate SPIR-V constant.
4788//
4789// If there are not enough elements present in 'consts', 0 will be substituted;
4790// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4791//
qining08408382016-03-21 09:51:37 -04004792spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004793{
4794 // vector of constants for SPIR-V
4795 std::vector<spv::Id> spvConsts;
4796
4797 // Type is used for struct and array constants
4798 spv::Id typeId = convertGlslangToSpvType(glslangType);
4799
4800 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004801 glslang::TType elementType(glslangType, 0);
4802 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004803 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004804 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004805 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004806 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004807 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004808 } else if (glslangType.getStruct()) {
4809 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4810 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004811 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004812 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004813 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4814 bool zero = nextConst >= consts.size();
4815 switch (glslangType.getBasicType()) {
4816 case glslang::EbtInt:
4817 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4818 break;
4819 case glslang::EbtUint:
4820 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4821 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004822 case glslang::EbtInt64:
4823 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4824 break;
4825 case glslang::EbtUint64:
4826 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4827 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004828 case glslang::EbtFloat:
4829 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4830 break;
4831 case glslang::EbtDouble:
4832 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4833 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004834#ifdef AMD_EXTENSIONS
4835 case glslang::EbtFloat16:
4836 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4837 break;
4838#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004839 case glslang::EbtBool:
4840 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4841 break;
4842 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004843 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004844 break;
4845 }
4846 ++nextConst;
4847 }
4848 } else {
4849 // we have a non-aggregate (scalar) constant
4850 bool zero = nextConst >= consts.size();
4851 spv::Id scalar = 0;
4852 switch (glslangType.getBasicType()) {
4853 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004854 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004855 break;
4856 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004857 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004858 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004859 case glslang::EbtInt64:
4860 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4861 break;
4862 case glslang::EbtUint64:
4863 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4864 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004865 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004866 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004867 break;
4868 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004869 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004870 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004871#ifdef AMD_EXTENSIONS
4872 case glslang::EbtFloat16:
4873 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4874 break;
4875#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004876 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004877 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004878 break;
4879 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004880 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004881 break;
4882 }
4883 ++nextConst;
4884 return scalar;
4885 }
4886
4887 return builder.makeCompositeConstant(typeId, spvConsts);
4888}
4889
John Kessenich7c1aa102015-10-15 13:29:11 -06004890// Return true if the node is a constant or symbol whose reading has no
4891// non-trivial observable cost or effect.
4892bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4893{
4894 // don't know what this is
4895 if (node == nullptr)
4896 return false;
4897
4898 // a constant is safe
4899 if (node->getAsConstantUnion() != nullptr)
4900 return true;
4901
4902 // not a symbol means non-trivial
4903 if (node->getAsSymbolNode() == nullptr)
4904 return false;
4905
4906 // a symbol, depends on what's being read
4907 switch (node->getType().getQualifier().storage) {
4908 case glslang::EvqTemporary:
4909 case glslang::EvqGlobal:
4910 case glslang::EvqIn:
4911 case glslang::EvqInOut:
4912 case glslang::EvqConst:
4913 case glslang::EvqConstReadOnly:
4914 case glslang::EvqUniform:
4915 return true;
4916 default:
4917 return false;
4918 }
qining25262b32016-05-06 17:25:16 -04004919}
John Kessenich7c1aa102015-10-15 13:29:11 -06004920
4921// A node is trivial if it is a single operation with no side effects.
4922// Error on the side of saying non-trivial.
4923// Return true if trivial.
4924bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4925{
4926 if (node == nullptr)
4927 return false;
4928
4929 // symbols and constants are trivial
4930 if (isTrivialLeaf(node))
4931 return true;
4932
4933 // otherwise, it needs to be a simple operation or one or two leaf nodes
4934
4935 // not a simple operation
4936 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4937 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4938 if (binaryNode == nullptr && unaryNode == nullptr)
4939 return false;
4940
4941 // not on leaf nodes
4942 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4943 return false;
4944
4945 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4946 return false;
4947 }
4948
4949 switch (node->getAsOperator()->getOp()) {
4950 case glslang::EOpLogicalNot:
4951 case glslang::EOpConvIntToBool:
4952 case glslang::EOpConvUintToBool:
4953 case glslang::EOpConvFloatToBool:
4954 case glslang::EOpConvDoubleToBool:
4955 case glslang::EOpEqual:
4956 case glslang::EOpNotEqual:
4957 case glslang::EOpLessThan:
4958 case glslang::EOpGreaterThan:
4959 case glslang::EOpLessThanEqual:
4960 case glslang::EOpGreaterThanEqual:
4961 case glslang::EOpIndexDirect:
4962 case glslang::EOpIndexDirectStruct:
4963 case glslang::EOpLogicalXor:
4964 case glslang::EOpAny:
4965 case glslang::EOpAll:
4966 return true;
4967 default:
4968 return false;
4969 }
4970}
4971
4972// Emit short-circuiting code, where 'right' is never evaluated unless
4973// the left side is true (for &&) or false (for ||).
4974spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4975{
4976 spv::Id boolTypeId = builder.makeBoolType();
4977
4978 // emit left operand
4979 builder.clearAccessChain();
4980 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004981 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004982
4983 // Operands to accumulate OpPhi operands
4984 std::vector<spv::Id> phiOperands;
4985 // accumulate left operand's phi information
4986 phiOperands.push_back(leftId);
4987 phiOperands.push_back(builder.getBuildPoint()->getId());
4988
4989 // Make the two kinds of operation symmetric with a "!"
4990 // || => emit "if (! left) result = right"
4991 // && => emit "if ( left) result = right"
4992 //
4993 // TODO: this runtime "not" for || could be avoided by adding functionality
4994 // to 'builder' to have an "else" without an "then"
4995 if (op == glslang::EOpLogicalOr)
4996 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4997
4998 // make an "if" based on the left value
4999 spv::Builder::If ifBuilder(leftId, builder);
5000
5001 // emit right operand as the "then" part of the "if"
5002 builder.clearAccessChain();
5003 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005004 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005005
5006 // accumulate left operand's phi information
5007 phiOperands.push_back(rightId);
5008 phiOperands.push_back(builder.getBuildPoint()->getId());
5009
5010 // finish the "if"
5011 ifBuilder.makeEndIf();
5012
5013 // phi together the two results
5014 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5015}
5016
Rex Xu9d93a232016-05-05 12:30:44 +08005017// Return type Id of the imported set of extended instructions corresponds to the name.
5018// Import this set if it has not been imported yet.
5019spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5020{
5021 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5022 return extBuiltinMap[name];
5023 else {
Rex Xu51596642016-09-21 18:56:12 +08005024 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005025 spv::Id extBuiltins = builder.import(name);
5026 extBuiltinMap[name] = extBuiltins;
5027 return extBuiltins;
5028 }
5029}
5030
John Kessenich140f3df2015-06-26 16:58:36 -06005031}; // end anonymous namespace
5032
5033namespace glslang {
5034
John Kessenich68d78fd2015-07-12 19:28:10 -06005035void GetSpirvVersion(std::string& version)
5036{
John Kessenich9e55f632015-07-15 10:03:39 -06005037 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005038 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005039 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005040 version = buf;
5041}
5042
John Kessenich140f3df2015-06-26 16:58:36 -06005043// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005044void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005045{
5046 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005047 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005048 for (int i = 0; i < (int)spirv.size(); ++i) {
5049 unsigned int word = spirv[i];
5050 out.write((const char*)&word, 4);
5051 }
5052 out.close();
5053}
5054
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005055// Write SPIR-V out to a text file with 32-bit hexadecimal words
5056void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5057{
5058 std::ofstream out;
5059 out.open(baseName, std::ios::binary | std::ios::out);
5060 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5061 const int WORDS_PER_LINE = 8;
5062 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5063 out << "\t";
5064 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5065 const unsigned int word = spirv[i + j];
5066 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5067 if (i + j + 1 < (int)spirv.size()) {
5068 out << ",";
5069 }
5070 }
5071 out << std::endl;
5072 }
5073 out.close();
5074}
5075
John Kessenich140f3df2015-06-26 16:58:36 -06005076//
5077// Set up the glslang traversal
5078//
5079void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5080{
Lei Zhang17535f72016-05-04 15:55:59 -04005081 spv::SpvBuildLogger logger;
5082 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005083}
5084
Lei Zhang17535f72016-05-04 15:55:59 -04005085void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005086{
John Kessenich140f3df2015-06-26 16:58:36 -06005087 TIntermNode* root = intermediate.getTreeRoot();
5088
5089 if (root == 0)
5090 return;
5091
5092 glslang::GetThreadPoolAllocator().push();
5093
Lei Zhang17535f72016-05-04 15:55:59 -04005094 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005095
5096 root->traverse(&it);
5097
5098 it.dumpSpv(spirv);
5099
5100 glslang::GetThreadPoolAllocator().pop();
5101}
5102
5103}; // end namespace glslang