blob: 6e18b2b69e3d29a43f402854bed01abd2f7701a6 [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 Kessenich55e7d112015-11-15 21:33:39 -0700175 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600176 int sequenceDepth;
177
Lei Zhang17535f72016-05-04 15:55:59 -0400178 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400179
John Kessenich140f3df2015-06-26 16:58:36 -0600180 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
181 spv::Builder builder;
182 bool inMain;
183 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700184 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 -0700185 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600186 const glslang::TIntermediate* glslangIntermediate;
187 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800188 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600189
John Kessenich2f273362015-07-18 22:34:27 -0600190 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600191 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600192 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700193 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600194 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 -0600195 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600196};
197
198//
199// Helper functions for translating glslang representations to SPIR-V enumerants.
200//
201
202// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700203spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600204{
John Kessenich66e2faf2016-03-12 18:34:36 -0700205 switch (source) {
206 case glslang::EShSourceGlsl:
207 switch (profile) {
208 case ENoProfile:
209 case ECoreProfile:
210 case ECompatibilityProfile:
211 return spv::SourceLanguageGLSL;
212 case EEsProfile:
213 return spv::SourceLanguageESSL;
214 default:
215 return spv::SourceLanguageUnknown;
216 }
217 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400218 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
219 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 default:
221 return spv::SourceLanguageUnknown;
222 }
223}
224
225// Translate glslang language (stage) to SPIR-V execution model.
226spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
227{
228 switch (stage) {
229 case EShLangVertex: return spv::ExecutionModelVertex;
230 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
231 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
232 case EShLangGeometry: return spv::ExecutionModelGeometry;
233 case EShLangFragment: return spv::ExecutionModelFragment;
234 case EShLangCompute: return spv::ExecutionModelGLCompute;
235 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700236 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600237 return spv::ExecutionModelFragment;
238 }
239}
240
241// Translate glslang type to SPIR-V storage class.
242spv::StorageClass TranslateStorageClass(const glslang::TType& type)
243{
244 if (type.getQualifier().isPipeInput())
245 return spv::StorageClassInput;
246 else if (type.getQualifier().isPipeOutput())
247 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700248 else if (type.getBasicType() == glslang::EbtSampler)
249 return spv::StorageClassUniformConstant;
250 else if (type.getBasicType() == glslang::EbtAtomicUint)
251 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600252 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700253 if (type.getQualifier().layoutPushConstant)
254 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600255 if (type.getBasicType() == glslang::EbtBlock)
256 return spv::StorageClassUniform;
257 else
258 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600259 // 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 -0600260 } else {
261 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700262 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
263 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
265 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400266 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600268 return spv::StorageClassFunction;
269 }
270 }
271}
272
273// Translate glslang sampler type to SPIR-V dimensionality.
274spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
275{
276 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700277 case glslang::Esd1D: return spv::Dim1D;
278 case glslang::Esd2D: return spv::Dim2D;
279 case glslang::Esd3D: return spv::Dim3D;
280 case glslang::EsdCube: return spv::DimCube;
281 case glslang::EsdRect: return spv::DimRect;
282 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700283 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700285 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600286 return spv::Dim2D;
287 }
288}
289
John Kessenichf6640762016-08-01 19:44:00 -0600290// Translate glslang precision to SPIR-V precision decorations.
291spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600292{
John Kessenichf6640762016-08-01 19:44:00 -0600293 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700294 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600295 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 default:
297 return spv::NoPrecision;
298 }
299}
300
John Kessenichf6640762016-08-01 19:44:00 -0600301// Translate glslang type to SPIR-V precision decorations.
302spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
303{
304 return TranslatePrecisionDecoration(type.getQualifier().precision);
305}
306
John Kessenich140f3df2015-06-26 16:58:36 -0600307// Translate glslang type to SPIR-V block decorations.
308spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
309{
310 if (type.getBasicType() == glslang::EbtBlock) {
311 switch (type.getQualifier().storage) {
312 case glslang::EvqUniform: return spv::DecorationBlock;
313 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
314 case glslang::EvqVaryingIn: return spv::DecorationBlock;
315 case glslang::EvqVaryingOut: return spv::DecorationBlock;
316 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600318 break;
319 }
320 }
321
John Kessenich4016e382016-07-15 11:53:56 -0600322 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600323}
324
Rex Xu1da878f2016-02-21 20:59:01 +0800325// Translate glslang type to SPIR-V memory decorations.
326void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
327{
328 if (qualifier.coherent)
329 memory.push_back(spv::DecorationCoherent);
330 if (qualifier.volatil)
331 memory.push_back(spv::DecorationVolatile);
332 if (qualifier.restrict)
333 memory.push_back(spv::DecorationRestrict);
334 if (qualifier.readonly)
335 memory.push_back(spv::DecorationNonWritable);
336 if (qualifier.writeonly)
337 memory.push_back(spv::DecorationNonReadable);
338}
339
John Kessenich140f3df2015-06-26 16:58:36 -0600340// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700341spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600342{
343 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700344 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600345 case glslang::ElmRowMajor:
346 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700347 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 default:
350 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 }
353 } else {
354 switch (type.getBasicType()) {
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 break;
358 case glslang::EbtBlock:
359 switch (type.getQualifier().storage) {
360 case glslang::EvqUniform:
361 case glslang::EvqBuffer:
362 switch (type.getQualifier().layoutPacking) {
363 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
365 default:
John Kessenich4016e382016-07-15 11:53:56 -0600366 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 }
368 case glslang::EvqVaryingIn:
369 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700370 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700373 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600374 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600375 }
376 }
377 }
378}
379
380// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700382// should be applied.
Rex Xubbceed72016-05-21 09:40:44 +0800383spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600384{
Rex Xubbceed72016-05-21 09:40:44 +0800385 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700386 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700389 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700390 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800392#ifdef AMD_EXTENSIONS
393 else if (qualifier.explicitInterp)
394 return spv::DecorationExplicitInterpAMD;
395#endif
Rex Xubbceed72016-05-21 09:40:44 +0800396 else
John Kessenich4016e382016-07-15 11:53:56 -0600397 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800398}
399
400// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600401// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800402// should be applied.
403spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
404{
405 if (qualifier.patch)
406 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600408 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700409 else if (qualifier.sample) {
410 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600411 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700412 } else
John Kessenich4016e382016-07-15 11:53:56 -0600413 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600414}
415
John Kessenich92187592016-02-01 13:45:25 -0700416// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700417spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600418{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700419 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600420 return spv::DecorationInvariant;
421 else
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423}
424
qining9220dbb2016-05-04 17:34:38 -0400425// If glslang type is noContraction, return SPIR-V NoContraction decoration.
426spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
427{
428 if (qualifier.noContraction)
429 return spv::DecorationNoContraction;
430 else
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400432}
433
David Netoa901ffe2016-06-08 14:11:40 +0100434// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
435// associated capabilities when required. For some built-in variables, a capability
436// is generated only when using the variable in an executable instruction, but not when
437// just declaring a struct member variable with it. This is true for PointSize,
438// ClipDistance, and CullDistance.
439spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600440{
441 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700442 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600443 // Defer adding the capability until the built-in is actually used.
444 if (! memberDeclaration) {
445 switch (glslangIntermediate->getStage()) {
446 case EShLangGeometry:
447 builder.addCapability(spv::CapabilityGeometryPointSize);
448 break;
449 case EShLangTessControl:
450 case EShLangTessEvaluation:
451 builder.addCapability(spv::CapabilityTessellationPointSize);
452 break;
453 default:
454 break;
455 }
John Kessenich92187592016-02-01 13:45:25 -0700456 }
457 return spv::BuiltInPointSize;
458
John Kessenichebb50532016-05-16 19:22:05 -0600459 // These *Distance capabilities logically belong here, but if the member is declared and
460 // then never used, consumers of SPIR-V prefer the capability not be declared.
461 // They are now generated when used, rather than here when declared.
462 // Potentially, the specification should be more clear what the minimum
463 // use needed is to trigger the capability.
464 //
John Kessenich92187592016-02-01 13:45:25 -0700465 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100466 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600467 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700468 return spv::BuiltInClipDistance;
469
470 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100471 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600472 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700473 return spv::BuiltInCullDistance;
474
475 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500476 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700477 return spv::BuiltInViewportIndex;
478
John Kessenich5e801132016-02-15 11:09:46 -0700479 case glslang::EbvSampleId:
480 builder.addCapability(spv::CapabilitySampleRateShading);
481 return spv::BuiltInSampleId;
482
483 case glslang::EbvSamplePosition:
484 builder.addCapability(spv::CapabilitySampleRateShading);
485 return spv::BuiltInSamplePosition;
486
487 case glslang::EbvSampleMask:
488 builder.addCapability(spv::CapabilitySampleRateShading);
489 return spv::BuiltInSampleMask;
490
John Kessenich78a45572016-07-08 14:05:15 -0600491 case glslang::EbvLayer:
492 builder.addCapability(spv::CapabilityGeometry);
493 return spv::BuiltInLayer;
494
John Kessenich140f3df2015-06-26 16:58:36 -0600495 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvVertexId: return spv::BuiltInVertexId;
497 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700498 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
499 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600500 case glslang::EbvBaseVertex:
501 case glslang::EbvBaseInstance:
502 case glslang::EbvDrawId:
503 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600504 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600505 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600506 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
507 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600508 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
509 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
510 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
511 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
512 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
513 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
514 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600515 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
516 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
517 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
518 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
519 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
520 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
521 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
522 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800523
Rex Xu574ab042016-04-14 16:53:07 +0800524 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800525 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800526 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
527 return spv::BuiltInSubgroupSize;
528
Rex Xu574ab042016-04-14 16:53:07 +0800529 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800530 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800531 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
532 return spv::BuiltInSubgroupLocalInvocationId;
533
Rex Xu574ab042016-04-14 16:53:07 +0800534 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800535 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
536 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
537 return spv::BuiltInSubgroupEqMaskKHR;
538
Rex Xu574ab042016-04-14 16:53:07 +0800539 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
541 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
542 return spv::BuiltInSubgroupGeMaskKHR;
543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupGtMaskKHR;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupLeMaskKHR;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupLtMaskKHR;
558
Rex Xu9d93a232016-05-05 12:30:44 +0800559#ifdef AMD_EXTENSIONS
560 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
561 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
562 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
563 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
564 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
565 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
566 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
567#endif
John Kessenich4016e382016-07-15 11:53:56 -0600568 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600569 }
570}
571
Rex Xufc618912015-09-09 16:42:49 +0800572// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700573spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800574{
575 assert(type.getBasicType() == glslang::EbtSampler);
576
John Kessenich5d0fa972016-02-15 11:57:00 -0700577 // Check for capabilities
578 switch (type.getQualifier().layoutFormat) {
579 case glslang::ElfRg32f:
580 case glslang::ElfRg16f:
581 case glslang::ElfR11fG11fB10f:
582 case glslang::ElfR16f:
583 case glslang::ElfRgba16:
584 case glslang::ElfRgb10A2:
585 case glslang::ElfRg16:
586 case glslang::ElfRg8:
587 case glslang::ElfR16:
588 case glslang::ElfR8:
589 case glslang::ElfRgba16Snorm:
590 case glslang::ElfRg16Snorm:
591 case glslang::ElfRg8Snorm:
592 case glslang::ElfR16Snorm:
593 case glslang::ElfR8Snorm:
594
595 case glslang::ElfRg32i:
596 case glslang::ElfRg16i:
597 case glslang::ElfRg8i:
598 case glslang::ElfR16i:
599 case glslang::ElfR8i:
600
601 case glslang::ElfRgb10a2ui:
602 case glslang::ElfRg32ui:
603 case glslang::ElfRg16ui:
604 case glslang::ElfRg8ui:
605 case glslang::ElfR16ui:
606 case glslang::ElfR8ui:
607 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
608 break;
609
610 default:
611 break;
612 }
613
614 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800615 switch (type.getQualifier().layoutFormat) {
616 case glslang::ElfNone: return spv::ImageFormatUnknown;
617 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
618 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
619 case glslang::ElfR32f: return spv::ImageFormatR32f;
620 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
621 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
622 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
623 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
624 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
625 case glslang::ElfR16f: return spv::ImageFormatR16f;
626 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
627 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
628 case glslang::ElfRg16: return spv::ImageFormatRg16;
629 case glslang::ElfRg8: return spv::ImageFormatRg8;
630 case glslang::ElfR16: return spv::ImageFormatR16;
631 case glslang::ElfR8: return spv::ImageFormatR8;
632 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
633 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
634 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
635 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
636 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
637 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
638 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
639 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
640 case glslang::ElfR32i: return spv::ImageFormatR32i;
641 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
642 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
643 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
644 case glslang::ElfR16i: return spv::ImageFormatR16i;
645 case glslang::ElfR8i: return spv::ImageFormatR8i;
646 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
647 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
648 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
649 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
650 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
651 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
652 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
653 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
654 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
655 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600656 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800657 }
658}
659
qining25262b32016-05-06 17:25:16 -0400660// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700661// descriptor set.
662bool IsDescriptorResource(const glslang::TType& type)
663{
John Kessenichf7497e22016-03-08 21:36:22 -0700664 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700665 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700666 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700667
668 // non block...
669 // basically samplerXXX/subpass/sampler/texture are all included
670 // if they are the global-scope-class, not the function parameter
671 // (or local, if they ever exist) class.
672 if (type.getBasicType() == glslang::EbtSampler)
673 return type.getQualifier().isUniformOrBuffer();
674
675 // None of the above.
676 return false;
677}
678
John Kesseniche0b6cad2015-12-24 10:30:13 -0700679void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
680{
681 if (child.layoutMatrix == glslang::ElmNone)
682 child.layoutMatrix = parent.layoutMatrix;
683
684 if (parent.invariant)
685 child.invariant = true;
686 if (parent.nopersp)
687 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800688#ifdef AMD_EXTENSIONS
689 if (parent.explicitInterp)
690 child.explicitInterp = true;
691#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700692 if (parent.flat)
693 child.flat = true;
694 if (parent.centroid)
695 child.centroid = true;
696 if (parent.patch)
697 child.patch = true;
698 if (parent.sample)
699 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800700 if (parent.coherent)
701 child.coherent = true;
702 if (parent.volatil)
703 child.volatil = true;
704 if (parent.restrict)
705 child.restrict = true;
706 if (parent.readonly)
707 child.readonly = true;
708 if (parent.writeonly)
709 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700710}
711
John Kessenichf2b7f332016-09-01 17:05:23 -0600712bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700713{
John Kessenich7b9fa252016-01-21 18:56:57 -0700714 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600715 // - struct members might inherit from a struct declaration
716 // (note that non-block structs don't explicitly inherit,
717 // only implicitly, meaning no decoration involved)
718 // - affect decorations on the struct members
719 // (note smooth does not, and expecting something like volatile
720 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700721 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600722 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700723}
724
John Kessenich140f3df2015-06-26 16:58:36 -0600725//
726// Implement the TGlslangToSpvTraverser class.
727//
728
Lei Zhang17535f72016-05-04 15:55:59 -0400729TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
730 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
731 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600732 inMain(false), mainTerminated(false), linkageOnly(false),
733 glslangIntermediate(glslangIntermediate)
734{
735 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
736
737 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700738 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600739 stdBuiltins = builder.import("GLSL.std.450");
740 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600741 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
742 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600743
744 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600745 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
746 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600747 builder.addSourceExtension(it->c_str());
748
749 // Add the top-level modes for this shader.
750
John Kessenich92187592016-02-01 13:45:25 -0700751 if (glslangIntermediate->getXfbMode()) {
752 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600753 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700754 }
John Kessenich140f3df2015-06-26 16:58:36 -0600755
756 unsigned int mode;
757 switch (glslangIntermediate->getStage()) {
758 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600759 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600760 break;
761
762 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600763 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600764 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
765 break;
766
767 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600768 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600769 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700770 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
771 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
772 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600773 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600774 }
John Kessenich4016e382016-07-15 11:53:56 -0600775 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600776 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
777
John Kesseniche6903322015-10-13 16:29:02 -0600778 switch (glslangIntermediate->getVertexSpacing()) {
779 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
780 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
781 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600782 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600783 }
John Kessenich4016e382016-07-15 11:53:56 -0600784 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600785 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
786
787 switch (glslangIntermediate->getVertexOrder()) {
788 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
789 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600790 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600791 }
John Kessenich4016e382016-07-15 11:53:56 -0600792 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600793 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
794
795 if (glslangIntermediate->getPointMode())
796 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600797 break;
798
799 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600800 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600801 switch (glslangIntermediate->getInputPrimitive()) {
802 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
803 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
804 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700805 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600806 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600807 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600808 }
John Kessenich4016e382016-07-15 11:53:56 -0600809 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600810 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600811
John Kessenich140f3df2015-06-26 16:58:36 -0600812 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
813
814 switch (glslangIntermediate->getOutputPrimitive()) {
815 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
816 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
817 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600818 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600819 }
John Kessenich4016e382016-07-15 11:53:56 -0600820 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600821 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
822 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
823 break;
824
825 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600826 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600827 if (glslangIntermediate->getPixelCenterInteger())
828 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600829
John Kessenich140f3df2015-06-26 16:58:36 -0600830 if (glslangIntermediate->getOriginUpperLeft())
831 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600832 else
833 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600834
835 if (glslangIntermediate->getEarlyFragmentTests())
836 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
837
838 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600839 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
840 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600841 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600842 }
John Kessenich4016e382016-07-15 11:53:56 -0600843 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600844 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
845
846 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
847 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600848 break;
849
850 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600851 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600852 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
853 glslangIntermediate->getLocalSize(1),
854 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600855 break;
856
857 default:
858 break;
859 }
860
861}
862
John Kessenich7ba63412015-12-20 17:37:07 -0700863// Finish everything and dump
864void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
865{
866 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100867 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
868 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700869
qiningda397332016-03-09 19:54:03 -0500870 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700871 builder.dump(out);
872}
873
John Kessenich140f3df2015-06-26 16:58:36 -0600874TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
875{
876 if (! mainTerminated) {
877 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
878 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600879 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600880 }
881}
882
883//
884// Implement the traversal functions.
885//
886// Return true from interior nodes to have the external traversal
887// continue on to children. Return false if children were
888// already processed.
889//
890
891//
qining25262b32016-05-06 17:25:16 -0400892// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600893// - uniform/input reads
894// - output writes
895// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
896// - something simple that degenerates into the last bullet
897//
898void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
899{
qining75d1d802016-04-06 14:42:01 -0400900 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
901 if (symbol->getType().getQualifier().isSpecConstant())
902 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
903
John Kessenich140f3df2015-06-26 16:58:36 -0600904 // getSymbolId() will set up all the IO decorations on the first call.
905 // Formal function parameters were mapped during makeFunctions().
906 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700907
908 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
909 if (builder.isPointer(id)) {
910 spv::StorageClass sc = builder.getStorageClass(id);
911 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
912 iOSet.insert(id);
913 }
914
915 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700916 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600917 // Prepare to generate code for the access
918
919 // L-value chains will be computed left to right. We're on the symbol now,
920 // which is the left-most part of the access chain, so now is "clear" time,
921 // followed by setting the base.
922 builder.clearAccessChain();
923
924 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700925 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600926 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700927 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600928 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700929 // These are also pure R-values.
930 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600931 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600932 builder.setAccessChainRValue(id);
933 else
934 builder.setAccessChainLValue(id);
935 }
936}
937
938bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
939{
qining40887662016-04-03 22:20:42 -0400940 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
941 if (node->getType().getQualifier().isSpecConstant())
942 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
943
John Kessenich140f3df2015-06-26 16:58:36 -0600944 // First, handle special cases
945 switch (node->getOp()) {
946 case glslang::EOpAssign:
947 case glslang::EOpAddAssign:
948 case glslang::EOpSubAssign:
949 case glslang::EOpMulAssign:
950 case glslang::EOpVectorTimesMatrixAssign:
951 case glslang::EOpVectorTimesScalarAssign:
952 case glslang::EOpMatrixTimesScalarAssign:
953 case glslang::EOpMatrixTimesMatrixAssign:
954 case glslang::EOpDivAssign:
955 case glslang::EOpModAssign:
956 case glslang::EOpAndAssign:
957 case glslang::EOpInclusiveOrAssign:
958 case glslang::EOpExclusiveOrAssign:
959 case glslang::EOpLeftShiftAssign:
960 case glslang::EOpRightShiftAssign:
961 // A bin-op assign "a += b" means the same thing as "a = a + b"
962 // where a is evaluated before b. For a simple assignment, GLSL
963 // says to evaluate the left before the right. So, always, left
964 // node then right node.
965 {
966 // get the left l-value, save it away
967 builder.clearAccessChain();
968 node->getLeft()->traverse(this);
969 spv::Builder::AccessChain lValue = builder.getAccessChain();
970
971 // evaluate the right
972 builder.clearAccessChain();
973 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700974 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600975
976 if (node->getOp() != glslang::EOpAssign) {
977 // the left is also an r-value
978 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700979 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600980
981 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600982 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400983 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600984 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
985 node->getType().getBasicType());
986
987 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700988 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600989 }
990
991 // store the result
992 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -0600993 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600994
995 // assignments are expressions having an rValue after they are evaluated...
996 builder.clearAccessChain();
997 builder.setAccessChainRValue(rValue);
998 }
999 return false;
1000 case glslang::EOpIndexDirect:
1001 case glslang::EOpIndexDirectStruct:
1002 {
1003 // Get the left part of the access chain.
1004 node->getLeft()->traverse(this);
1005
1006 // Add the next element in the chain
1007
David Netoa901ffe2016-06-08 14:11:40 +01001008 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001009 if (! node->getLeft()->getType().isArray() &&
1010 node->getLeft()->getType().isVector() &&
1011 node->getOp() == glslang::EOpIndexDirect) {
1012 // This is essentially a hard-coded vector swizzle of size 1,
1013 // so short circuit the access-chain stuff with a swizzle.
1014 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001015 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001016 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001017 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001018 int spvIndex = glslangIndex;
1019 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1020 node->getOp() == glslang::EOpIndexDirectStruct)
1021 {
1022 // This may be, e.g., an anonymous block-member selection, which generally need
1023 // index remapping due to hidden members in anonymous blocks.
1024 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1025 assert(remapper.size() > 0);
1026 spvIndex = remapper[glslangIndex];
1027 }
John Kessenichebb50532016-05-16 19:22:05 -06001028
David Netoa901ffe2016-06-08 14:11:40 +01001029 // normal case for indexing array or structure or block
1030 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1031
1032 // Add capabilities here for accessing PointSize and clip/cull distance.
1033 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001034 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001035 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001036 }
1037 }
1038 return false;
1039 case glslang::EOpIndexIndirect:
1040 {
1041 // Structure or array or vector indirection.
1042 // Will use native SPIR-V access-chain for struct and array indirection;
1043 // matrices are arrays of vectors, so will also work for a matrix.
1044 // Will use the access chain's 'component' for variable index into a vector.
1045
1046 // This adapter is building access chains left to right.
1047 // Set up the access chain to the left.
1048 node->getLeft()->traverse(this);
1049
1050 // save it so that computing the right side doesn't trash it
1051 spv::Builder::AccessChain partial = builder.getAccessChain();
1052
1053 // compute the next index in the chain
1054 builder.clearAccessChain();
1055 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001056 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001057
1058 // restore the saved access chain
1059 builder.setAccessChain(partial);
1060
1061 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001062 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001063 else
John Kessenichfa668da2015-09-13 14:46:30 -06001064 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001065 }
1066 return false;
1067 case glslang::EOpVectorSwizzle:
1068 {
1069 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001070 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001071 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001072 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001073 }
1074 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001075 case glslang::EOpLogicalOr:
1076 case glslang::EOpLogicalAnd:
1077 {
1078
1079 // These may require short circuiting, but can sometimes be done as straight
1080 // binary operations. The right operand must be short circuited if it has
1081 // side effects, and should probably be if it is complex.
1082 if (isTrivial(node->getRight()->getAsTyped()))
1083 break; // handle below as a normal binary operation
1084 // otherwise, we need to do dynamic short circuiting on the right operand
1085 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1086 builder.clearAccessChain();
1087 builder.setAccessChainRValue(result);
1088 }
1089 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001090 default:
1091 break;
1092 }
1093
1094 // Assume generic binary op...
1095
John Kessenich32cfd492016-02-02 12:37:46 -07001096 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001097 builder.clearAccessChain();
1098 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001099 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001100
John Kessenich32cfd492016-02-02 12:37:46 -07001101 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001102 builder.clearAccessChain();
1103 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001104 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001105
John Kessenich32cfd492016-02-02 12:37:46 -07001106 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001107 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001108 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001109 convertGlslangToSpvType(node->getType()), left, right,
1110 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001111
John Kessenich50e57562015-12-21 21:21:11 -07001112 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001113 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001114 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001115 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001116 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001117 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001118 return false;
1119 }
John Kessenich140f3df2015-06-26 16:58:36 -06001120}
1121
1122bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1123{
qining40887662016-04-03 22:20:42 -04001124 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1125 if (node->getType().getQualifier().isSpecConstant())
1126 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1127
John Kessenichfc51d282015-08-19 13:34:18 -06001128 spv::Id result = spv::NoResult;
1129
1130 // try texturing first
1131 result = createImageTextureFunctionCall(node);
1132 if (result != spv::NoResult) {
1133 builder.clearAccessChain();
1134 builder.setAccessChainRValue(result);
1135
1136 return false; // done with this node
1137 }
1138
1139 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001140
1141 if (node->getOp() == glslang::EOpArrayLength) {
1142 // Quite special; won't want to evaluate the operand.
1143
1144 // Normal .length() would have been constant folded by the front-end.
1145 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001146 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001147 assert(node->getOperand()->getType().isRuntimeSizedArray());
1148 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1149 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001150 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1151 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001152
1153 builder.clearAccessChain();
1154 builder.setAccessChainRValue(length);
1155
1156 return false;
1157 }
1158
John Kessenichfc51d282015-08-19 13:34:18 -06001159 // Start by evaluating the operand
1160
John Kessenich8c8505c2016-07-26 12:50:38 -06001161 // Does it need a swizzle inversion? If so, evaluation is inverted;
1162 // operate first on the swizzle base, then apply the swizzle.
1163 spv::Id invertedType = spv::NoType;
1164 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1165 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1166 invertedType = getInvertedSwizzleType(*node->getOperand());
1167
John Kessenich140f3df2015-06-26 16:58:36 -06001168 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001169 if (invertedType != spv::NoType)
1170 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1171 else
1172 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001173
Rex Xufc618912015-09-09 16:42:49 +08001174 spv::Id operand = spv::NoResult;
1175
1176 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1177 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001178 node->getOp() == glslang::EOpAtomicCounter ||
1179 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001180 operand = builder.accessChainGetLValue(); // Special case l-value operands
1181 else
John Kessenich32cfd492016-02-02 12:37:46 -07001182 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001183
John Kessenichf6640762016-08-01 19:44:00 -06001184 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001185 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001186
1187 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001188 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001189 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001190
1191 // if not, then possibly an operation
1192 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001193 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001194
1195 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001196 if (invertedType)
1197 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1198
John Kessenich140f3df2015-06-26 16:58:36 -06001199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(result);
1201
1202 return false; // done with this node
1203 }
1204
1205 // it must be a special case, check...
1206 switch (node->getOp()) {
1207 case glslang::EOpPostIncrement:
1208 case glslang::EOpPostDecrement:
1209 case glslang::EOpPreIncrement:
1210 case glslang::EOpPreDecrement:
1211 {
1212 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001213 spv::Id one = 0;
1214 if (node->getBasicType() == glslang::EbtFloat)
1215 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001216 else if (node->getBasicType() == glslang::EbtDouble)
1217 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001218#ifdef AMD_EXTENSIONS
1219 else if (node->getBasicType() == glslang::EbtFloat16)
1220 one = builder.makeFloat16Constant(1.0F);
1221#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001222 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1223 one = builder.makeInt64Constant(1);
1224 else
1225 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001226 glslang::TOperator op;
1227 if (node->getOp() == glslang::EOpPreIncrement ||
1228 node->getOp() == glslang::EOpPostIncrement)
1229 op = glslang::EOpAdd;
1230 else
1231 op = glslang::EOpSub;
1232
John Kessenichf6640762016-08-01 19:44:00 -06001233 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001234 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001235 convertGlslangToSpvType(node->getType()), operand, one,
1236 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001237 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001238
1239 // The result of operation is always stored, but conditionally the
1240 // consumed result. The consumed result is always an r-value.
1241 builder.accessChainStore(result);
1242 builder.clearAccessChain();
1243 if (node->getOp() == glslang::EOpPreIncrement ||
1244 node->getOp() == glslang::EOpPreDecrement)
1245 builder.setAccessChainRValue(result);
1246 else
1247 builder.setAccessChainRValue(operand);
1248 }
1249
1250 return false;
1251
1252 case glslang::EOpEmitStreamVertex:
1253 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1254 return false;
1255 case glslang::EOpEndStreamPrimitive:
1256 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1257 return false;
1258
1259 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001260 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001261 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001262 }
John Kessenich140f3df2015-06-26 16:58:36 -06001263}
1264
1265bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1266{
qining27e04a02016-04-14 16:40:20 -04001267 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1268 if (node->getType().getQualifier().isSpecConstant())
1269 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1270
John Kessenichfc51d282015-08-19 13:34:18 -06001271 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001272 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1273 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001274
1275 // try texturing
1276 result = createImageTextureFunctionCall(node);
1277 if (result != spv::NoResult) {
1278 builder.clearAccessChain();
1279 builder.setAccessChainRValue(result);
1280
1281 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001282 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001283 // "imageStore" is a special case, which has no result
1284 return false;
1285 }
John Kessenichfc51d282015-08-19 13:34:18 -06001286
John Kessenich140f3df2015-06-26 16:58:36 -06001287 glslang::TOperator binOp = glslang::EOpNull;
1288 bool reduceComparison = true;
1289 bool isMatrix = false;
1290 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001291 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001292
1293 assert(node->getOp());
1294
John Kessenichf6640762016-08-01 19:44:00 -06001295 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001296
1297 switch (node->getOp()) {
1298 case glslang::EOpSequence:
1299 {
1300 if (preVisit)
1301 ++sequenceDepth;
1302 else
1303 --sequenceDepth;
1304
1305 if (sequenceDepth == 1) {
1306 // If this is the parent node of all the functions, we want to see them
1307 // early, so all call points have actual SPIR-V functions to reference.
1308 // In all cases, still let the traverser visit the children for us.
1309 makeFunctions(node->getAsAggregate()->getSequence());
1310
John Kessenich6fccb3c2016-09-19 16:01:41 -06001311 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001312 // anything else gets there, so visit out of order, doing them all now.
1313 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1314
1315 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1316 // so do them manually.
1317 visitFunctions(node->getAsAggregate()->getSequence());
1318
1319 return false;
1320 }
1321
1322 return true;
1323 }
1324 case glslang::EOpLinkerObjects:
1325 {
1326 if (visit == glslang::EvPreVisit)
1327 linkageOnly = true;
1328 else
1329 linkageOnly = false;
1330
1331 return true;
1332 }
1333 case glslang::EOpComma:
1334 {
1335 // processing from left to right naturally leaves the right-most
1336 // lying around in the access chain
1337 glslang::TIntermSequence& glslangOperands = node->getSequence();
1338 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1339 glslangOperands[i]->traverse(this);
1340
1341 return false;
1342 }
1343 case glslang::EOpFunction:
1344 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001345 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001346 inMain = true;
1347 builder.setBuildPoint(shaderEntry->getLastBlock());
1348 } else {
1349 handleFunctionEntry(node);
1350 }
1351 } else {
1352 if (inMain)
1353 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001354 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001355 inMain = false;
1356 }
1357
1358 return true;
1359 case glslang::EOpParameters:
1360 // Parameters will have been consumed by EOpFunction processing, but not
1361 // the body, so we still visited the function node's children, making this
1362 // child redundant.
1363 return false;
1364 case glslang::EOpFunctionCall:
1365 {
1366 if (node->isUserDefined())
1367 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001368 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1369 if (result) {
1370 builder.clearAccessChain();
1371 builder.setAccessChainRValue(result);
1372 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001373 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001374
1375 return false;
1376 }
1377 case glslang::EOpConstructMat2x2:
1378 case glslang::EOpConstructMat2x3:
1379 case glslang::EOpConstructMat2x4:
1380 case glslang::EOpConstructMat3x2:
1381 case glslang::EOpConstructMat3x3:
1382 case glslang::EOpConstructMat3x4:
1383 case glslang::EOpConstructMat4x2:
1384 case glslang::EOpConstructMat4x3:
1385 case glslang::EOpConstructMat4x4:
1386 case glslang::EOpConstructDMat2x2:
1387 case glslang::EOpConstructDMat2x3:
1388 case glslang::EOpConstructDMat2x4:
1389 case glslang::EOpConstructDMat3x2:
1390 case glslang::EOpConstructDMat3x3:
1391 case glslang::EOpConstructDMat3x4:
1392 case glslang::EOpConstructDMat4x2:
1393 case glslang::EOpConstructDMat4x3:
1394 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001395#ifdef AMD_EXTENSIONS
1396 case glslang::EOpConstructF16Mat2x2:
1397 case glslang::EOpConstructF16Mat2x3:
1398 case glslang::EOpConstructF16Mat2x4:
1399 case glslang::EOpConstructF16Mat3x2:
1400 case glslang::EOpConstructF16Mat3x3:
1401 case glslang::EOpConstructF16Mat3x4:
1402 case glslang::EOpConstructF16Mat4x2:
1403 case glslang::EOpConstructF16Mat4x3:
1404 case glslang::EOpConstructF16Mat4x4:
1405#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001406 isMatrix = true;
1407 // fall through
1408 case glslang::EOpConstructFloat:
1409 case glslang::EOpConstructVec2:
1410 case glslang::EOpConstructVec3:
1411 case glslang::EOpConstructVec4:
1412 case glslang::EOpConstructDouble:
1413 case glslang::EOpConstructDVec2:
1414 case glslang::EOpConstructDVec3:
1415 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001416#ifdef AMD_EXTENSIONS
1417 case glslang::EOpConstructFloat16:
1418 case glslang::EOpConstructF16Vec2:
1419 case glslang::EOpConstructF16Vec3:
1420 case glslang::EOpConstructF16Vec4:
1421#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001422 case glslang::EOpConstructBool:
1423 case glslang::EOpConstructBVec2:
1424 case glslang::EOpConstructBVec3:
1425 case glslang::EOpConstructBVec4:
1426 case glslang::EOpConstructInt:
1427 case glslang::EOpConstructIVec2:
1428 case glslang::EOpConstructIVec3:
1429 case glslang::EOpConstructIVec4:
1430 case glslang::EOpConstructUint:
1431 case glslang::EOpConstructUVec2:
1432 case glslang::EOpConstructUVec3:
1433 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001434 case glslang::EOpConstructInt64:
1435 case glslang::EOpConstructI64Vec2:
1436 case glslang::EOpConstructI64Vec3:
1437 case glslang::EOpConstructI64Vec4:
1438 case glslang::EOpConstructUint64:
1439 case glslang::EOpConstructU64Vec2:
1440 case glslang::EOpConstructU64Vec3:
1441 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001442 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001443 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001444 {
1445 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001446 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001447 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001448 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001449 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001450 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001451 std::vector<spv::Id> constituents;
1452 for (int c = 0; c < (int)arguments.size(); ++c)
1453 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001454 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001455 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001456 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001457 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001458 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001459
1460 builder.clearAccessChain();
1461 builder.setAccessChainRValue(constructed);
1462
1463 return false;
1464 }
1465
1466 // These six are component-wise compares with component-wise results.
1467 // Forward on to createBinaryOperation(), requesting a vector result.
1468 case glslang::EOpLessThan:
1469 case glslang::EOpGreaterThan:
1470 case glslang::EOpLessThanEqual:
1471 case glslang::EOpGreaterThanEqual:
1472 case glslang::EOpVectorEqual:
1473 case glslang::EOpVectorNotEqual:
1474 {
1475 // Map the operation to a binary
1476 binOp = node->getOp();
1477 reduceComparison = false;
1478 switch (node->getOp()) {
1479 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1480 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1481 default: binOp = node->getOp(); break;
1482 }
1483
1484 break;
1485 }
1486 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001487 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001488 binOp = glslang::EOpMul;
1489 break;
1490 case glslang::EOpOuterProduct:
1491 // two vectors multiplied to make a matrix
1492 binOp = glslang::EOpOuterProduct;
1493 break;
1494 case glslang::EOpDot:
1495 {
qining25262b32016-05-06 17:25:16 -04001496 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001497 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001498 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001499 binOp = glslang::EOpMul;
1500 break;
1501 }
1502 case glslang::EOpMod:
1503 // when an aggregate, this is the floating-point mod built-in function,
1504 // which can be emitted by the one in createBinaryOperation()
1505 binOp = glslang::EOpMod;
1506 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001507 case glslang::EOpEmitVertex:
1508 case glslang::EOpEndPrimitive:
1509 case glslang::EOpBarrier:
1510 case glslang::EOpMemoryBarrier:
1511 case glslang::EOpMemoryBarrierAtomicCounter:
1512 case glslang::EOpMemoryBarrierBuffer:
1513 case glslang::EOpMemoryBarrierImage:
1514 case glslang::EOpMemoryBarrierShared:
1515 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001516 case glslang::EOpAllMemoryBarrierWithGroupSync:
1517 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1518 case glslang::EOpWorkgroupMemoryBarrier:
1519 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001520 noReturnValue = true;
1521 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1522 break;
1523
John Kessenich426394d2015-07-23 10:22:48 -06001524 case glslang::EOpAtomicAdd:
1525 case glslang::EOpAtomicMin:
1526 case glslang::EOpAtomicMax:
1527 case glslang::EOpAtomicAnd:
1528 case glslang::EOpAtomicOr:
1529 case glslang::EOpAtomicXor:
1530 case glslang::EOpAtomicExchange:
1531 case glslang::EOpAtomicCompSwap:
1532 atomic = true;
1533 break;
1534
John Kessenich140f3df2015-06-26 16:58:36 -06001535 default:
1536 break;
1537 }
1538
1539 //
1540 // See if it maps to a regular operation.
1541 //
John Kessenich140f3df2015-06-26 16:58:36 -06001542 if (binOp != glslang::EOpNull) {
1543 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1544 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1545 assert(left && right);
1546
1547 builder.clearAccessChain();
1548 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001549 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001550
1551 builder.clearAccessChain();
1552 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001553 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001554
qining25262b32016-05-06 17:25:16 -04001555 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001556 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001557 left->getType().getBasicType(), reduceComparison);
1558
1559 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001560 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 builder.clearAccessChain();
1562 builder.setAccessChainRValue(result);
1563
1564 return false;
1565 }
1566
John Kessenich426394d2015-07-23 10:22:48 -06001567 //
1568 // Create the list of operands.
1569 //
John Kessenich140f3df2015-06-26 16:58:36 -06001570 glslang::TIntermSequence& glslangOperands = node->getSequence();
1571 std::vector<spv::Id> operands;
1572 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001573 // special case l-value operands; there are just a few
1574 bool lvalue = false;
1575 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001576 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001577 case glslang::EOpModf:
1578 if (arg == 1)
1579 lvalue = true;
1580 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001581 case glslang::EOpInterpolateAtSample:
1582 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001583#ifdef AMD_EXTENSIONS
1584 case glslang::EOpInterpolateAtVertex:
1585#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001586 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001587 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001588
1589 // Does it need a swizzle inversion? If so, evaluation is inverted;
1590 // operate first on the swizzle base, then apply the swizzle.
1591 if (glslangOperands[0]->getAsOperator() &&
1592 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1593 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1594 }
Rex Xu7a26c172015-12-08 17:12:09 +08001595 break;
Rex Xud4782c12015-09-06 16:30:11 +08001596 case glslang::EOpAtomicAdd:
1597 case glslang::EOpAtomicMin:
1598 case glslang::EOpAtomicMax:
1599 case glslang::EOpAtomicAnd:
1600 case glslang::EOpAtomicOr:
1601 case glslang::EOpAtomicXor:
1602 case glslang::EOpAtomicExchange:
1603 case glslang::EOpAtomicCompSwap:
1604 if (arg == 0)
1605 lvalue = true;
1606 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001607 case glslang::EOpAddCarry:
1608 case glslang::EOpSubBorrow:
1609 if (arg == 2)
1610 lvalue = true;
1611 break;
1612 case glslang::EOpUMulExtended:
1613 case glslang::EOpIMulExtended:
1614 if (arg >= 2)
1615 lvalue = true;
1616 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001617 default:
1618 break;
1619 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001620 builder.clearAccessChain();
1621 if (invertedType != spv::NoType && arg == 0)
1622 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1623 else
1624 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001625 if (lvalue)
1626 operands.push_back(builder.accessChainGetLValue());
1627 else
John Kessenich32cfd492016-02-02 12:37:46 -07001628 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001629 }
John Kessenich426394d2015-07-23 10:22:48 -06001630
1631 if (atomic) {
1632 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001633 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001634 } else {
1635 // Pass through to generic operations.
1636 switch (glslangOperands.size()) {
1637 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001638 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001639 break;
1640 case 1:
qining25262b32016-05-06 17:25:16 -04001641 result = createUnaryOperation(
1642 node->getOp(), precision,
1643 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001644 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001645 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001646 break;
1647 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001648 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001649 break;
1650 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001651 if (invertedType)
1652 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001653 }
1654
1655 if (noReturnValue)
1656 return false;
1657
1658 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001659 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001660 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001661 } else {
1662 builder.clearAccessChain();
1663 builder.setAccessChainRValue(result);
1664 return false;
1665 }
1666}
1667
1668bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1669{
1670 // This path handles both if-then-else and ?:
1671 // The if-then-else has a node type of void, while
1672 // ?: has a non-void node type
1673 spv::Id result = 0;
1674 if (node->getBasicType() != glslang::EbtVoid) {
1675 // don't handle this as just on-the-fly temporaries, because there will be two names
1676 // and better to leave SSA to later passes
1677 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1678 }
1679
1680 // emit the condition before doing anything with selection
1681 node->getCondition()->traverse(this);
1682
1683 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001684 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001685
1686 if (node->getTrueBlock()) {
1687 // emit the "then" statement
1688 node->getTrueBlock()->traverse(this);
1689 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001690 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001691 }
1692
1693 if (node->getFalseBlock()) {
1694 ifBuilder.makeBeginElse();
1695 // emit the "else" statement
1696 node->getFalseBlock()->traverse(this);
1697 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001698 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001699 }
1700
1701 ifBuilder.makeEndIf();
1702
1703 if (result) {
1704 // GLSL only has r-values as the result of a :?, but
1705 // if we have an l-value, that can be more efficient if it will
1706 // become the base of a complex r-value expression, because the
1707 // next layer copies r-values into memory to use the access-chain mechanism
1708 builder.clearAccessChain();
1709 builder.setAccessChainLValue(result);
1710 }
1711
1712 return false;
1713}
1714
1715bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1716{
1717 // emit and get the condition before doing anything with switch
1718 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001719 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001720
1721 // browse the children to sort out code segments
1722 int defaultSegment = -1;
1723 std::vector<TIntermNode*> codeSegments;
1724 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1725 std::vector<int> caseValues;
1726 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1727 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1728 TIntermNode* child = *c;
1729 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001730 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001731 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001732 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001733 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1734 } else
1735 codeSegments.push_back(child);
1736 }
1737
qining25262b32016-05-06 17:25:16 -04001738 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001739 // statements between the last case and the end of the switch statement
1740 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1741 (int)codeSegments.size() == defaultSegment)
1742 codeSegments.push_back(nullptr);
1743
1744 // make the switch statement
1745 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001746 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001747
1748 // emit all the code in the segments
1749 breakForLoop.push(false);
1750 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1751 builder.nextSwitchSegment(segmentBlocks, s);
1752 if (codeSegments[s])
1753 codeSegments[s]->traverse(this);
1754 else
1755 builder.addSwitchBreak();
1756 }
1757 breakForLoop.pop();
1758
1759 builder.endSwitch(segmentBlocks);
1760
1761 return false;
1762}
1763
1764void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1765{
1766 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001767 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001768
1769 builder.clearAccessChain();
1770 builder.setAccessChainRValue(constant);
1771}
1772
1773bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1774{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001775 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001776 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001777 // Spec requires back edges to target header blocks, and every header block
1778 // must dominate its merge block. Make a header block first to ensure these
1779 // conditions are met. By definition, it will contain OpLoopMerge, followed
1780 // by a block-ending branch. But we don't want to put any other body/test
1781 // instructions in it, since the body/test may have arbitrary instructions,
1782 // including merges of its own.
1783 builder.setBuildPoint(&blocks.head);
1784 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001785 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001786 spv::Block& test = builder.makeNewBlock();
1787 builder.createBranch(&test);
1788
1789 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001790 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001791 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001792 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001793 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1794
1795 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001796 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001797 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001798 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001799 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001800 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001801
1802 builder.setBuildPoint(&blocks.continue_target);
1803 if (node->getTerminal())
1804 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001805 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001806 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001807 builder.createBranch(&blocks.body);
1808
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001809 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001810 builder.setBuildPoint(&blocks.body);
1811 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001812 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001813 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001814 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001815
1816 builder.setBuildPoint(&blocks.continue_target);
1817 if (node->getTerminal())
1818 node->getTerminal()->traverse(this);
1819 if (node->getTest()) {
1820 node->getTest()->traverse(this);
1821 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001822 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001823 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001824 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001825 // TODO: unless there was a break/return/discard instruction
1826 // somewhere in the body, this is an infinite loop, so we should
1827 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001828 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001829 }
John Kessenich140f3df2015-06-26 16:58:36 -06001830 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001831 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001832 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001833 return false;
1834}
1835
1836bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1837{
1838 if (node->getExpression())
1839 node->getExpression()->traverse(this);
1840
1841 switch (node->getFlowOp()) {
1842 case glslang::EOpKill:
1843 builder.makeDiscard();
1844 break;
1845 case glslang::EOpBreak:
1846 if (breakForLoop.top())
1847 builder.createLoopExit();
1848 else
1849 builder.addSwitchBreak();
1850 break;
1851 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001852 builder.createLoopContinue();
1853 break;
1854 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001855 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001856 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001857 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001858 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001859
1860 builder.clearAccessChain();
1861 break;
1862
1863 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001864 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001865 break;
1866 }
1867
1868 return false;
1869}
1870
1871spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1872{
qining25262b32016-05-06 17:25:16 -04001873 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001874 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001875 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001876 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001877 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001878 }
1879
1880 // Now, handle actual variables
1881 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1882 spv::Id spvType = convertGlslangToSpvType(node->getType());
1883
1884 const char* name = node->getName().c_str();
1885 if (glslang::IsAnonymous(name))
1886 name = "";
1887
1888 return builder.createVariable(storageClass, spvType, name);
1889}
1890
1891// Return type Id of the sampled type.
1892spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1893{
1894 switch (sampler.type) {
1895 case glslang::EbtFloat: return builder.makeFloatType(32);
1896 case glslang::EbtInt: return builder.makeIntType(32);
1897 case glslang::EbtUint: return builder.makeUintType(32);
1898 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001899 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001900 return builder.makeFloatType(32);
1901 }
1902}
1903
John Kessenich8c8505c2016-07-26 12:50:38 -06001904// If node is a swizzle operation, return the type that should be used if
1905// the swizzle base is first consumed by another operation, before the swizzle
1906// is applied.
1907spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1908{
1909 if (node.getAsOperator() &&
1910 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1911 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1912 else
1913 return spv::NoType;
1914}
1915
1916// When inverting a swizzle with a parent op, this function
1917// will apply the swizzle operation to a completed parent operation.
1918spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1919{
1920 std::vector<unsigned> swizzle;
1921 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1922 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1923}
1924
John Kessenich8c8505c2016-07-26 12:50:38 -06001925// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1926void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1927{
1928 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1929 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1930 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1931}
1932
John Kessenich3ac051e2015-12-20 11:29:16 -07001933// Convert from a glslang type to an SPV type, by calling into a
1934// recursive version of this function. This establishes the inherited
1935// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001936spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1937{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001938 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001939}
1940
1941// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001942// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001943// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001944spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001945{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001946 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001947
1948 switch (type.getBasicType()) {
1949 case glslang::EbtVoid:
1950 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001951 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001952 break;
1953 case glslang::EbtFloat:
1954 spvType = builder.makeFloatType(32);
1955 break;
1956 case glslang::EbtDouble:
1957 spvType = builder.makeFloatType(64);
1958 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001959#ifdef AMD_EXTENSIONS
1960 case glslang::EbtFloat16:
1961 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
1962 builder.addCapability(spv::CapabilityFloat16);
1963 spvType = builder.makeFloatType(16);
1964 break;
1965#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001966 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001967 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1968 // a 32-bit int where non-0 means true.
1969 if (explicitLayout != glslang::ElpNone)
1970 spvType = builder.makeUintType(32);
1971 else
1972 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001973 break;
1974 case glslang::EbtInt:
1975 spvType = builder.makeIntType(32);
1976 break;
1977 case glslang::EbtUint:
1978 spvType = builder.makeUintType(32);
1979 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001980 case glslang::EbtInt64:
1981 builder.addCapability(spv::CapabilityInt64);
1982 spvType = builder.makeIntType(64);
1983 break;
1984 case glslang::EbtUint64:
1985 builder.addCapability(spv::CapabilityInt64);
1986 spvType = builder.makeUintType(64);
1987 break;
John Kessenich426394d2015-07-23 10:22:48 -06001988 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001989 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001990 spvType = builder.makeUintType(32);
1991 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001992 case glslang::EbtSampler:
1993 {
1994 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001995 if (sampler.sampler) {
1996 // pure sampler
1997 spvType = builder.makeSamplerType();
1998 } else {
1999 // an image is present, make its type
2000 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2001 sampler.image ? 2 : 1, TranslateImageFormat(type));
2002 if (sampler.combined) {
2003 // already has both image and sampler, make the combined type
2004 spvType = builder.makeSampledImageType(spvType);
2005 }
John Kessenich55e7d112015-11-15 21:33:39 -07002006 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002007 }
John Kessenich140f3df2015-06-26 16:58:36 -06002008 break;
2009 case glslang::EbtStruct:
2010 case glslang::EbtBlock:
2011 {
2012 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002013 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002014
2015 // Try to share structs for different layouts, but not yet for other
2016 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002017 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002018 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002019 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002020 break;
2021
2022 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002023 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002024 memberRemapper[glslangMembers].resize(glslangMembers->size());
2025 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002026 }
2027 break;
2028 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002029 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002030 break;
2031 }
2032
2033 if (type.isMatrix())
2034 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2035 else {
2036 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2037 if (type.getVectorSize() > 1)
2038 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2039 }
2040
2041 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002042 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2043
John Kessenichc9a80832015-09-12 12:17:44 -06002044 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002045 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002046 // We need to decorate array strides for types needing explicit layout, except blocks.
2047 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002048 // Use a dummy glslang type for querying internal strides of
2049 // arrays of arrays, but using just a one-dimensional array.
2050 glslang::TType simpleArrayType(type, 0); // deference type of the array
2051 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2052 simpleArrayType.getArraySizes().dereference();
2053
2054 // Will compute the higher-order strides here, rather than making a whole
2055 // pile of types and doing repetitive recursion on their contents.
2056 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2057 }
John Kessenichf8842e52016-01-04 19:22:56 -07002058
2059 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002060 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002061 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002062 if (stride > 0)
2063 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002064 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002065 }
2066 } else {
2067 // single-dimensional array, and don't yet have stride
2068
John Kessenichf8842e52016-01-04 19:22:56 -07002069 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002070 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2071 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002072 }
John Kessenich31ed4832015-09-09 17:51:38 -06002073
John Kessenichc9a80832015-09-12 12:17:44 -06002074 // Do the outer dimension, which might not be known for a runtime-sized array
2075 if (type.isRuntimeSizedArray()) {
2076 spvType = builder.makeRuntimeArray(spvType);
2077 } else {
2078 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002079 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002080 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002081 if (stride > 0)
2082 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002083 }
2084
2085 return spvType;
2086}
2087
John Kessenich6090df02016-06-30 21:18:02 -06002088
2089// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2090// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2091// Mutually recursive with convertGlslangToSpvType().
2092spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2093 const glslang::TTypeList* glslangMembers,
2094 glslang::TLayoutPacking explicitLayout,
2095 const glslang::TQualifier& qualifier)
2096{
2097 // Create a vector of struct types for SPIR-V to consume
2098 std::vector<spv::Id> spvMembers;
2099 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2100 int locationOffset = 0; // for use across struct members, when they are called recursively
2101 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2102 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2103 if (glslangMember.hiddenMember()) {
2104 ++memberDelta;
2105 if (type.getBasicType() == glslang::EbtBlock)
2106 memberRemapper[glslangMembers][i] = -1;
2107 } else {
2108 if (type.getBasicType() == glslang::EbtBlock)
2109 memberRemapper[glslangMembers][i] = i - memberDelta;
2110 // modify just this child's view of the qualifier
2111 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2112 InheritQualifiers(memberQualifier, qualifier);
2113
2114 // manually inherit location; it's more complex
2115 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2116 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2117 if (qualifier.hasLocation())
2118 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2119
2120 // recurse
2121 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2122 }
2123 }
2124
2125 // Make the SPIR-V type
2126 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002127 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002128 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2129
2130 // Decorate it
2131 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2132
2133 return spvType;
2134}
2135
2136void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2137 const glslang::TTypeList* glslangMembers,
2138 glslang::TLayoutPacking explicitLayout,
2139 const glslang::TQualifier& qualifier,
2140 spv::Id spvType)
2141{
2142 // Name and decorate the non-hidden members
2143 int offset = -1;
2144 int locationOffset = 0; // for use within the members of this struct
2145 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2146 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2147 int member = i;
2148 if (type.getBasicType() == glslang::EbtBlock)
2149 member = memberRemapper[glslangMembers][i];
2150
2151 // modify just this child's view of the qualifier
2152 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2153 InheritQualifiers(memberQualifier, qualifier);
2154
2155 // using -1 above to indicate a hidden member
2156 if (member >= 0) {
2157 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2158 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2159 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2160 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2161 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2162 if (type.getBasicType() == glslang::EbtBlock) {
2163 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2164 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2165 }
2166 }
2167 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2168
2169 if (qualifier.storage == glslang::EvqBuffer) {
2170 std::vector<spv::Decoration> memory;
2171 TranslateMemoryDecoration(memberQualifier, memory);
2172 for (unsigned int i = 0; i < memory.size(); ++i)
2173 addMemberDecoration(spvType, member, memory[i]);
2174 }
2175
John Kessenich2f47bc92016-06-30 21:47:35 -06002176 // Compute location decoration; tricky based on whether inheritance is at play and
2177 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002178 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2179 // probably move to the linker stage of the front end proper, and just have the
2180 // answer sitting already distributed throughout the individual member locations.
2181 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002182 // Ignore member locations if the container is an array, as that's
2183 // ill-specified and decisions have been made to not allow this anyway.
2184 // The object itself must have a location, and that comes out from decorating the object,
2185 // not the type (this code decorates types).
2186 if (! type.isArray()) {
2187 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2188 // struct members should not have explicit locations
2189 assert(type.getBasicType() != glslang::EbtStruct);
2190 location = memberQualifier.layoutLocation;
2191 } else if (type.getBasicType() != glslang::EbtBlock) {
2192 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2193 // The members, and their nested types, must not themselves have Location decorations.
2194 } else if (qualifier.hasLocation()) // inheritance
2195 location = qualifier.layoutLocation + locationOffset;
2196 }
John Kessenich6090df02016-06-30 21:18:02 -06002197 if (location >= 0)
2198 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2199
John Kessenich2f47bc92016-06-30 21:47:35 -06002200 if (qualifier.hasLocation()) // track for upcoming inheritance
2201 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2202
John Kessenich6090df02016-06-30 21:18:02 -06002203 // component, XFB, others
2204 if (glslangMember.getQualifier().hasComponent())
2205 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2206 if (glslangMember.getQualifier().hasXfbOffset())
2207 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2208 else if (explicitLayout != glslang::ElpNone) {
2209 // figure out what to do with offset, which is accumulating
2210 int nextOffset;
2211 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2212 if (offset >= 0)
2213 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2214 offset = nextOffset;
2215 }
2216
2217 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2218 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2219
2220 // built-in variable decorations
2221 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002222 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002223 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2224 }
2225 }
2226
2227 // Decorate the structure
2228 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2229 addDecoration(spvType, TranslateBlockDecoration(type));
2230 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2231 builder.addCapability(spv::CapabilityGeometryStreams);
2232 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2233 }
2234 if (glslangIntermediate->getXfbMode()) {
2235 builder.addCapability(spv::CapabilityTransformFeedback);
2236 if (type.getQualifier().hasXfbStride())
2237 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2238 if (type.getQualifier().hasXfbBuffer())
2239 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2240 }
2241}
2242
John Kessenich6c292d32016-02-15 20:58:50 -07002243// Turn the expression forming the array size into an id.
2244// This is not quite trivial, because of specialization constants.
2245// Sometimes, a raw constant is turned into an Id, and sometimes
2246// a specialization constant expression is.
2247spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2248{
2249 // First, see if this is sized with a node, meaning a specialization constant:
2250 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2251 if (specNode != nullptr) {
2252 builder.clearAccessChain();
2253 specNode->traverse(this);
2254 return accessChainLoad(specNode->getAsTyped()->getType());
2255 }
qining25262b32016-05-06 17:25:16 -04002256
John Kessenich6c292d32016-02-15 20:58:50 -07002257 // Otherwise, need a compile-time (front end) size, get it:
2258 int size = arraySizes.getDimSize(dim);
2259 assert(size > 0);
2260 return builder.makeUintConstant(size);
2261}
2262
John Kessenich103bef92016-02-08 21:38:15 -07002263// Wrap the builder's accessChainLoad to:
2264// - localize handling of RelaxedPrecision
2265// - use the SPIR-V inferred type instead of another conversion of the glslang type
2266// (avoids unnecessary work and possible type punning for structures)
2267// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002268spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2269{
John Kessenich103bef92016-02-08 21:38:15 -07002270 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2271 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2272
2273 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002274 if (type.getBasicType() == glslang::EbtBool) {
2275 if (builder.isScalarType(nominalTypeId)) {
2276 // Conversion for bool
2277 spv::Id boolType = builder.makeBoolType();
2278 if (nominalTypeId != boolType)
2279 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2280 } else if (builder.isVectorType(nominalTypeId)) {
2281 // Conversion for bvec
2282 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2283 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2284 if (nominalTypeId != bvecType)
2285 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2286 }
2287 }
John Kessenich103bef92016-02-08 21:38:15 -07002288
2289 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002290}
2291
Rex Xu27253232016-02-23 17:51:09 +08002292// Wrap the builder's accessChainStore to:
2293// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002294//
2295// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002296void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2297{
2298 // Need to convert to abstract types when necessary
2299 if (type.getBasicType() == glslang::EbtBool) {
2300 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2301
2302 if (builder.isScalarType(nominalTypeId)) {
2303 // Conversion for bool
2304 spv::Id boolType = builder.makeBoolType();
2305 if (nominalTypeId != boolType) {
2306 spv::Id zero = builder.makeUintConstant(0);
2307 spv::Id one = builder.makeUintConstant(1);
2308 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2309 }
2310 } else if (builder.isVectorType(nominalTypeId)) {
2311 // Conversion for bvec
2312 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2313 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2314 if (nominalTypeId != bvecType) {
2315 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2316 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2317 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2318 }
2319 }
2320 }
2321
2322 builder.accessChainStore(rvalue);
2323}
2324
John Kessenich4bf71552016-09-02 11:20:21 -06002325// For storing when types match at the glslang level, but not might match at the
2326// SPIR-V level.
2327//
2328// This especially happens when a single glslang type expands to multiple
2329// SPIR-V types, like a struct that is used in an member-undecorated way as well
2330// as in a member-decorated way.
2331//
2332// NOTE: This function can handle any store request; if it's not special it
2333// simplifies to a simple OpStore.
2334//
2335// Implicitly uses the existing builder.accessChain as the storage target.
2336void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2337{
John Kessenichb3e24e42016-09-11 12:33:43 -06002338 // we only do the complex path here if it's an aggregate
2339 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002340 accessChainStore(type, rValue);
2341 return;
2342 }
2343
John Kessenichb3e24e42016-09-11 12:33:43 -06002344 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002345 spv::Id rType = builder.getTypeId(rValue);
2346 spv::Id lValue = builder.accessChainGetLValue();
2347 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2348 if (lType == rType) {
2349 accessChainStore(type, rValue);
2350 return;
2351 }
2352
John Kessenichb3e24e42016-09-11 12:33:43 -06002353 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002354 // where the two types were the same type in GLSL. This requires member
2355 // by member copy, recursively.
2356
John Kessenichb3e24e42016-09-11 12:33:43 -06002357 // If an array, copy element by element.
2358 if (type.isArray()) {
2359 glslang::TType glslangElementType(type, 0);
2360 spv::Id elementRType = builder.getContainedTypeId(rType);
2361 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2362 // get the source member
2363 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002364
John Kessenichb3e24e42016-09-11 12:33:43 -06002365 // set up the target storage
2366 builder.clearAccessChain();
2367 builder.setAccessChainLValue(lValue);
2368 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002369
John Kessenichb3e24e42016-09-11 12:33:43 -06002370 // store the member
2371 multiTypeStore(glslangElementType, elementRValue);
2372 }
2373 } else {
2374 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002375
John Kessenichb3e24e42016-09-11 12:33:43 -06002376 // loop over structure members
2377 const glslang::TTypeList& members = *type.getStruct();
2378 for (int m = 0; m < (int)members.size(); ++m) {
2379 const glslang::TType& glslangMemberType = *members[m].type;
2380
2381 // get the source member
2382 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2383 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2384
2385 // set up the target storage
2386 builder.clearAccessChain();
2387 builder.setAccessChainLValue(lValue);
2388 builder.accessChainPush(builder.makeIntConstant(m));
2389
2390 // store the member
2391 multiTypeStore(glslangMemberType, memberRValue);
2392 }
John Kessenich4bf71552016-09-02 11:20:21 -06002393 }
2394}
2395
John Kessenichf85e8062015-12-19 13:57:10 -07002396// Decide whether or not this type should be
2397// decorated with offsets and strides, and if so
2398// whether std140 or std430 rules should be applied.
2399glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002400{
John Kessenichf85e8062015-12-19 13:57:10 -07002401 // has to be a block
2402 if (type.getBasicType() != glslang::EbtBlock)
2403 return glslang::ElpNone;
2404
2405 // has to be a uniform or buffer block
2406 if (type.getQualifier().storage != glslang::EvqUniform &&
2407 type.getQualifier().storage != glslang::EvqBuffer)
2408 return glslang::ElpNone;
2409
2410 // return the layout to use
2411 switch (type.getQualifier().layoutPacking) {
2412 case glslang::ElpStd140:
2413 case glslang::ElpStd430:
2414 return type.getQualifier().layoutPacking;
2415 default:
2416 return glslang::ElpNone;
2417 }
John Kessenich31ed4832015-09-09 17:51:38 -06002418}
2419
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002420// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002421int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002422{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002423 int size;
John Kessenich49987892015-12-29 17:11:44 -07002424 int stride;
2425 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002426
2427 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002428}
2429
John Kessenich49987892015-12-29 17:11:44 -07002430// 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 -07002431// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002432int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002433{
John Kessenich49987892015-12-29 17:11:44 -07002434 glslang::TType elementType;
2435 elementType.shallowCopy(matrixType);
2436 elementType.clearArraySizes();
2437
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002438 int size;
John Kessenich49987892015-12-29 17:11:44 -07002439 int stride;
2440 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2441
2442 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002443}
2444
John Kessenich5e4b1242015-08-06 22:53:06 -06002445// Given a member type of a struct, realign the current offset for it, and compute
2446// the next (not yet aligned) offset for the next member, which will get aligned
2447// on the next call.
2448// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2449// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2450// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002451void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002452 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002453{
2454 // this will get a positive value when deemed necessary
2455 nextOffset = -1;
2456
John Kessenich5e4b1242015-08-06 22:53:06 -06002457 // override anything in currentOffset with user-set offset
2458 if (memberType.getQualifier().hasOffset())
2459 currentOffset = memberType.getQualifier().layoutOffset;
2460
2461 // It could be that current linker usage in glslang updated all the layoutOffset,
2462 // in which case the following code does not matter. But, that's not quite right
2463 // once cross-compilation unit GLSL validation is done, as the original user
2464 // settings are needed in layoutOffset, and then the following will come into play.
2465
John Kessenichf85e8062015-12-19 13:57:10 -07002466 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002467 if (! memberType.getQualifier().hasOffset())
2468 currentOffset = -1;
2469
2470 return;
2471 }
2472
John Kessenichf85e8062015-12-19 13:57:10 -07002473 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002474 if (currentOffset < 0)
2475 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002476
John Kessenich5e4b1242015-08-06 22:53:06 -06002477 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2478 // but possibly not yet correctly aligned.
2479
2480 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002481 int dummyStride;
2482 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002483 glslang::RoundToPow2(currentOffset, memberAlignment);
2484 nextOffset = currentOffset + memberSize;
2485}
2486
David Netoa901ffe2016-06-08 14:11:40 +01002487void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002488{
David Netoa901ffe2016-06-08 14:11:40 +01002489 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2490 switch (glslangBuiltIn)
2491 {
2492 case glslang::EbvClipDistance:
2493 case glslang::EbvCullDistance:
2494 case glslang::EbvPointSize:
2495 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2496 // Alternately, we could just call this for any glslang built-in, since the
2497 // capability already guards against duplicates.
2498 TranslateBuiltInDecoration(glslangBuiltIn, false);
2499 break;
2500 default:
2501 // Capabilities were already generated when the struct was declared.
2502 break;
2503 }
John Kessenichebb50532016-05-16 19:22:05 -06002504}
2505
John Kessenich6fccb3c2016-09-19 16:01:41 -06002506bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002507{
John Kessenicheee9d532016-09-19 18:09:30 -06002508 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002509}
2510
2511// Make all the functions, skeletally, without actually visiting their bodies.
2512void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2513{
2514 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2515 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002516 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002517 continue;
2518
2519 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002520 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002521 //
qining25262b32016-05-06 17:25:16 -04002522 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002523 // function. What it is an address of varies:
2524 //
John Kessenich4bf71552016-09-02 11:20:21 -06002525 // - "in" parameters not marked as "const" can be written to without modifying the calling
2526 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002527 //
2528 // - "const in" parameters can just be the r-value, as no writes need occur.
2529 //
John Kessenich4bf71552016-09-02 11:20:21 -06002530 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2531 // 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 -06002532
2533 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002534 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2536
2537 for (int p = 0; p < (int)parameters.size(); ++p) {
2538 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2539 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002540 if (paramType.isOpaque())
2541 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2542 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002543 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2544 else
John Kessenich4bf71552016-09-02 11:20:21 -06002545 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002546 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002547 paramTypes.push_back(typeId);
2548 }
2549
2550 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002551 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2552 convertGlslangToSpvType(glslFunction->getType()),
2553 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002554
2555 // Track function to emit/call later
2556 functionMap[glslFunction->getName().c_str()] = function;
2557
2558 // Set the parameter id's
2559 for (int p = 0; p < (int)parameters.size(); ++p) {
2560 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2561 // give a name too
2562 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2563 }
2564 }
2565}
2566
2567// Process all the initializers, while skipping the functions and link objects
2568void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2569{
2570 builder.setBuildPoint(shaderEntry->getLastBlock());
2571 for (int i = 0; i < (int)initializers.size(); ++i) {
2572 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2573 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2574
2575 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002576 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002577 initializer->traverse(this);
2578 }
2579 }
2580}
2581
2582// Process all the functions, while skipping initializers.
2583void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2584{
2585 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2586 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2587 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2588 node->traverse(this);
2589 }
2590}
2591
2592void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2593{
qining25262b32016-05-06 17:25:16 -04002594 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002595 // that called makeFunctions().
2596 spv::Function* function = functionMap[node->getName().c_str()];
2597 spv::Block* functionBlock = function->getEntryBlock();
2598 builder.setBuildPoint(functionBlock);
2599}
2600
Rex Xu04db3f52015-09-16 11:44:02 +08002601void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002602{
Rex Xufc618912015-09-09 16:42:49 +08002603 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002604
2605 glslang::TSampler sampler = {};
2606 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002607 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002608 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2609 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2610 }
2611
John Kessenich140f3df2015-06-26 16:58:36 -06002612 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2613 builder.clearAccessChain();
2614 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002615
2616 // Special case l-value operands
2617 bool lvalue = false;
2618 switch (node.getOp()) {
2619 case glslang::EOpImageAtomicAdd:
2620 case glslang::EOpImageAtomicMin:
2621 case glslang::EOpImageAtomicMax:
2622 case glslang::EOpImageAtomicAnd:
2623 case glslang::EOpImageAtomicOr:
2624 case glslang::EOpImageAtomicXor:
2625 case glslang::EOpImageAtomicExchange:
2626 case glslang::EOpImageAtomicCompSwap:
2627 if (i == 0)
2628 lvalue = true;
2629 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002630 case glslang::EOpSparseImageLoad:
2631 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2632 lvalue = true;
2633 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002634 case glslang::EOpSparseTexture:
2635 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2636 lvalue = true;
2637 break;
2638 case glslang::EOpSparseTextureClamp:
2639 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2640 lvalue = true;
2641 break;
2642 case glslang::EOpSparseTextureLod:
2643 case glslang::EOpSparseTextureOffset:
2644 if (i == 3)
2645 lvalue = true;
2646 break;
2647 case glslang::EOpSparseTextureFetch:
2648 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2649 lvalue = true;
2650 break;
2651 case glslang::EOpSparseTextureFetchOffset:
2652 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2653 lvalue = true;
2654 break;
2655 case glslang::EOpSparseTextureLodOffset:
2656 case glslang::EOpSparseTextureGrad:
2657 case glslang::EOpSparseTextureOffsetClamp:
2658 if (i == 4)
2659 lvalue = true;
2660 break;
2661 case glslang::EOpSparseTextureGradOffset:
2662 case glslang::EOpSparseTextureGradClamp:
2663 if (i == 5)
2664 lvalue = true;
2665 break;
2666 case glslang::EOpSparseTextureGradOffsetClamp:
2667 if (i == 6)
2668 lvalue = true;
2669 break;
2670 case glslang::EOpSparseTextureGather:
2671 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2672 lvalue = true;
2673 break;
2674 case glslang::EOpSparseTextureGatherOffset:
2675 case glslang::EOpSparseTextureGatherOffsets:
2676 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2677 lvalue = true;
2678 break;
Rex Xufc618912015-09-09 16:42:49 +08002679 default:
2680 break;
2681 }
2682
Rex Xu6b86d492015-09-16 17:48:22 +08002683 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002684 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002685 else
John Kessenich32cfd492016-02-02 12:37:46 -07002686 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002687 }
2688}
2689
John Kessenichfc51d282015-08-19 13:34:18 -06002690void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002691{
John Kessenichfc51d282015-08-19 13:34:18 -06002692 builder.clearAccessChain();
2693 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002694 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002695}
John Kessenich140f3df2015-06-26 16:58:36 -06002696
John Kessenichfc51d282015-08-19 13:34:18 -06002697spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2698{
Rex Xufc618912015-09-09 16:42:49 +08002699 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002700 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002701 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002702 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002703
John Kessenichfc51d282015-08-19 13:34:18 -06002704 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002705 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2706 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2707 std::vector<spv::Id> arguments;
2708 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002709 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002710 else
2711 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002712 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002713
2714 spv::Builder::TextureParameters params = { };
2715 params.sampler = arguments[0];
2716
Rex Xu04db3f52015-09-16 11:44:02 +08002717 glslang::TCrackedTextureOp cracked;
2718 node->crackTexture(sampler, cracked);
2719
John Kessenichfc51d282015-08-19 13:34:18 -06002720 // Check for queries
2721 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002722 // a sampled image needs to have the image extracted first
2723 if (builder.isSampledImage(params.sampler))
2724 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002725 switch (node->getOp()) {
2726 case glslang::EOpImageQuerySize:
2727 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002728 if (arguments.size() > 1) {
2729 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002730 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002731 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002732 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002733 case glslang::EOpImageQuerySamples:
2734 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002735 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002736 case glslang::EOpTextureQueryLod:
2737 params.coords = arguments[1];
2738 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2739 case glslang::EOpTextureQueryLevels:
2740 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002741 case glslang::EOpSparseTexelsResident:
2742 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002743 default:
2744 assert(0);
2745 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002746 }
John Kessenich140f3df2015-06-26 16:58:36 -06002747 }
2748
Rex Xufc618912015-09-09 16:42:49 +08002749 // Check for image functions other than queries
2750 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002751 std::vector<spv::Id> operands;
2752 auto opIt = arguments.begin();
2753 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002754
2755 // Handle subpass operations
2756 // TODO: GLSL should change to have the "MS" only on the type rather than the
2757 // built-in function.
2758 if (cracked.subpass) {
2759 // add on the (0,0) coordinate
2760 spv::Id zero = builder.makeIntConstant(0);
2761 std::vector<spv::Id> comps;
2762 comps.push_back(zero);
2763 comps.push_back(zero);
2764 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2765 if (sampler.ms) {
2766 operands.push_back(spv::ImageOperandsSampleMask);
2767 operands.push_back(*(opIt++));
2768 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002769 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002770 }
2771
John Kessenich56bab042015-09-16 10:54:31 -06002772 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002773 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002774 if (sampler.ms) {
2775 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002776 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002777 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002778 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2779 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002780 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002781 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002782 if (sampler.ms) {
2783 operands.push_back(*(opIt + 1));
2784 operands.push_back(spv::ImageOperandsSampleMask);
2785 operands.push_back(*opIt);
2786 } else
2787 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002788 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002789 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2790 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002791 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002792 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2793 builder.addCapability(spv::CapabilitySparseResidency);
2794 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2795 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2796
2797 if (sampler.ms) {
2798 operands.push_back(spv::ImageOperandsSampleMask);
2799 operands.push_back(*opIt++);
2800 }
2801
2802 // Create the return type that was a special structure
2803 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002804 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002805 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2806 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2807
2808 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2809
2810 // Decode the return type
2811 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2812 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002813 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002814 // Process image atomic operations
2815
2816 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2817 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002818 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002819
John Kessenich8c8505c2016-07-26 12:50:38 -06002820 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002821 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002822
2823 std::vector<spv::Id> operands;
2824 operands.push_back(pointer);
2825 for (; opIt != arguments.end(); ++opIt)
2826 operands.push_back(*opIt);
2827
John Kessenich8c8505c2016-07-26 12:50:38 -06002828 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002829 }
2830 }
2831
2832 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002833 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002834 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2835
John Kessenichfc51d282015-08-19 13:34:18 -06002836 // check for bias argument
2837 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002838 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002839 int nonBiasArgCount = 2;
2840 if (cracked.offset)
2841 ++nonBiasArgCount;
2842 if (cracked.grad)
2843 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002844 if (cracked.lodClamp)
2845 ++nonBiasArgCount;
2846 if (sparse)
2847 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002848
2849 if ((int)arguments.size() > nonBiasArgCount)
2850 bias = true;
2851 }
2852
John Kessenicha5c33d62016-06-02 23:45:21 -06002853 // See if the sampler param should really be just the SPV image part
2854 if (cracked.fetch) {
2855 // a fetch needs to have the image extracted first
2856 if (builder.isSampledImage(params.sampler))
2857 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2858 }
2859
John Kessenichfc51d282015-08-19 13:34:18 -06002860 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002861
John Kessenichfc51d282015-08-19 13:34:18 -06002862 params.coords = arguments[1];
2863 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002864 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002865
2866 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002867 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002868 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002869 ++extraArgs;
2870 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002871 params.Dref = arguments[2];
2872 ++extraArgs;
2873 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002874 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002875 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002876 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002877 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002878 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002879 dRefComp = builder.getNumComponents(params.coords) - 1;
2880 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002881 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2882 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002883
2884 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002885 if (cracked.lod) {
2886 params.lod = arguments[2];
2887 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002888 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2889 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2890 noImplicitLod = true;
2891 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002892
2893 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002894 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002895 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002896 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002897 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002898
2899 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002900 if (cracked.grad) {
2901 params.gradX = arguments[2 + extraArgs];
2902 params.gradY = arguments[3 + extraArgs];
2903 extraArgs += 2;
2904 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002905
2906 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002907 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002908 params.offset = arguments[2 + extraArgs];
2909 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002910 } else if (cracked.offsets) {
2911 params.offsets = arguments[2 + extraArgs];
2912 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002913 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002914
2915 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002916 if (cracked.lodClamp) {
2917 params.lodClamp = arguments[2 + extraArgs];
2918 ++extraArgs;
2919 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002920
2921 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002922 if (sparse) {
2923 params.texelOut = arguments[2 + extraArgs];
2924 ++extraArgs;
2925 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002926
2927 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002928 if (bias) {
2929 params.bias = arguments[2 + extraArgs];
2930 ++extraArgs;
2931 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002932
2933 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002934 if (cracked.gather && ! sampler.shadow) {
2935 // default component is 0, if missing, otherwise an argument
2936 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002937 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002938 ++extraArgs;
2939 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002940 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002941 }
2942 }
John Kessenichfc51d282015-08-19 13:34:18 -06002943
John Kessenich65336482016-06-16 14:06:26 -06002944 // projective component (might not to move)
2945 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2946 // are divided by the last component of P."
2947 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2948 // unused components will appear after all used components."
2949 if (cracked.proj) {
2950 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2951 int projTargetComp;
2952 switch (sampler.dim) {
2953 case glslang::Esd1D: projTargetComp = 1; break;
2954 case glslang::Esd2D: projTargetComp = 2; break;
2955 case glslang::EsdRect: projTargetComp = 2; break;
2956 default: projTargetComp = projSourceComp; break;
2957 }
2958 // copy the projective coordinate if we have to
2959 if (projTargetComp != projSourceComp) {
2960 spv::Id projComp = builder.createCompositeExtract(params.coords,
2961 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2962 projSourceComp);
2963 params.coords = builder.createCompositeInsert(projComp, params.coords,
2964 builder.getTypeId(params.coords), projTargetComp);
2965 }
2966 }
2967
John Kessenich8c8505c2016-07-26 12:50:38 -06002968 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002969}
2970
2971spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2972{
2973 // Grab the function's pointer from the previously created function
2974 spv::Function* function = functionMap[node->getName().c_str()];
2975 if (! function)
2976 return 0;
2977
2978 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2979 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2980
2981 // See comments in makeFunctions() for details about the semantics for parameter passing.
2982 //
2983 // These imply we need a four step process:
2984 // 1. Evaluate the arguments
2985 // 2. Allocate and make copies of in, out, and inout arguments
2986 // 3. Make the call
2987 // 4. Copy back the results
2988
2989 // 1. Evaluate the arguments
2990 std::vector<spv::Builder::AccessChain> lValues;
2991 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002992 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002994 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002995 // build l-value
2996 builder.clearAccessChain();
2997 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002998 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002999 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003000 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003001 // save l-value
3002 lValues.push_back(builder.getAccessChain());
3003 } else {
3004 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003005 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003006 }
3007 }
3008
3009 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3010 // copy the original into that space.
3011 //
3012 // Also, build up the list of actual arguments to pass in for the call
3013 int lValueCount = 0;
3014 int rValueCount = 0;
3015 std::vector<spv::Id> spvArgs;
3016 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003017 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003018 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003019 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003020 builder.setAccessChain(lValues[lValueCount]);
3021 arg = builder.accessChainGetLValue();
3022 ++lValueCount;
3023 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003024 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003025 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3026 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3027 // need to copy the input into output space
3028 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003029 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003030 builder.clearAccessChain();
3031 builder.setAccessChainLValue(arg);
3032 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003033 }
3034 ++lValueCount;
3035 } else {
3036 arg = rValues[rValueCount];
3037 ++rValueCount;
3038 }
3039 spvArgs.push_back(arg);
3040 }
3041
3042 // 3. Make the call.
3043 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003044 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003045
3046 // 4. Copy back out an "out" arguments.
3047 lValueCount = 0;
3048 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003049 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003050 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3051 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3052 spv::Id copy = builder.createLoad(spvArgs[a]);
3053 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003054 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003055 }
3056 ++lValueCount;
3057 }
3058 }
3059
3060 return result;
3061}
3062
3063// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003064spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3065 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003066 spv::Id typeId, spv::Id left, spv::Id right,
3067 glslang::TBasicType typeProxy, bool reduceComparison)
3068{
Rex Xu8ff43de2016-04-22 16:51:45 +08003069 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003070#ifdef AMD_EXTENSIONS
3071 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3072#else
John Kessenich140f3df2015-06-26 16:58:36 -06003073 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003074#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003075 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003076
3077 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003078 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003079 bool comparison = false;
3080
3081 switch (op) {
3082 case glslang::EOpAdd:
3083 case glslang::EOpAddAssign:
3084 if (isFloat)
3085 binOp = spv::OpFAdd;
3086 else
3087 binOp = spv::OpIAdd;
3088 break;
3089 case glslang::EOpSub:
3090 case glslang::EOpSubAssign:
3091 if (isFloat)
3092 binOp = spv::OpFSub;
3093 else
3094 binOp = spv::OpISub;
3095 break;
3096 case glslang::EOpMul:
3097 case glslang::EOpMulAssign:
3098 if (isFloat)
3099 binOp = spv::OpFMul;
3100 else
3101 binOp = spv::OpIMul;
3102 break;
3103 case glslang::EOpVectorTimesScalar:
3104 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003105 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003106 if (builder.isVector(right))
3107 std::swap(left, right);
3108 assert(builder.isScalar(right));
3109 needMatchingVectors = false;
3110 binOp = spv::OpVectorTimesScalar;
3111 } else
3112 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003113 break;
3114 case glslang::EOpVectorTimesMatrix:
3115 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003116 binOp = spv::OpVectorTimesMatrix;
3117 break;
3118 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003119 binOp = spv::OpMatrixTimesVector;
3120 break;
3121 case glslang::EOpMatrixTimesScalar:
3122 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003123 binOp = spv::OpMatrixTimesScalar;
3124 break;
3125 case glslang::EOpMatrixTimesMatrix:
3126 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003127 binOp = spv::OpMatrixTimesMatrix;
3128 break;
3129 case glslang::EOpOuterProduct:
3130 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003131 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003132 break;
3133
3134 case glslang::EOpDiv:
3135 case glslang::EOpDivAssign:
3136 if (isFloat)
3137 binOp = spv::OpFDiv;
3138 else if (isUnsigned)
3139 binOp = spv::OpUDiv;
3140 else
3141 binOp = spv::OpSDiv;
3142 break;
3143 case glslang::EOpMod:
3144 case glslang::EOpModAssign:
3145 if (isFloat)
3146 binOp = spv::OpFMod;
3147 else if (isUnsigned)
3148 binOp = spv::OpUMod;
3149 else
3150 binOp = spv::OpSMod;
3151 break;
3152 case glslang::EOpRightShift:
3153 case glslang::EOpRightShiftAssign:
3154 if (isUnsigned)
3155 binOp = spv::OpShiftRightLogical;
3156 else
3157 binOp = spv::OpShiftRightArithmetic;
3158 break;
3159 case glslang::EOpLeftShift:
3160 case glslang::EOpLeftShiftAssign:
3161 binOp = spv::OpShiftLeftLogical;
3162 break;
3163 case glslang::EOpAnd:
3164 case glslang::EOpAndAssign:
3165 binOp = spv::OpBitwiseAnd;
3166 break;
3167 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003168 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003169 binOp = spv::OpLogicalAnd;
3170 break;
3171 case glslang::EOpInclusiveOr:
3172 case glslang::EOpInclusiveOrAssign:
3173 binOp = spv::OpBitwiseOr;
3174 break;
3175 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003176 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003177 binOp = spv::OpLogicalOr;
3178 break;
3179 case glslang::EOpExclusiveOr:
3180 case glslang::EOpExclusiveOrAssign:
3181 binOp = spv::OpBitwiseXor;
3182 break;
3183 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003184 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003185 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003186 break;
3187
3188 case glslang::EOpLessThan:
3189 case glslang::EOpGreaterThan:
3190 case glslang::EOpLessThanEqual:
3191 case glslang::EOpGreaterThanEqual:
3192 case glslang::EOpEqual:
3193 case glslang::EOpNotEqual:
3194 case glslang::EOpVectorEqual:
3195 case glslang::EOpVectorNotEqual:
3196 comparison = true;
3197 break;
3198 default:
3199 break;
3200 }
3201
John Kessenich7c1aa102015-10-15 13:29:11 -06003202 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003203 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003204 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003205 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003206 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003207
3208 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003209 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003210 builder.promoteScalar(precision, left, right);
3211
qining25262b32016-05-06 17:25:16 -04003212 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3213 addDecoration(result, noContraction);
3214 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003215 }
3216
3217 if (! comparison)
3218 return 0;
3219
John Kessenich7c1aa102015-10-15 13:29:11 -06003220 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003221
John Kessenich4583b612016-08-07 19:14:22 -06003222 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3223 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003224 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003225
3226 switch (op) {
3227 case glslang::EOpLessThan:
3228 if (isFloat)
3229 binOp = spv::OpFOrdLessThan;
3230 else if (isUnsigned)
3231 binOp = spv::OpULessThan;
3232 else
3233 binOp = spv::OpSLessThan;
3234 break;
3235 case glslang::EOpGreaterThan:
3236 if (isFloat)
3237 binOp = spv::OpFOrdGreaterThan;
3238 else if (isUnsigned)
3239 binOp = spv::OpUGreaterThan;
3240 else
3241 binOp = spv::OpSGreaterThan;
3242 break;
3243 case glslang::EOpLessThanEqual:
3244 if (isFloat)
3245 binOp = spv::OpFOrdLessThanEqual;
3246 else if (isUnsigned)
3247 binOp = spv::OpULessThanEqual;
3248 else
3249 binOp = spv::OpSLessThanEqual;
3250 break;
3251 case glslang::EOpGreaterThanEqual:
3252 if (isFloat)
3253 binOp = spv::OpFOrdGreaterThanEqual;
3254 else if (isUnsigned)
3255 binOp = spv::OpUGreaterThanEqual;
3256 else
3257 binOp = spv::OpSGreaterThanEqual;
3258 break;
3259 case glslang::EOpEqual:
3260 case glslang::EOpVectorEqual:
3261 if (isFloat)
3262 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003263 else if (isBool)
3264 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003265 else
3266 binOp = spv::OpIEqual;
3267 break;
3268 case glslang::EOpNotEqual:
3269 case glslang::EOpVectorNotEqual:
3270 if (isFloat)
3271 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003272 else if (isBool)
3273 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003274 else
3275 binOp = spv::OpINotEqual;
3276 break;
3277 default:
3278 break;
3279 }
3280
qining25262b32016-05-06 17:25:16 -04003281 if (binOp != spv::OpNop) {
3282 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3283 addDecoration(result, noContraction);
3284 return builder.setPrecision(result, precision);
3285 }
John Kessenich140f3df2015-06-26 16:58:36 -06003286
3287 return 0;
3288}
3289
John Kessenich04bb8a02015-12-12 12:28:14 -07003290//
3291// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3292// These can be any of:
3293//
3294// matrix * scalar
3295// scalar * matrix
3296// matrix * matrix linear algebraic
3297// matrix * vector
3298// vector * matrix
3299// matrix * matrix componentwise
3300// matrix op matrix op in {+, -, /}
3301// matrix op scalar op in {+, -, /}
3302// scalar op matrix op in {+, -, /}
3303//
qining25262b32016-05-06 17:25:16 -04003304spv::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 -07003305{
3306 bool firstClass = true;
3307
3308 // First, handle first-class matrix operations (* and matrix/scalar)
3309 switch (op) {
3310 case spv::OpFDiv:
3311 if (builder.isMatrix(left) && builder.isScalar(right)) {
3312 // turn matrix / scalar into a multiply...
3313 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3314 op = spv::OpMatrixTimesScalar;
3315 } else
3316 firstClass = false;
3317 break;
3318 case spv::OpMatrixTimesScalar:
3319 if (builder.isMatrix(right))
3320 std::swap(left, right);
3321 assert(builder.isScalar(right));
3322 break;
3323 case spv::OpVectorTimesMatrix:
3324 assert(builder.isVector(left));
3325 assert(builder.isMatrix(right));
3326 break;
3327 case spv::OpMatrixTimesVector:
3328 assert(builder.isMatrix(left));
3329 assert(builder.isVector(right));
3330 break;
3331 case spv::OpMatrixTimesMatrix:
3332 assert(builder.isMatrix(left));
3333 assert(builder.isMatrix(right));
3334 break;
3335 default:
3336 firstClass = false;
3337 break;
3338 }
3339
qining25262b32016-05-06 17:25:16 -04003340 if (firstClass) {
3341 spv::Id result = builder.createBinOp(op, typeId, left, right);
3342 addDecoration(result, noContraction);
3343 return builder.setPrecision(result, precision);
3344 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003345
LoopDawg592860c2016-06-09 08:57:35 -06003346 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003347 // The result type of all of them is the same type as the (a) matrix operand.
3348 // The algorithm is to:
3349 // - break the matrix(es) into vectors
3350 // - smear any scalar to a vector
3351 // - do vector operations
3352 // - make a matrix out the vector results
3353 switch (op) {
3354 case spv::OpFAdd:
3355 case spv::OpFSub:
3356 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003357 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003358 case spv::OpFMul:
3359 {
3360 // one time set up...
3361 bool leftMat = builder.isMatrix(left);
3362 bool rightMat = builder.isMatrix(right);
3363 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3364 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3365 spv::Id scalarType = builder.getScalarTypeId(typeId);
3366 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3367 std::vector<spv::Id> results;
3368 spv::Id smearVec = spv::NoResult;
3369 if (builder.isScalar(left))
3370 smearVec = builder.smearScalar(precision, left, vecType);
3371 else if (builder.isScalar(right))
3372 smearVec = builder.smearScalar(precision, right, vecType);
3373
3374 // do each vector op
3375 for (unsigned int c = 0; c < numCols; ++c) {
3376 std::vector<unsigned int> indexes;
3377 indexes.push_back(c);
3378 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3379 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003380 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3381 addDecoration(result, noContraction);
3382 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003383 }
3384
3385 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003386 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003387 }
3388 default:
3389 assert(0);
3390 return spv::NoResult;
3391 }
3392}
3393
qining25262b32016-05-06 17:25:16 -04003394spv::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 -06003395{
3396 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003397 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003398 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003399 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003400#ifdef AMD_EXTENSIONS
3401 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3402#else
Rex Xu04db3f52015-09-16 11:44:02 +08003403 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003404#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003405
3406 switch (op) {
3407 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003408 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003409 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003410 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003411 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003412 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003413 unaryOp = spv::OpSNegate;
3414 break;
3415
3416 case glslang::EOpLogicalNot:
3417 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003418 unaryOp = spv::OpLogicalNot;
3419 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003420 case glslang::EOpBitwiseNot:
3421 unaryOp = spv::OpNot;
3422 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003423
John Kessenich140f3df2015-06-26 16:58:36 -06003424 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003425 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003426 break;
3427 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003428 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003429 break;
3430 case glslang::EOpTranspose:
3431 unaryOp = spv::OpTranspose;
3432 break;
3433
3434 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003435 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003436 break;
3437 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003438 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003439 break;
3440 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003441 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003442 break;
3443 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003444 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003445 break;
3446 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003447 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003448 break;
3449 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003450 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003453 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003454 break;
3455 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003456 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003457 break;
3458
3459 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003460 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003461 break;
3462 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003463 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003464 break;
3465 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003466 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003469 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003470 break;
3471 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003472 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003473 break;
3474 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003475 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003476 break;
3477
3478 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003482 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003483 break;
3484
3485 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003486 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003487 break;
3488 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003489 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003490 break;
3491 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003492 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003493 break;
3494 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003495 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003496 break;
3497 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003498 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003501 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 break;
3503
3504 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003505 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003506 break;
3507 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003508 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003509 break;
3510 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003512 break;
3513 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003514 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003515 break;
3516 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003517 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003518 break;
3519 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003520 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003521 break;
3522
3523 case glslang::EOpIsNan:
3524 unaryOp = spv::OpIsNan;
3525 break;
3526 case glslang::EOpIsInf:
3527 unaryOp = spv::OpIsInf;
3528 break;
LoopDawg592860c2016-06-09 08:57:35 -06003529 case glslang::EOpIsFinite:
3530 unaryOp = spv::OpIsFinite;
3531 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003532
Rex Xucbc426e2015-12-15 16:03:10 +08003533 case glslang::EOpFloatBitsToInt:
3534 case glslang::EOpFloatBitsToUint:
3535 case glslang::EOpIntBitsToFloat:
3536 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003537 case glslang::EOpDoubleBitsToInt64:
3538 case glslang::EOpDoubleBitsToUint64:
3539 case glslang::EOpInt64BitsToDouble:
3540 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003541 unaryOp = spv::OpBitcast;
3542 break;
3543
John Kessenich140f3df2015-06-26 16:58:36 -06003544 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003545 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003546 break;
3547 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003548 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003549 break;
3550 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003551 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003554 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003555 break;
3556 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003557 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003558 break;
3559 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003560 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003561 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003562 case glslang::EOpPackSnorm4x8:
3563 libCall = spv::GLSLstd450PackSnorm4x8;
3564 break;
3565 case glslang::EOpUnpackSnorm4x8:
3566 libCall = spv::GLSLstd450UnpackSnorm4x8;
3567 break;
3568 case glslang::EOpPackUnorm4x8:
3569 libCall = spv::GLSLstd450PackUnorm4x8;
3570 break;
3571 case glslang::EOpUnpackUnorm4x8:
3572 libCall = spv::GLSLstd450UnpackUnorm4x8;
3573 break;
3574 case glslang::EOpPackDouble2x32:
3575 libCall = spv::GLSLstd450PackDouble2x32;
3576 break;
3577 case glslang::EOpUnpackDouble2x32:
3578 libCall = spv::GLSLstd450UnpackDouble2x32;
3579 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003580
Rex Xu8ff43de2016-04-22 16:51:45 +08003581 case glslang::EOpPackInt2x32:
3582 case glslang::EOpUnpackInt2x32:
3583 case glslang::EOpPackUint2x32:
3584 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003585 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003586 break;
3587
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003588#ifdef AMD_EXTENSIONS
3589 case glslang::EOpPackFloat2x16:
3590 case glslang::EOpUnpackFloat2x16:
3591 unaryOp = spv::OpBitcast;
3592 break;
3593#endif
3594
John Kessenich140f3df2015-06-26 16:58:36 -06003595 case glslang::EOpDPdx:
3596 unaryOp = spv::OpDPdx;
3597 break;
3598 case glslang::EOpDPdy:
3599 unaryOp = spv::OpDPdy;
3600 break;
3601 case glslang::EOpFwidth:
3602 unaryOp = spv::OpFwidth;
3603 break;
3604 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003605 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003606 unaryOp = spv::OpDPdxFine;
3607 break;
3608 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003609 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003610 unaryOp = spv::OpDPdyFine;
3611 break;
3612 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003613 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003614 unaryOp = spv::OpFwidthFine;
3615 break;
3616 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003617 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003618 unaryOp = spv::OpDPdxCoarse;
3619 break;
3620 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003621 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003622 unaryOp = spv::OpDPdyCoarse;
3623 break;
3624 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003625 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003626 unaryOp = spv::OpFwidthCoarse;
3627 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003628 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003629 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003630 libCall = spv::GLSLstd450InterpolateAtCentroid;
3631 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003632 case glslang::EOpAny:
3633 unaryOp = spv::OpAny;
3634 break;
3635 case glslang::EOpAll:
3636 unaryOp = spv::OpAll;
3637 break;
3638
3639 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003640 if (isFloat)
3641 libCall = spv::GLSLstd450FAbs;
3642 else
3643 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003644 break;
3645 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003646 if (isFloat)
3647 libCall = spv::GLSLstd450FSign;
3648 else
3649 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003650 break;
3651
John Kessenichfc51d282015-08-19 13:34:18 -06003652 case glslang::EOpAtomicCounterIncrement:
3653 case glslang::EOpAtomicCounterDecrement:
3654 case glslang::EOpAtomicCounter:
3655 {
3656 // Handle all of the atomics in one place, in createAtomicOperation()
3657 std::vector<spv::Id> operands;
3658 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003659 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003660 }
3661
John Kessenichfc51d282015-08-19 13:34:18 -06003662 case glslang::EOpBitFieldReverse:
3663 unaryOp = spv::OpBitReverse;
3664 break;
3665 case glslang::EOpBitCount:
3666 unaryOp = spv::OpBitCount;
3667 break;
3668 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003669 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003670 break;
3671 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003672 if (isUnsigned)
3673 libCall = spv::GLSLstd450FindUMsb;
3674 else
3675 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003676 break;
3677
Rex Xu574ab042016-04-14 16:53:07 +08003678 case glslang::EOpBallot:
3679 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003680 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003681 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003682 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003683#ifdef AMD_EXTENSIONS
3684 case glslang::EOpMinInvocations:
3685 case glslang::EOpMaxInvocations:
3686 case glslang::EOpAddInvocations:
3687 case glslang::EOpMinInvocationsNonUniform:
3688 case glslang::EOpMaxInvocationsNonUniform:
3689 case glslang::EOpAddInvocationsNonUniform:
3690#endif
Rex Xu51596642016-09-21 18:56:12 +08003691 {
3692 std::vector<spv::Id> operands;
3693 operands.push_back(operand);
3694 return createInvocationsOperation(op, typeId, operands, typeProxy);
3695 }
Rex Xu9d93a232016-05-05 12:30:44 +08003696
3697#ifdef AMD_EXTENSIONS
3698 case glslang::EOpMbcnt:
3699 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3700 libCall = spv::MbcntAMD;
3701 break;
3702
3703 case glslang::EOpCubeFaceIndex:
3704 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3705 libCall = spv::CubeFaceIndexAMD;
3706 break;
3707
3708 case glslang::EOpCubeFaceCoord:
3709 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3710 libCall = spv::CubeFaceCoordAMD;
3711 break;
3712#endif
Rex Xu338b1852016-05-05 20:38:33 +08003713
John Kessenich140f3df2015-06-26 16:58:36 -06003714 default:
3715 return 0;
3716 }
3717
3718 spv::Id id;
3719 if (libCall >= 0) {
3720 std::vector<spv::Id> args;
3721 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003722 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003723 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003724 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003725 }
John Kessenich140f3df2015-06-26 16:58:36 -06003726
qining25262b32016-05-06 17:25:16 -04003727 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003728 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003729}
3730
John Kessenich7a53f762016-01-20 11:19:27 -07003731// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003732spv::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 -07003733{
3734 // Handle unary operations vector by vector.
3735 // The result type is the same type as the original type.
3736 // The algorithm is to:
3737 // - break the matrix into vectors
3738 // - apply the operation to each vector
3739 // - make a matrix out the vector results
3740
3741 // get the types sorted out
3742 int numCols = builder.getNumColumns(operand);
3743 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003744 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3745 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003746 std::vector<spv::Id> results;
3747
3748 // do each vector op
3749 for (int c = 0; c < numCols; ++c) {
3750 std::vector<unsigned int> indexes;
3751 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003752 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3753 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3754 addDecoration(destVec, noContraction);
3755 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003756 }
3757
3758 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003759 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003760}
3761
Rex Xu73e3ce72016-04-27 18:48:17 +08003762spv::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 -06003763{
3764 spv::Op convOp = spv::OpNop;
3765 spv::Id zero = 0;
3766 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003767 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003768
3769 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3770
3771 switch (op) {
3772 case glslang::EOpConvIntToBool:
3773 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003774 case glslang::EOpConvInt64ToBool:
3775 case glslang::EOpConvUint64ToBool:
3776 zero = (op == glslang::EOpConvInt64ToBool ||
3777 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003778 zero = makeSmearedConstant(zero, vectorSize);
3779 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3780
3781 case glslang::EOpConvFloatToBool:
3782 zero = builder.makeFloatConstant(0.0F);
3783 zero = makeSmearedConstant(zero, vectorSize);
3784 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3785
3786 case glslang::EOpConvDoubleToBool:
3787 zero = builder.makeDoubleConstant(0.0);
3788 zero = makeSmearedConstant(zero, vectorSize);
3789 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3790
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003791#ifdef AMD_EXTENSIONS
3792 case glslang::EOpConvFloat16ToBool:
3793 zero = builder.makeFloat16Constant(0.0F);
3794 zero = makeSmearedConstant(zero, vectorSize);
3795 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3796#endif
3797
John Kessenich140f3df2015-06-26 16:58:36 -06003798 case glslang::EOpConvBoolToFloat:
3799 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003800 zero = builder.makeFloatConstant(0.0F);
3801 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003802 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003803
John Kessenich140f3df2015-06-26 16:58:36 -06003804 case glslang::EOpConvBoolToDouble:
3805 convOp = spv::OpSelect;
3806 zero = builder.makeDoubleConstant(0.0);
3807 one = builder.makeDoubleConstant(1.0);
3808 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003809
3810#ifdef AMD_EXTENSIONS
3811 case glslang::EOpConvBoolToFloat16:
3812 convOp = spv::OpSelect;
3813 zero = builder.makeFloat16Constant(0.0F);
3814 one = builder.makeFloat16Constant(1.0F);
3815 break;
3816#endif
3817
John Kessenich140f3df2015-06-26 16:58:36 -06003818 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003819 case glslang::EOpConvBoolToInt64:
3820 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3821 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003822 convOp = spv::OpSelect;
3823 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003824
John Kessenich140f3df2015-06-26 16:58:36 -06003825 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003826 case glslang::EOpConvBoolToUint64:
3827 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3828 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 convOp = spv::OpSelect;
3830 break;
3831
3832 case glslang::EOpConvIntToFloat:
3833 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003834 case glslang::EOpConvInt64ToFloat:
3835 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003836#ifdef AMD_EXTENSIONS
3837 case glslang::EOpConvIntToFloat16:
3838 case glslang::EOpConvInt64ToFloat16:
3839#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003840 convOp = spv::OpConvertSToF;
3841 break;
3842
3843 case glslang::EOpConvUintToFloat:
3844 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003845 case glslang::EOpConvUint64ToFloat:
3846 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003847#ifdef AMD_EXTENSIONS
3848 case glslang::EOpConvUintToFloat16:
3849 case glslang::EOpConvUint64ToFloat16:
3850#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003851 convOp = spv::OpConvertUToF;
3852 break;
3853
3854 case glslang::EOpConvDoubleToFloat:
3855 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003856#ifdef AMD_EXTENSIONS
3857 case glslang::EOpConvDoubleToFloat16:
3858 case glslang::EOpConvFloat16ToDouble:
3859 case glslang::EOpConvFloatToFloat16:
3860 case glslang::EOpConvFloat16ToFloat:
3861#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003862 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003863 if (builder.isMatrixType(destType))
3864 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003865 break;
3866
3867 case glslang::EOpConvFloatToInt:
3868 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003869 case glslang::EOpConvFloatToInt64:
3870 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003871#ifdef AMD_EXTENSIONS
3872 case glslang::EOpConvFloat16ToInt:
3873 case glslang::EOpConvFloat16ToInt64:
3874#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003875 convOp = spv::OpConvertFToS;
3876 break;
3877
3878 case glslang::EOpConvUintToInt:
3879 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003880 case glslang::EOpConvUint64ToInt64:
3881 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003882 if (builder.isInSpecConstCodeGenMode()) {
3883 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003884 zero = (op == glslang::EOpConvUint64ToInt64 ||
3885 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003886 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003887 // Use OpIAdd, instead of OpBitcast to do the conversion when
3888 // generating for OpSpecConstantOp instruction.
3889 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3890 }
3891 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003892 convOp = spv::OpBitcast;
3893 break;
3894
3895 case glslang::EOpConvFloatToUint:
3896 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003897 case glslang::EOpConvFloatToUint64:
3898 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003899#ifdef AMD_EXTENSIONS
3900 case glslang::EOpConvFloat16ToUint:
3901 case glslang::EOpConvFloat16ToUint64:
3902#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003903 convOp = spv::OpConvertFToU;
3904 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003905
3906 case glslang::EOpConvIntToInt64:
3907 case glslang::EOpConvInt64ToInt:
3908 convOp = spv::OpSConvert;
3909 break;
3910
3911 case glslang::EOpConvUintToUint64:
3912 case glslang::EOpConvUint64ToUint:
3913 convOp = spv::OpUConvert;
3914 break;
3915
3916 case glslang::EOpConvIntToUint64:
3917 case glslang::EOpConvInt64ToUint:
3918 case glslang::EOpConvUint64ToInt:
3919 case glslang::EOpConvUintToInt64:
3920 // OpSConvert/OpUConvert + OpBitCast
3921 switch (op) {
3922 case glslang::EOpConvIntToUint64:
3923 convOp = spv::OpSConvert;
3924 type = builder.makeIntType(64);
3925 break;
3926 case glslang::EOpConvInt64ToUint:
3927 convOp = spv::OpSConvert;
3928 type = builder.makeIntType(32);
3929 break;
3930 case glslang::EOpConvUint64ToInt:
3931 convOp = spv::OpUConvert;
3932 type = builder.makeUintType(32);
3933 break;
3934 case glslang::EOpConvUintToInt64:
3935 convOp = spv::OpUConvert;
3936 type = builder.makeUintType(64);
3937 break;
3938 default:
3939 assert(0);
3940 break;
3941 }
3942
3943 if (vectorSize > 0)
3944 type = builder.makeVectorType(type, vectorSize);
3945
3946 operand = builder.createUnaryOp(convOp, type, operand);
3947
3948 if (builder.isInSpecConstCodeGenMode()) {
3949 // Build zero scalar or vector for OpIAdd.
3950 zero = (op == glslang::EOpConvIntToUint64 ||
3951 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3952 zero = makeSmearedConstant(zero, vectorSize);
3953 // Use OpIAdd, instead of OpBitcast to do the conversion when
3954 // generating for OpSpecConstantOp instruction.
3955 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3956 }
3957 // For normal run-time conversion instruction, use OpBitcast.
3958 convOp = spv::OpBitcast;
3959 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003960 default:
3961 break;
3962 }
3963
3964 spv::Id result = 0;
3965 if (convOp == spv::OpNop)
3966 return result;
3967
3968 if (convOp == spv::OpSelect) {
3969 zero = makeSmearedConstant(zero, vectorSize);
3970 one = makeSmearedConstant(one, vectorSize);
3971 result = builder.createTriOp(convOp, destType, operand, one, zero);
3972 } else
3973 result = builder.createUnaryOp(convOp, destType, operand);
3974
John Kessenich32cfd492016-02-02 12:37:46 -07003975 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003976}
3977
3978spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3979{
3980 if (vectorSize == 0)
3981 return constant;
3982
3983 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3984 std::vector<spv::Id> components;
3985 for (int c = 0; c < vectorSize; ++c)
3986 components.push_back(constant);
3987 return builder.makeCompositeConstant(vectorTypeId, components);
3988}
3989
John Kessenich426394d2015-07-23 10:22:48 -06003990// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003991spv::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 -06003992{
3993 spv::Op opCode = spv::OpNop;
3994
3995 switch (op) {
3996 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003997 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003998 opCode = spv::OpAtomicIAdd;
3999 break;
4000 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004001 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004002 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004003 break;
4004 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004005 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004006 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004007 break;
4008 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004009 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004010 opCode = spv::OpAtomicAnd;
4011 break;
4012 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004013 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004014 opCode = spv::OpAtomicOr;
4015 break;
4016 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004017 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004018 opCode = spv::OpAtomicXor;
4019 break;
4020 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004021 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004022 opCode = spv::OpAtomicExchange;
4023 break;
4024 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004025 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004026 opCode = spv::OpAtomicCompareExchange;
4027 break;
4028 case glslang::EOpAtomicCounterIncrement:
4029 opCode = spv::OpAtomicIIncrement;
4030 break;
4031 case glslang::EOpAtomicCounterDecrement:
4032 opCode = spv::OpAtomicIDecrement;
4033 break;
4034 case glslang::EOpAtomicCounter:
4035 opCode = spv::OpAtomicLoad;
4036 break;
4037 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004038 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004039 break;
4040 }
4041
4042 // Sort out the operands
4043 // - mapping from glslang -> SPV
4044 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004045 // - compare-exchange swaps the value and comparator
4046 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004047 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4048 auto opIt = operands.begin(); // walk the glslang operands
4049 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004050 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4051 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4052 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004053 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4054 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004055 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004056 spvAtomicOperands.push_back(*(opIt + 1));
4057 spvAtomicOperands.push_back(*opIt);
4058 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004059 }
John Kessenich426394d2015-07-23 10:22:48 -06004060
John Kessenich3e60a6f2015-09-14 22:45:16 -06004061 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004062 for (; opIt != operands.end(); ++opIt)
4063 spvAtomicOperands.push_back(*opIt);
4064
4065 return builder.createOp(opCode, typeId, spvAtomicOperands);
4066}
4067
John Kessenich91cef522016-05-05 16:45:40 -06004068// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004069spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004070{
Rex Xu9d93a232016-05-05 12:30:44 +08004071 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004072#ifdef AMD_EXTENSIONS
4073 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4074#else
Rex Xu9d93a232016-05-05 12:30:44 +08004075 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004076#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004077
Rex Xu51596642016-09-21 18:56:12 +08004078 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004079
Rex Xu51596642016-09-21 18:56:12 +08004080 std::vector<spv::Id> spvGroupOperands;
4081 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4082 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4083 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4084 } else {
4085 builder.addCapability(spv::CapabilityGroups);
4086
4087 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004088#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004089 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4090 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4091 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004092#endif
Rex Xu51596642016-09-21 18:56:12 +08004093 }
4094
4095 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4096 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004097
4098 switch (op) {
4099 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004100 opCode = spv::OpGroupAny;
4101 break;
John Kessenich91cef522016-05-05 16:45:40 -06004102 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004103 opCode = spv::OpGroupAll;
4104 break;
John Kessenich91cef522016-05-05 16:45:40 -06004105 case glslang::EOpAllInvocationsEqual:
4106 {
Rex Xu51596642016-09-21 18:56:12 +08004107 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4108 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004109
4110 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4111 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4112 }
Rex Xu51596642016-09-21 18:56:12 +08004113
4114 case glslang::EOpReadInvocation:
4115 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004116 if (builder.isVectorType(typeId))
4117 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004118 break;
4119 case glslang::EOpReadFirstInvocation:
4120 opCode = spv::OpSubgroupFirstInvocationKHR;
4121 break;
4122 case glslang::EOpBallot:
4123 {
4124 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4125 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4126 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4127 //
4128 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4129 //
4130 spv::Id uintType = builder.makeUintType(32);
4131 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4132 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4133
4134 std::vector<spv::Id> components;
4135 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4136 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4137
4138 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4139 return builder.createUnaryOp(spv::OpBitcast, typeId,
4140 builder.createCompositeConstruct(uvec2Type, components));
4141 }
4142
Rex Xu9d93a232016-05-05 12:30:44 +08004143#ifdef AMD_EXTENSIONS
4144 case glslang::EOpMinInvocations:
4145 case glslang::EOpMaxInvocations:
4146 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004147 if (op == glslang::EOpMinInvocations) {
4148 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004149 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004150 else {
4151 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004152 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004153 else
Rex Xu51596642016-09-21 18:56:12 +08004154 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004155 }
4156 } else if (op == glslang::EOpMaxInvocations) {
4157 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004158 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004159 else {
4160 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004161 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004162 else
Rex Xu51596642016-09-21 18:56:12 +08004163 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004164 }
4165 } else {
4166 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004167 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004168 else
Rex Xu51596642016-09-21 18:56:12 +08004169 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004170 }
4171
Rex Xu2bbbe062016-08-23 15:41:05 +08004172 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004173 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004174
4175 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004176 case glslang::EOpMinInvocationsNonUniform:
4177 case glslang::EOpMaxInvocationsNonUniform:
4178 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004179 if (op == glslang::EOpMinInvocationsNonUniform) {
4180 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004181 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004182 else {
4183 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004184 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004185 else
Rex Xu51596642016-09-21 18:56:12 +08004186 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004187 }
4188 }
4189 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4190 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004191 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004192 else {
4193 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004194 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004195 else
Rex Xu51596642016-09-21 18:56:12 +08004196 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004197 }
4198 }
4199 else {
4200 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004201 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004202 else
Rex Xu51596642016-09-21 18:56:12 +08004203 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004204 }
4205
Rex Xu2bbbe062016-08-23 15:41:05 +08004206 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004207 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004208
4209 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004210#endif
John Kessenich91cef522016-05-05 16:45:40 -06004211 default:
4212 logger->missingFunctionality("invocation operation");
4213 return spv::NoResult;
4214 }
Rex Xu51596642016-09-21 18:56:12 +08004215
4216 assert(opCode != spv::OpNop);
4217 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004218}
4219
Rex Xu2bbbe062016-08-23 15:41:05 +08004220// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004221spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004222{
Rex Xub7072052016-09-26 15:53:40 +08004223#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004224 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4225 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004226 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004227 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4228 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4229 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004230#else
4231 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4232 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4233 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4234#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004235
4236 // Handle group invocation operations scalar by scalar.
4237 // The result type is the same type as the original type.
4238 // The algorithm is to:
4239 // - break the vector into scalars
4240 // - apply the operation to each scalar
4241 // - make a vector out the scalar results
4242
4243 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004244 int numComponents = builder.getNumComponents(operands[0]);
4245 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004246 std::vector<spv::Id> results;
4247
4248 // do each scalar op
4249 for (int comp = 0; comp < numComponents; ++comp) {
4250 std::vector<unsigned int> indexes;
4251 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004252 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004253
Rex Xub7072052016-09-26 15:53:40 +08004254 std::vector<spv::Id> spvGroupOperands;
4255 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4256 if (op == spv::OpGroupBroadcast) {
4257 spvGroupOperands.push_back(scalar);
4258 spvGroupOperands.push_back(operands[1]);
4259 } else {
4260 spvGroupOperands.push_back(spv::GroupOperationReduce);
4261 spvGroupOperands.push_back(scalar);
4262 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004263
Rex Xub7072052016-09-26 15:53:40 +08004264 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004265 }
4266
4267 // put the pieces together
4268 return builder.createCompositeConstruct(typeId, results);
4269}
Rex Xu2bbbe062016-08-23 15:41:05 +08004270
John Kessenich5e4b1242015-08-06 22:53:06 -06004271spv::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 -06004272{
Rex Xu8ff43de2016-04-22 16:51:45 +08004273 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004274#ifdef AMD_EXTENSIONS
4275 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4276#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004277 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004278#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004279
John Kessenich140f3df2015-06-26 16:58:36 -06004280 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004281 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004282 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004283 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004284 spv::Id typeId0 = 0;
4285 if (consumedOperands > 0)
4286 typeId0 = builder.getTypeId(operands[0]);
4287 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004288
4289 switch (op) {
4290 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004291 if (isFloat)
4292 libCall = spv::GLSLstd450FMin;
4293 else if (isUnsigned)
4294 libCall = spv::GLSLstd450UMin;
4295 else
4296 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004297 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004298 break;
4299 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004300 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004301 break;
4302 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004303 if (isFloat)
4304 libCall = spv::GLSLstd450FMax;
4305 else if (isUnsigned)
4306 libCall = spv::GLSLstd450UMax;
4307 else
4308 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004309 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004310 break;
4311 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004312 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004313 break;
4314 case glslang::EOpDot:
4315 opCode = spv::OpDot;
4316 break;
4317 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004318 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004319 break;
4320
4321 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004322 if (isFloat)
4323 libCall = spv::GLSLstd450FClamp;
4324 else if (isUnsigned)
4325 libCall = spv::GLSLstd450UClamp;
4326 else
4327 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004328 builder.promoteScalar(precision, operands.front(), operands[1]);
4329 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004330 break;
4331 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004332 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4333 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004334 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004335 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004336 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004337 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004338 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004339 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004340 break;
4341 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004342 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004343 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004344 break;
4345 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004346 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004347 builder.promoteScalar(precision, operands[0], operands[2]);
4348 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004349 break;
4350
4351 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004352 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004353 break;
4354 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004355 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004356 break;
4357 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004358 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004359 break;
4360 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004361 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004362 break;
4363 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004364 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004365 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004366 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004367 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004368 libCall = spv::GLSLstd450InterpolateAtSample;
4369 break;
4370 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004371 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004372 libCall = spv::GLSLstd450InterpolateAtOffset;
4373 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004374 case glslang::EOpAddCarry:
4375 opCode = spv::OpIAddCarry;
4376 typeId = builder.makeStructResultType(typeId0, typeId0);
4377 consumedOperands = 2;
4378 break;
4379 case glslang::EOpSubBorrow:
4380 opCode = spv::OpISubBorrow;
4381 typeId = builder.makeStructResultType(typeId0, typeId0);
4382 consumedOperands = 2;
4383 break;
4384 case glslang::EOpUMulExtended:
4385 opCode = spv::OpUMulExtended;
4386 typeId = builder.makeStructResultType(typeId0, typeId0);
4387 consumedOperands = 2;
4388 break;
4389 case glslang::EOpIMulExtended:
4390 opCode = spv::OpSMulExtended;
4391 typeId = builder.makeStructResultType(typeId0, typeId0);
4392 consumedOperands = 2;
4393 break;
4394 case glslang::EOpBitfieldExtract:
4395 if (isUnsigned)
4396 opCode = spv::OpBitFieldUExtract;
4397 else
4398 opCode = spv::OpBitFieldSExtract;
4399 break;
4400 case glslang::EOpBitfieldInsert:
4401 opCode = spv::OpBitFieldInsert;
4402 break;
4403
4404 case glslang::EOpFma:
4405 libCall = spv::GLSLstd450Fma;
4406 break;
4407 case glslang::EOpFrexp:
4408 libCall = spv::GLSLstd450FrexpStruct;
4409 if (builder.getNumComponents(operands[0]) == 1)
4410 frexpIntType = builder.makeIntegerType(32, true);
4411 else
4412 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4413 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4414 consumedOperands = 1;
4415 break;
4416 case glslang::EOpLdexp:
4417 libCall = spv::GLSLstd450Ldexp;
4418 break;
4419
Rex Xu574ab042016-04-14 16:53:07 +08004420 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004421 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004422
Rex Xu9d93a232016-05-05 12:30:44 +08004423#ifdef AMD_EXTENSIONS
4424 case glslang::EOpSwizzleInvocations:
4425 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4426 libCall = spv::SwizzleInvocationsAMD;
4427 break;
4428 case glslang::EOpSwizzleInvocationsMasked:
4429 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4430 libCall = spv::SwizzleInvocationsMaskedAMD;
4431 break;
4432 case glslang::EOpWriteInvocation:
4433 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4434 libCall = spv::WriteInvocationAMD;
4435 break;
4436
4437 case glslang::EOpMin3:
4438 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4439 if (isFloat)
4440 libCall = spv::FMin3AMD;
4441 else {
4442 if (isUnsigned)
4443 libCall = spv::UMin3AMD;
4444 else
4445 libCall = spv::SMin3AMD;
4446 }
4447 break;
4448 case glslang::EOpMax3:
4449 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4450 if (isFloat)
4451 libCall = spv::FMax3AMD;
4452 else {
4453 if (isUnsigned)
4454 libCall = spv::UMax3AMD;
4455 else
4456 libCall = spv::SMax3AMD;
4457 }
4458 break;
4459 case glslang::EOpMid3:
4460 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4461 if (isFloat)
4462 libCall = spv::FMid3AMD;
4463 else {
4464 if (isUnsigned)
4465 libCall = spv::UMid3AMD;
4466 else
4467 libCall = spv::SMid3AMD;
4468 }
4469 break;
4470
4471 case glslang::EOpInterpolateAtVertex:
4472 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4473 libCall = spv::InterpolateAtVertexAMD;
4474 break;
4475#endif
4476
John Kessenich140f3df2015-06-26 16:58:36 -06004477 default:
4478 return 0;
4479 }
4480
4481 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004482 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004483 // Use an extended instruction from the standard library.
4484 // Construct the call arguments, without modifying the original operands vector.
4485 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4486 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004487 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004488 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004489 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004490 case 0:
4491 // should all be handled by visitAggregate and createNoArgOperation
4492 assert(0);
4493 return 0;
4494 case 1:
4495 // should all be handled by createUnaryOperation
4496 assert(0);
4497 return 0;
4498 case 2:
4499 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4500 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004501 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004502 // anything 3 or over doesn't have l-value operands, so all should be consumed
4503 assert(consumedOperands == operands.size());
4504 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004505 break;
4506 }
4507 }
4508
John Kessenich55e7d112015-11-15 21:33:39 -07004509 // Decode the return types that were structures
4510 switch (op) {
4511 case glslang::EOpAddCarry:
4512 case glslang::EOpSubBorrow:
4513 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4514 id = builder.createCompositeExtract(id, typeId0, 0);
4515 break;
4516 case glslang::EOpUMulExtended:
4517 case glslang::EOpIMulExtended:
4518 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4519 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4520 break;
4521 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004522 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004523 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4524 id = builder.createCompositeExtract(id, typeId0, 0);
4525 break;
4526 default:
4527 break;
4528 }
4529
John Kessenich32cfd492016-02-02 12:37:46 -07004530 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004531}
4532
Rex Xu9d93a232016-05-05 12:30:44 +08004533// Intrinsics with no arguments (or no return value, and no precision).
4534spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004535{
4536 // TODO: get the barrier operands correct
4537
4538 switch (op) {
4539 case glslang::EOpEmitVertex:
4540 builder.createNoResultOp(spv::OpEmitVertex);
4541 return 0;
4542 case glslang::EOpEndPrimitive:
4543 builder.createNoResultOp(spv::OpEndPrimitive);
4544 return 0;
4545 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004546 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004547 return 0;
4548 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004549 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004550 return 0;
4551 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004552 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004553 return 0;
4554 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004555 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004556 return 0;
4557 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004558 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004559 return 0;
4560 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004561 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004562 return 0;
4563 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004564 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004565 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004566 case glslang::EOpAllMemoryBarrierWithGroupSync:
4567 // Control barrier with non-"None" semantic is also a memory barrier.
4568 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4569 return 0;
4570 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4571 // Control barrier with non-"None" semantic is also a memory barrier.
4572 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4573 return 0;
4574 case glslang::EOpWorkgroupMemoryBarrier:
4575 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4576 return 0;
4577 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4578 // Control barrier with non-"None" semantic is also a memory barrier.
4579 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4580 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004581#ifdef AMD_EXTENSIONS
4582 case glslang::EOpTime:
4583 {
4584 std::vector<spv::Id> args; // Dummy arguments
4585 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4586 return builder.setPrecision(id, precision);
4587 }
4588#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004589 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004590 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004591 return 0;
4592 }
4593}
4594
4595spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4596{
John Kessenich2f273362015-07-18 22:34:27 -06004597 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004598 spv::Id id;
4599 if (symbolValues.end() != iter) {
4600 id = iter->second;
4601 return id;
4602 }
4603
4604 // it was not found, create it
4605 id = createSpvVariable(symbol);
4606 symbolValues[symbol->getId()] = id;
4607
Rex Xuc884b4a2016-06-29 15:03:44 +08004608 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004609 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004610 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004611 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004612 if (symbol->getType().getQualifier().hasSpecConstantId())
4613 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004614 if (symbol->getQualifier().hasIndex())
4615 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4616 if (symbol->getQualifier().hasComponent())
4617 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4618 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004619 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004620 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004621 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004622 if (symbol->getQualifier().hasXfbBuffer())
4623 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4624 if (symbol->getQualifier().hasXfbOffset())
4625 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4626 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004627 // atomic counters use this:
4628 if (symbol->getQualifier().hasOffset())
4629 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004630 }
4631
scygan2c864272016-05-18 18:09:17 +02004632 if (symbol->getQualifier().hasLocation())
4633 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004634 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004635 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004636 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004637 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004638 }
John Kessenich140f3df2015-06-26 16:58:36 -06004639 if (symbol->getQualifier().hasSet())
4640 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004641 else if (IsDescriptorResource(symbol->getType())) {
4642 // default to 0
4643 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4644 }
John Kessenich140f3df2015-06-26 16:58:36 -06004645 if (symbol->getQualifier().hasBinding())
4646 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004647 if (symbol->getQualifier().hasAttachment())
4648 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004649 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004650 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004651 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004652 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004653 if (symbol->getQualifier().hasXfbBuffer())
4654 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4655 }
4656
Rex Xu1da878f2016-02-21 20:59:01 +08004657 if (symbol->getType().isImage()) {
4658 std::vector<spv::Decoration> memory;
4659 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4660 for (unsigned int i = 0; i < memory.size(); ++i)
4661 addDecoration(id, memory[i]);
4662 }
4663
John Kessenich140f3df2015-06-26 16:58:36 -06004664 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004665 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004666 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004667 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004668
John Kessenich140f3df2015-06-26 16:58:36 -06004669 return id;
4670}
4671
John Kessenich55e7d112015-11-15 21:33:39 -07004672// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004673void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4674{
John Kessenich4016e382016-07-15 11:53:56 -06004675 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004676 builder.addDecoration(id, dec);
4677}
4678
John Kessenich55e7d112015-11-15 21:33:39 -07004679// If 'dec' is valid, add a one-operand decoration to an object
4680void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4681{
John Kessenich4016e382016-07-15 11:53:56 -06004682 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004683 builder.addDecoration(id, dec, value);
4684}
4685
4686// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004687void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4688{
John Kessenich4016e382016-07-15 11:53:56 -06004689 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004690 builder.addMemberDecoration(id, (unsigned)member, dec);
4691}
4692
John Kessenich92187592016-02-01 13:45:25 -07004693// If 'dec' is valid, add a one-operand decoration to a struct member
4694void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4695{
John Kessenich4016e382016-07-15 11:53:56 -06004696 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004697 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4698}
4699
John Kessenich55e7d112015-11-15 21:33:39 -07004700// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004701// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004702//
4703// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4704//
4705// Recursively walk the nodes. The nodes form a tree whose leaves are
4706// regular constants, which themselves are trees that createSpvConstant()
4707// recursively walks. So, this function walks the "top" of the tree:
4708// - emit specialization constant-building instructions for specConstant
4709// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004710spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004711{
John Kessenich7cc0e282016-03-20 00:46:02 -06004712 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004713
qining4f4bb812016-04-03 23:55:17 -04004714 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004715 if (! node.getQualifier().specConstant) {
4716 // hand off to the non-spec-constant path
4717 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4718 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004719 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004720 nextConst, false);
4721 }
4722
4723 // We now know we have a specialization constant to build
4724
John Kessenichd94c0032016-05-30 19:29:40 -06004725 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004726 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4727 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4728 std::vector<spv::Id> dimConstId;
4729 for (int dim = 0; dim < 3; ++dim) {
4730 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4731 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4732 if (specConst)
4733 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4734 }
4735 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4736 }
4737
4738 // An AST node labelled as specialization constant should be a symbol node.
4739 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4740 if (auto* sn = node.getAsSymbolNode()) {
4741 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004742 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4743 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4744 // will set the builder into spec constant op instruction generating mode.
4745 sub_tree->traverse(this);
4746 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004747 } else if (auto* const_union_array = &sn->getConstArray()){
4748 int nextConst = 0;
4749 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004750 }
4751 }
qining4f4bb812016-04-03 23:55:17 -04004752
4753 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4754 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004755 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004756 exit(1);
4757 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004758}
4759
John Kessenich140f3df2015-06-26 16:58:36 -06004760// Use 'consts' as the flattened glslang source of scalar constants to recursively
4761// build the aggregate SPIR-V constant.
4762//
4763// If there are not enough elements present in 'consts', 0 will be substituted;
4764// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4765//
qining08408382016-03-21 09:51:37 -04004766spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004767{
4768 // vector of constants for SPIR-V
4769 std::vector<spv::Id> spvConsts;
4770
4771 // Type is used for struct and array constants
4772 spv::Id typeId = convertGlslangToSpvType(glslangType);
4773
4774 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004775 glslang::TType elementType(glslangType, 0);
4776 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004777 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004778 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004779 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004780 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004781 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004782 } else if (glslangType.getStruct()) {
4783 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4784 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004785 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004786 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004787 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4788 bool zero = nextConst >= consts.size();
4789 switch (glslangType.getBasicType()) {
4790 case glslang::EbtInt:
4791 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4792 break;
4793 case glslang::EbtUint:
4794 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4795 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004796 case glslang::EbtInt64:
4797 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4798 break;
4799 case glslang::EbtUint64:
4800 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4801 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004802 case glslang::EbtFloat:
4803 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4804 break;
4805 case glslang::EbtDouble:
4806 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4807 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004808#ifdef AMD_EXTENSIONS
4809 case glslang::EbtFloat16:
4810 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4811 break;
4812#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004813 case glslang::EbtBool:
4814 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4815 break;
4816 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004817 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004818 break;
4819 }
4820 ++nextConst;
4821 }
4822 } else {
4823 // we have a non-aggregate (scalar) constant
4824 bool zero = nextConst >= consts.size();
4825 spv::Id scalar = 0;
4826 switch (glslangType.getBasicType()) {
4827 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004828 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004829 break;
4830 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004831 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004832 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004833 case glslang::EbtInt64:
4834 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4835 break;
4836 case glslang::EbtUint64:
4837 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4838 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004839 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004840 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004841 break;
4842 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004843 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004844 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004845#ifdef AMD_EXTENSIONS
4846 case glslang::EbtFloat16:
4847 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4848 break;
4849#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004850 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004851 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004852 break;
4853 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004854 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004855 break;
4856 }
4857 ++nextConst;
4858 return scalar;
4859 }
4860
4861 return builder.makeCompositeConstant(typeId, spvConsts);
4862}
4863
John Kessenich7c1aa102015-10-15 13:29:11 -06004864// Return true if the node is a constant or symbol whose reading has no
4865// non-trivial observable cost or effect.
4866bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4867{
4868 // don't know what this is
4869 if (node == nullptr)
4870 return false;
4871
4872 // a constant is safe
4873 if (node->getAsConstantUnion() != nullptr)
4874 return true;
4875
4876 // not a symbol means non-trivial
4877 if (node->getAsSymbolNode() == nullptr)
4878 return false;
4879
4880 // a symbol, depends on what's being read
4881 switch (node->getType().getQualifier().storage) {
4882 case glslang::EvqTemporary:
4883 case glslang::EvqGlobal:
4884 case glslang::EvqIn:
4885 case glslang::EvqInOut:
4886 case glslang::EvqConst:
4887 case glslang::EvqConstReadOnly:
4888 case glslang::EvqUniform:
4889 return true;
4890 default:
4891 return false;
4892 }
qining25262b32016-05-06 17:25:16 -04004893}
John Kessenich7c1aa102015-10-15 13:29:11 -06004894
4895// A node is trivial if it is a single operation with no side effects.
4896// Error on the side of saying non-trivial.
4897// Return true if trivial.
4898bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4899{
4900 if (node == nullptr)
4901 return false;
4902
4903 // symbols and constants are trivial
4904 if (isTrivialLeaf(node))
4905 return true;
4906
4907 // otherwise, it needs to be a simple operation or one or two leaf nodes
4908
4909 // not a simple operation
4910 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4911 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4912 if (binaryNode == nullptr && unaryNode == nullptr)
4913 return false;
4914
4915 // not on leaf nodes
4916 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4917 return false;
4918
4919 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4920 return false;
4921 }
4922
4923 switch (node->getAsOperator()->getOp()) {
4924 case glslang::EOpLogicalNot:
4925 case glslang::EOpConvIntToBool:
4926 case glslang::EOpConvUintToBool:
4927 case glslang::EOpConvFloatToBool:
4928 case glslang::EOpConvDoubleToBool:
4929 case glslang::EOpEqual:
4930 case glslang::EOpNotEqual:
4931 case glslang::EOpLessThan:
4932 case glslang::EOpGreaterThan:
4933 case glslang::EOpLessThanEqual:
4934 case glslang::EOpGreaterThanEqual:
4935 case glslang::EOpIndexDirect:
4936 case glslang::EOpIndexDirectStruct:
4937 case glslang::EOpLogicalXor:
4938 case glslang::EOpAny:
4939 case glslang::EOpAll:
4940 return true;
4941 default:
4942 return false;
4943 }
4944}
4945
4946// Emit short-circuiting code, where 'right' is never evaluated unless
4947// the left side is true (for &&) or false (for ||).
4948spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4949{
4950 spv::Id boolTypeId = builder.makeBoolType();
4951
4952 // emit left operand
4953 builder.clearAccessChain();
4954 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004955 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004956
4957 // Operands to accumulate OpPhi operands
4958 std::vector<spv::Id> phiOperands;
4959 // accumulate left operand's phi information
4960 phiOperands.push_back(leftId);
4961 phiOperands.push_back(builder.getBuildPoint()->getId());
4962
4963 // Make the two kinds of operation symmetric with a "!"
4964 // || => emit "if (! left) result = right"
4965 // && => emit "if ( left) result = right"
4966 //
4967 // TODO: this runtime "not" for || could be avoided by adding functionality
4968 // to 'builder' to have an "else" without an "then"
4969 if (op == glslang::EOpLogicalOr)
4970 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4971
4972 // make an "if" based on the left value
4973 spv::Builder::If ifBuilder(leftId, builder);
4974
4975 // emit right operand as the "then" part of the "if"
4976 builder.clearAccessChain();
4977 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004978 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004979
4980 // accumulate left operand's phi information
4981 phiOperands.push_back(rightId);
4982 phiOperands.push_back(builder.getBuildPoint()->getId());
4983
4984 // finish the "if"
4985 ifBuilder.makeEndIf();
4986
4987 // phi together the two results
4988 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4989}
4990
Rex Xu9d93a232016-05-05 12:30:44 +08004991// Return type Id of the imported set of extended instructions corresponds to the name.
4992// Import this set if it has not been imported yet.
4993spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4994{
4995 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4996 return extBuiltinMap[name];
4997 else {
Rex Xu51596642016-09-21 18:56:12 +08004998 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08004999 spv::Id extBuiltins = builder.import(name);
5000 extBuiltinMap[name] = extBuiltins;
5001 return extBuiltins;
5002 }
5003}
5004
John Kessenich140f3df2015-06-26 16:58:36 -06005005}; // end anonymous namespace
5006
5007namespace glslang {
5008
John Kessenich68d78fd2015-07-12 19:28:10 -06005009void GetSpirvVersion(std::string& version)
5010{
John Kessenich9e55f632015-07-15 10:03:39 -06005011 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005012 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005013 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005014 version = buf;
5015}
5016
John Kessenich140f3df2015-06-26 16:58:36 -06005017// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005018void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005019{
5020 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005021 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005022 for (int i = 0; i < (int)spirv.size(); ++i) {
5023 unsigned int word = spirv[i];
5024 out.write((const char*)&word, 4);
5025 }
5026 out.close();
5027}
5028
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005029// Write SPIR-V out to a text file with 32-bit hexadecimal words
5030void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5031{
5032 std::ofstream out;
5033 out.open(baseName, std::ios::binary | std::ios::out);
5034 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5035 const int WORDS_PER_LINE = 8;
5036 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5037 out << "\t";
5038 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5039 const unsigned int word = spirv[i + j];
5040 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5041 if (i + j + 1 < (int)spirv.size()) {
5042 out << ",";
5043 }
5044 }
5045 out << std::endl;
5046 }
5047 out.close();
5048}
5049
John Kessenich140f3df2015-06-26 16:58:36 -06005050//
5051// Set up the glslang traversal
5052//
5053void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5054{
Lei Zhang17535f72016-05-04 15:55:59 -04005055 spv::SpvBuildLogger logger;
5056 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005057}
5058
Lei Zhang17535f72016-05-04 15:55:59 -04005059void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005060{
John Kessenich140f3df2015-06-26 16:58:36 -06005061 TIntermNode* root = intermediate.getTreeRoot();
5062
5063 if (root == 0)
5064 return;
5065
5066 glslang::GetThreadPoolAllocator().push();
5067
Lei Zhang17535f72016-05-04 15:55:59 -04005068 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005069
5070 root->traverse(&it);
5071
5072 it.dumpSpv(spirv);
5073
5074 glslang::GetThreadPoolAllocator().pop();
5075}
5076
5077}; // end namespace glslang