blob: 34cdc5c20159bce6a337e6d8f0774e113e6d3846 [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:
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200502
John Kessenichda581a22015-10-14 14:10:30 -0600503 case glslang::EbvDrawId:
504 // TODO: Add SPIR-V builtin ID.
John Kessenichc8a56762016-05-05 12:04:22 -0600505 logger->missingFunctionality("shader draw parameters");
John Kessenich4016e382016-07-15 11:53:56 -0600506 return spv::BuiltInMax;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200507
508 case glslang::EbvPrimitiveId:
509 if (glslangIntermediate->getStage() == EShLangFragment)
510 builder.addCapability(spv::CapabilityGeometry);
511 return spv::BuiltInPrimitiveId;
512
John Kessenich140f3df2015-06-26 16:58:36 -0600513 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600514 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
515 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
516 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
517 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
518 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
519 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
520 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600521 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
522 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
523 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
524 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
525 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
526 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
527 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
528 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800529
Rex Xu574ab042016-04-14 16:53:07 +0800530 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800531 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800532 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
533 return spv::BuiltInSubgroupSize;
534
Rex Xu574ab042016-04-14 16:53:07 +0800535 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800536 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800537 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
538 return spv::BuiltInSubgroupLocalInvocationId;
539
Rex Xu574ab042016-04-14 16:53:07 +0800540 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800541 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
542 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
543 return spv::BuiltInSubgroupEqMaskKHR;
544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupGeMaskKHR;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupGtMaskKHR;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupLeMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupLtMaskKHR;
564
Rex Xu9d93a232016-05-05 12:30:44 +0800565#ifdef AMD_EXTENSIONS
566 case glslang::EbvBaryCoordNoPersp: return spv::BuiltInBaryCoordNoPerspAMD;
567 case glslang::EbvBaryCoordNoPerspCentroid: return spv::BuiltInBaryCoordNoPerspCentroidAMD;
568 case glslang::EbvBaryCoordNoPerspSample: return spv::BuiltInBaryCoordNoPerspSampleAMD;
569 case glslang::EbvBaryCoordSmooth: return spv::BuiltInBaryCoordSmoothAMD;
570 case glslang::EbvBaryCoordSmoothCentroid: return spv::BuiltInBaryCoordSmoothCentroidAMD;
571 case glslang::EbvBaryCoordSmoothSample: return spv::BuiltInBaryCoordSmoothSampleAMD;
572 case glslang::EbvBaryCoordPullModel: return spv::BuiltInBaryCoordPullModelAMD;
573#endif
John Kessenich4016e382016-07-15 11:53:56 -0600574 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600575 }
576}
577
Rex Xufc618912015-09-09 16:42:49 +0800578// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700579spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800580{
581 assert(type.getBasicType() == glslang::EbtSampler);
582
John Kessenich5d0fa972016-02-15 11:57:00 -0700583 // Check for capabilities
584 switch (type.getQualifier().layoutFormat) {
585 case glslang::ElfRg32f:
586 case glslang::ElfRg16f:
587 case glslang::ElfR11fG11fB10f:
588 case glslang::ElfR16f:
589 case glslang::ElfRgba16:
590 case glslang::ElfRgb10A2:
591 case glslang::ElfRg16:
592 case glslang::ElfRg8:
593 case glslang::ElfR16:
594 case glslang::ElfR8:
595 case glslang::ElfRgba16Snorm:
596 case glslang::ElfRg16Snorm:
597 case glslang::ElfRg8Snorm:
598 case glslang::ElfR16Snorm:
599 case glslang::ElfR8Snorm:
600
601 case glslang::ElfRg32i:
602 case glslang::ElfRg16i:
603 case glslang::ElfRg8i:
604 case glslang::ElfR16i:
605 case glslang::ElfR8i:
606
607 case glslang::ElfRgb10a2ui:
608 case glslang::ElfRg32ui:
609 case glslang::ElfRg16ui:
610 case glslang::ElfRg8ui:
611 case glslang::ElfR16ui:
612 case glslang::ElfR8ui:
613 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
614 break;
615
616 default:
617 break;
618 }
619
620 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800621 switch (type.getQualifier().layoutFormat) {
622 case glslang::ElfNone: return spv::ImageFormatUnknown;
623 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
624 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
625 case glslang::ElfR32f: return spv::ImageFormatR32f;
626 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
627 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
628 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
629 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
630 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
631 case glslang::ElfR16f: return spv::ImageFormatR16f;
632 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
633 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
634 case glslang::ElfRg16: return spv::ImageFormatRg16;
635 case glslang::ElfRg8: return spv::ImageFormatRg8;
636 case glslang::ElfR16: return spv::ImageFormatR16;
637 case glslang::ElfR8: return spv::ImageFormatR8;
638 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
639 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
640 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
641 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
642 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
643 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
644 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
645 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
646 case glslang::ElfR32i: return spv::ImageFormatR32i;
647 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
648 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
649 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
650 case glslang::ElfR16i: return spv::ImageFormatR16i;
651 case glslang::ElfR8i: return spv::ImageFormatR8i;
652 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
653 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
654 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
655 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
656 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
657 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
658 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
659 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
660 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
661 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600662 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800663 }
664}
665
qining25262b32016-05-06 17:25:16 -0400666// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700667// descriptor set.
668bool IsDescriptorResource(const glslang::TType& type)
669{
John Kessenichf7497e22016-03-08 21:36:22 -0700670 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700671 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700672 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700673
674 // non block...
675 // basically samplerXXX/subpass/sampler/texture are all included
676 // if they are the global-scope-class, not the function parameter
677 // (or local, if they ever exist) class.
678 if (type.getBasicType() == glslang::EbtSampler)
679 return type.getQualifier().isUniformOrBuffer();
680
681 // None of the above.
682 return false;
683}
684
John Kesseniche0b6cad2015-12-24 10:30:13 -0700685void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
686{
687 if (child.layoutMatrix == glslang::ElmNone)
688 child.layoutMatrix = parent.layoutMatrix;
689
690 if (parent.invariant)
691 child.invariant = true;
692 if (parent.nopersp)
693 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800694#ifdef AMD_EXTENSIONS
695 if (parent.explicitInterp)
696 child.explicitInterp = true;
697#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700698 if (parent.flat)
699 child.flat = true;
700 if (parent.centroid)
701 child.centroid = true;
702 if (parent.patch)
703 child.patch = true;
704 if (parent.sample)
705 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800706 if (parent.coherent)
707 child.coherent = true;
708 if (parent.volatil)
709 child.volatil = true;
710 if (parent.restrict)
711 child.restrict = true;
712 if (parent.readonly)
713 child.readonly = true;
714 if (parent.writeonly)
715 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700716}
717
John Kessenichf2b7f332016-09-01 17:05:23 -0600718bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700719{
John Kessenich7b9fa252016-01-21 18:56:57 -0700720 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600721 // - struct members might inherit from a struct declaration
722 // (note that non-block structs don't explicitly inherit,
723 // only implicitly, meaning no decoration involved)
724 // - affect decorations on the struct members
725 // (note smooth does not, and expecting something like volatile
726 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700727 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600728 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700729}
730
John Kessenich140f3df2015-06-26 16:58:36 -0600731//
732// Implement the TGlslangToSpvTraverser class.
733//
734
Lei Zhang17535f72016-05-04 15:55:59 -0400735TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
736 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
737 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600738 inMain(false), mainTerminated(false), linkageOnly(false),
739 glslangIntermediate(glslangIntermediate)
740{
741 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
742
743 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700744 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600745 stdBuiltins = builder.import("GLSL.std.450");
746 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600747 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
748 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600749
750 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600751 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
752 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600753 builder.addSourceExtension(it->c_str());
754
755 // Add the top-level modes for this shader.
756
John Kessenich92187592016-02-01 13:45:25 -0700757 if (glslangIntermediate->getXfbMode()) {
758 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600759 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700760 }
John Kessenich140f3df2015-06-26 16:58:36 -0600761
762 unsigned int mode;
763 switch (glslangIntermediate->getStage()) {
764 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600765 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600766 break;
767
768 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600769 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600770 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
771 break;
772
773 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600774 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600775 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700776 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
777 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
778 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600779 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600780 }
John Kessenich4016e382016-07-15 11:53:56 -0600781 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600782 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
783
John Kesseniche6903322015-10-13 16:29:02 -0600784 switch (glslangIntermediate->getVertexSpacing()) {
785 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
786 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
787 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600788 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600789 }
John Kessenich4016e382016-07-15 11:53:56 -0600790 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600791 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
792
793 switch (glslangIntermediate->getVertexOrder()) {
794 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
795 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600796 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600797 }
John Kessenich4016e382016-07-15 11:53:56 -0600798 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600799 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
800
801 if (glslangIntermediate->getPointMode())
802 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600803 break;
804
805 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600806 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600807 switch (glslangIntermediate->getInputPrimitive()) {
808 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
809 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
810 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700811 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600812 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600813 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600814 }
John Kessenich4016e382016-07-15 11:53:56 -0600815 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600816 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600817
John Kessenich140f3df2015-06-26 16:58:36 -0600818 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
819
820 switch (glslangIntermediate->getOutputPrimitive()) {
821 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
822 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
823 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600824 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600825 }
John Kessenich4016e382016-07-15 11:53:56 -0600826 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600827 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
828 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
829 break;
830
831 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600832 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600833 if (glslangIntermediate->getPixelCenterInteger())
834 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600835
John Kessenich140f3df2015-06-26 16:58:36 -0600836 if (glslangIntermediate->getOriginUpperLeft())
837 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600838 else
839 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600840
841 if (glslangIntermediate->getEarlyFragmentTests())
842 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
843
844 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600845 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
846 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600847 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600848 }
John Kessenich4016e382016-07-15 11:53:56 -0600849 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600850 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
851
852 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
853 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600854 break;
855
856 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600857 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600858 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
859 glslangIntermediate->getLocalSize(1),
860 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600861 break;
862
863 default:
864 break;
865 }
866
867}
868
John Kessenich7ba63412015-12-20 17:37:07 -0700869// Finish everything and dump
870void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
871{
872 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100873 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
874 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700875
qiningda397332016-03-09 19:54:03 -0500876 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700877 builder.dump(out);
878}
879
John Kessenich140f3df2015-06-26 16:58:36 -0600880TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
881{
882 if (! mainTerminated) {
883 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
884 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600885 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600886 }
887}
888
889//
890// Implement the traversal functions.
891//
892// Return true from interior nodes to have the external traversal
893// continue on to children. Return false if children were
894// already processed.
895//
896
897//
qining25262b32016-05-06 17:25:16 -0400898// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600899// - uniform/input reads
900// - output writes
901// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
902// - something simple that degenerates into the last bullet
903//
904void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
905{
qining75d1d802016-04-06 14:42:01 -0400906 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
907 if (symbol->getType().getQualifier().isSpecConstant())
908 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
909
John Kessenich140f3df2015-06-26 16:58:36 -0600910 // getSymbolId() will set up all the IO decorations on the first call.
911 // Formal function parameters were mapped during makeFunctions().
912 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700913
914 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
915 if (builder.isPointer(id)) {
916 spv::StorageClass sc = builder.getStorageClass(id);
917 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
918 iOSet.insert(id);
919 }
920
921 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700922 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600923 // Prepare to generate code for the access
924
925 // L-value chains will be computed left to right. We're on the symbol now,
926 // which is the left-most part of the access chain, so now is "clear" time,
927 // followed by setting the base.
928 builder.clearAccessChain();
929
930 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700931 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600932 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700933 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600934 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700935 // These are also pure R-values.
936 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600937 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600938 builder.setAccessChainRValue(id);
939 else
940 builder.setAccessChainLValue(id);
941 }
942}
943
944bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
945{
qining40887662016-04-03 22:20:42 -0400946 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
947 if (node->getType().getQualifier().isSpecConstant())
948 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
949
John Kessenich140f3df2015-06-26 16:58:36 -0600950 // First, handle special cases
951 switch (node->getOp()) {
952 case glslang::EOpAssign:
953 case glslang::EOpAddAssign:
954 case glslang::EOpSubAssign:
955 case glslang::EOpMulAssign:
956 case glslang::EOpVectorTimesMatrixAssign:
957 case glslang::EOpVectorTimesScalarAssign:
958 case glslang::EOpMatrixTimesScalarAssign:
959 case glslang::EOpMatrixTimesMatrixAssign:
960 case glslang::EOpDivAssign:
961 case glslang::EOpModAssign:
962 case glslang::EOpAndAssign:
963 case glslang::EOpInclusiveOrAssign:
964 case glslang::EOpExclusiveOrAssign:
965 case glslang::EOpLeftShiftAssign:
966 case glslang::EOpRightShiftAssign:
967 // A bin-op assign "a += b" means the same thing as "a = a + b"
968 // where a is evaluated before b. For a simple assignment, GLSL
969 // says to evaluate the left before the right. So, always, left
970 // node then right node.
971 {
972 // get the left l-value, save it away
973 builder.clearAccessChain();
974 node->getLeft()->traverse(this);
975 spv::Builder::AccessChain lValue = builder.getAccessChain();
976
977 // evaluate the right
978 builder.clearAccessChain();
979 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700980 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600981
982 if (node->getOp() != glslang::EOpAssign) {
983 // the left is also an r-value
984 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700985 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600986
987 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -0600988 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -0400989 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -0600990 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
991 node->getType().getBasicType());
992
993 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700994 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600995 }
996
997 // store the result
998 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -0600999 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001000
1001 // assignments are expressions having an rValue after they are evaluated...
1002 builder.clearAccessChain();
1003 builder.setAccessChainRValue(rValue);
1004 }
1005 return false;
1006 case glslang::EOpIndexDirect:
1007 case glslang::EOpIndexDirectStruct:
1008 {
1009 // Get the left part of the access chain.
1010 node->getLeft()->traverse(this);
1011
1012 // Add the next element in the chain
1013
David Netoa901ffe2016-06-08 14:11:40 +01001014 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001015 if (! node->getLeft()->getType().isArray() &&
1016 node->getLeft()->getType().isVector() &&
1017 node->getOp() == glslang::EOpIndexDirect) {
1018 // This is essentially a hard-coded vector swizzle of size 1,
1019 // so short circuit the access-chain stuff with a swizzle.
1020 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001021 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001022 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001023 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001024 int spvIndex = glslangIndex;
1025 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1026 node->getOp() == glslang::EOpIndexDirectStruct)
1027 {
1028 // This may be, e.g., an anonymous block-member selection, which generally need
1029 // index remapping due to hidden members in anonymous blocks.
1030 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1031 assert(remapper.size() > 0);
1032 spvIndex = remapper[glslangIndex];
1033 }
John Kessenichebb50532016-05-16 19:22:05 -06001034
David Netoa901ffe2016-06-08 14:11:40 +01001035 // normal case for indexing array or structure or block
1036 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1037
1038 // Add capabilities here for accessing PointSize and clip/cull distance.
1039 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001040 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001041 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001042 }
1043 }
1044 return false;
1045 case glslang::EOpIndexIndirect:
1046 {
1047 // Structure or array or vector indirection.
1048 // Will use native SPIR-V access-chain for struct and array indirection;
1049 // matrices are arrays of vectors, so will also work for a matrix.
1050 // Will use the access chain's 'component' for variable index into a vector.
1051
1052 // This adapter is building access chains left to right.
1053 // Set up the access chain to the left.
1054 node->getLeft()->traverse(this);
1055
1056 // save it so that computing the right side doesn't trash it
1057 spv::Builder::AccessChain partial = builder.getAccessChain();
1058
1059 // compute the next index in the chain
1060 builder.clearAccessChain();
1061 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001062 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001063
1064 // restore the saved access chain
1065 builder.setAccessChain(partial);
1066
1067 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001068 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001069 else
John Kessenichfa668da2015-09-13 14:46:30 -06001070 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001071 }
1072 return false;
1073 case glslang::EOpVectorSwizzle:
1074 {
1075 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001076 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001077 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001078 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001079 }
1080 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001081 case glslang::EOpLogicalOr:
1082 case glslang::EOpLogicalAnd:
1083 {
1084
1085 // These may require short circuiting, but can sometimes be done as straight
1086 // binary operations. The right operand must be short circuited if it has
1087 // side effects, and should probably be if it is complex.
1088 if (isTrivial(node->getRight()->getAsTyped()))
1089 break; // handle below as a normal binary operation
1090 // otherwise, we need to do dynamic short circuiting on the right operand
1091 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1092 builder.clearAccessChain();
1093 builder.setAccessChainRValue(result);
1094 }
1095 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001096 default:
1097 break;
1098 }
1099
1100 // Assume generic binary op...
1101
John Kessenich32cfd492016-02-02 12:37:46 -07001102 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001103 builder.clearAccessChain();
1104 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001105 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001106
John Kessenich32cfd492016-02-02 12:37:46 -07001107 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001108 builder.clearAccessChain();
1109 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001110 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001111
John Kessenich32cfd492016-02-02 12:37:46 -07001112 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001113 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001114 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001115 convertGlslangToSpvType(node->getType()), left, right,
1116 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001117
John Kessenich50e57562015-12-21 21:21:11 -07001118 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001119 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001120 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001121 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001122 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001123 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001124 return false;
1125 }
John Kessenich140f3df2015-06-26 16:58:36 -06001126}
1127
1128bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1129{
qining40887662016-04-03 22:20:42 -04001130 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1131 if (node->getType().getQualifier().isSpecConstant())
1132 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1133
John Kessenichfc51d282015-08-19 13:34:18 -06001134 spv::Id result = spv::NoResult;
1135
1136 // try texturing first
1137 result = createImageTextureFunctionCall(node);
1138 if (result != spv::NoResult) {
1139 builder.clearAccessChain();
1140 builder.setAccessChainRValue(result);
1141
1142 return false; // done with this node
1143 }
1144
1145 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001146
1147 if (node->getOp() == glslang::EOpArrayLength) {
1148 // Quite special; won't want to evaluate the operand.
1149
1150 // Normal .length() would have been constant folded by the front-end.
1151 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001152 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001153 assert(node->getOperand()->getType().isRuntimeSizedArray());
1154 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1155 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001156 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1157 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001158
1159 builder.clearAccessChain();
1160 builder.setAccessChainRValue(length);
1161
1162 return false;
1163 }
1164
John Kessenichfc51d282015-08-19 13:34:18 -06001165 // Start by evaluating the operand
1166
John Kessenich8c8505c2016-07-26 12:50:38 -06001167 // Does it need a swizzle inversion? If so, evaluation is inverted;
1168 // operate first on the swizzle base, then apply the swizzle.
1169 spv::Id invertedType = spv::NoType;
1170 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1171 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1172 invertedType = getInvertedSwizzleType(*node->getOperand());
1173
John Kessenich140f3df2015-06-26 16:58:36 -06001174 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001175 if (invertedType != spv::NoType)
1176 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1177 else
1178 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001179
Rex Xufc618912015-09-09 16:42:49 +08001180 spv::Id operand = spv::NoResult;
1181
1182 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1183 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001184 node->getOp() == glslang::EOpAtomicCounter ||
1185 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001186 operand = builder.accessChainGetLValue(); // Special case l-value operands
1187 else
John Kessenich32cfd492016-02-02 12:37:46 -07001188 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001189
John Kessenichf6640762016-08-01 19:44:00 -06001190 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001191 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001192
1193 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001194 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001195 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001196
1197 // if not, then possibly an operation
1198 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001199 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001200
1201 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001202 if (invertedType)
1203 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1204
John Kessenich140f3df2015-06-26 16:58:36 -06001205 builder.clearAccessChain();
1206 builder.setAccessChainRValue(result);
1207
1208 return false; // done with this node
1209 }
1210
1211 // it must be a special case, check...
1212 switch (node->getOp()) {
1213 case glslang::EOpPostIncrement:
1214 case glslang::EOpPostDecrement:
1215 case glslang::EOpPreIncrement:
1216 case glslang::EOpPreDecrement:
1217 {
1218 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001219 spv::Id one = 0;
1220 if (node->getBasicType() == glslang::EbtFloat)
1221 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001222 else if (node->getBasicType() == glslang::EbtDouble)
1223 one = builder.makeDoubleConstant(1.0);
Rex Xu8ff43de2016-04-22 16:51:45 +08001224 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1225 one = builder.makeInt64Constant(1);
1226 else
1227 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001228 glslang::TOperator op;
1229 if (node->getOp() == glslang::EOpPreIncrement ||
1230 node->getOp() == glslang::EOpPostIncrement)
1231 op = glslang::EOpAdd;
1232 else
1233 op = glslang::EOpSub;
1234
John Kessenichf6640762016-08-01 19:44:00 -06001235 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001236 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001237 convertGlslangToSpvType(node->getType()), operand, one,
1238 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001239 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001240
1241 // The result of operation is always stored, but conditionally the
1242 // consumed result. The consumed result is always an r-value.
1243 builder.accessChainStore(result);
1244 builder.clearAccessChain();
1245 if (node->getOp() == glslang::EOpPreIncrement ||
1246 node->getOp() == glslang::EOpPreDecrement)
1247 builder.setAccessChainRValue(result);
1248 else
1249 builder.setAccessChainRValue(operand);
1250 }
1251
1252 return false;
1253
1254 case glslang::EOpEmitStreamVertex:
1255 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1256 return false;
1257 case glslang::EOpEndStreamPrimitive:
1258 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1259 return false;
1260
1261 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001262 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001263 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001264 }
John Kessenich140f3df2015-06-26 16:58:36 -06001265}
1266
1267bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1268{
qining27e04a02016-04-14 16:40:20 -04001269 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1270 if (node->getType().getQualifier().isSpecConstant())
1271 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1272
John Kessenichfc51d282015-08-19 13:34:18 -06001273 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001274 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1275 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001276
1277 // try texturing
1278 result = createImageTextureFunctionCall(node);
1279 if (result != spv::NoResult) {
1280 builder.clearAccessChain();
1281 builder.setAccessChainRValue(result);
1282
1283 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001284 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001285 // "imageStore" is a special case, which has no result
1286 return false;
1287 }
John Kessenichfc51d282015-08-19 13:34:18 -06001288
John Kessenich140f3df2015-06-26 16:58:36 -06001289 glslang::TOperator binOp = glslang::EOpNull;
1290 bool reduceComparison = true;
1291 bool isMatrix = false;
1292 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001293 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001294
1295 assert(node->getOp());
1296
John Kessenichf6640762016-08-01 19:44:00 -06001297 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 switch (node->getOp()) {
1300 case glslang::EOpSequence:
1301 {
1302 if (preVisit)
1303 ++sequenceDepth;
1304 else
1305 --sequenceDepth;
1306
1307 if (sequenceDepth == 1) {
1308 // If this is the parent node of all the functions, we want to see them
1309 // early, so all call points have actual SPIR-V functions to reference.
1310 // In all cases, still let the traverser visit the children for us.
1311 makeFunctions(node->getAsAggregate()->getSequence());
1312
John Kessenich6fccb3c2016-09-19 16:01:41 -06001313 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001314 // anything else gets there, so visit out of order, doing them all now.
1315 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1316
1317 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1318 // so do them manually.
1319 visitFunctions(node->getAsAggregate()->getSequence());
1320
1321 return false;
1322 }
1323
1324 return true;
1325 }
1326 case glslang::EOpLinkerObjects:
1327 {
1328 if (visit == glslang::EvPreVisit)
1329 linkageOnly = true;
1330 else
1331 linkageOnly = false;
1332
1333 return true;
1334 }
1335 case glslang::EOpComma:
1336 {
1337 // processing from left to right naturally leaves the right-most
1338 // lying around in the access chain
1339 glslang::TIntermSequence& glslangOperands = node->getSequence();
1340 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1341 glslangOperands[i]->traverse(this);
1342
1343 return false;
1344 }
1345 case glslang::EOpFunction:
1346 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001347 if (isShaderEntryPoint(node)) {
John Kessenich140f3df2015-06-26 16:58:36 -06001348 inMain = true;
1349 builder.setBuildPoint(shaderEntry->getLastBlock());
1350 } else {
1351 handleFunctionEntry(node);
1352 }
1353 } else {
1354 if (inMain)
1355 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001356 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001357 inMain = false;
1358 }
1359
1360 return true;
1361 case glslang::EOpParameters:
1362 // Parameters will have been consumed by EOpFunction processing, but not
1363 // the body, so we still visited the function node's children, making this
1364 // child redundant.
1365 return false;
1366 case glslang::EOpFunctionCall:
1367 {
1368 if (node->isUserDefined())
1369 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001370 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1371 if (result) {
1372 builder.clearAccessChain();
1373 builder.setAccessChainRValue(result);
1374 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001375 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001376
1377 return false;
1378 }
1379 case glslang::EOpConstructMat2x2:
1380 case glslang::EOpConstructMat2x3:
1381 case glslang::EOpConstructMat2x4:
1382 case glslang::EOpConstructMat3x2:
1383 case glslang::EOpConstructMat3x3:
1384 case glslang::EOpConstructMat3x4:
1385 case glslang::EOpConstructMat4x2:
1386 case glslang::EOpConstructMat4x3:
1387 case glslang::EOpConstructMat4x4:
1388 case glslang::EOpConstructDMat2x2:
1389 case glslang::EOpConstructDMat2x3:
1390 case glslang::EOpConstructDMat2x4:
1391 case glslang::EOpConstructDMat3x2:
1392 case glslang::EOpConstructDMat3x3:
1393 case glslang::EOpConstructDMat3x4:
1394 case glslang::EOpConstructDMat4x2:
1395 case glslang::EOpConstructDMat4x3:
1396 case glslang::EOpConstructDMat4x4:
1397 isMatrix = true;
1398 // fall through
1399 case glslang::EOpConstructFloat:
1400 case glslang::EOpConstructVec2:
1401 case glslang::EOpConstructVec3:
1402 case glslang::EOpConstructVec4:
1403 case glslang::EOpConstructDouble:
1404 case glslang::EOpConstructDVec2:
1405 case glslang::EOpConstructDVec3:
1406 case glslang::EOpConstructDVec4:
1407 case glslang::EOpConstructBool:
1408 case glslang::EOpConstructBVec2:
1409 case glslang::EOpConstructBVec3:
1410 case glslang::EOpConstructBVec4:
1411 case glslang::EOpConstructInt:
1412 case glslang::EOpConstructIVec2:
1413 case glslang::EOpConstructIVec3:
1414 case glslang::EOpConstructIVec4:
1415 case glslang::EOpConstructUint:
1416 case glslang::EOpConstructUVec2:
1417 case glslang::EOpConstructUVec3:
1418 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001419 case glslang::EOpConstructInt64:
1420 case glslang::EOpConstructI64Vec2:
1421 case glslang::EOpConstructI64Vec3:
1422 case glslang::EOpConstructI64Vec4:
1423 case glslang::EOpConstructUint64:
1424 case glslang::EOpConstructU64Vec2:
1425 case glslang::EOpConstructU64Vec3:
1426 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001427 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001428 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001429 {
1430 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001431 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001432 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001433 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001434 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001435 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001436 std::vector<spv::Id> constituents;
1437 for (int c = 0; c < (int)arguments.size(); ++c)
1438 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001439 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001440 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001441 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001442 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001443 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001444
1445 builder.clearAccessChain();
1446 builder.setAccessChainRValue(constructed);
1447
1448 return false;
1449 }
1450
1451 // These six are component-wise compares with component-wise results.
1452 // Forward on to createBinaryOperation(), requesting a vector result.
1453 case glslang::EOpLessThan:
1454 case glslang::EOpGreaterThan:
1455 case glslang::EOpLessThanEqual:
1456 case glslang::EOpGreaterThanEqual:
1457 case glslang::EOpVectorEqual:
1458 case glslang::EOpVectorNotEqual:
1459 {
1460 // Map the operation to a binary
1461 binOp = node->getOp();
1462 reduceComparison = false;
1463 switch (node->getOp()) {
1464 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1465 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1466 default: binOp = node->getOp(); break;
1467 }
1468
1469 break;
1470 }
1471 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001472 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001473 binOp = glslang::EOpMul;
1474 break;
1475 case glslang::EOpOuterProduct:
1476 // two vectors multiplied to make a matrix
1477 binOp = glslang::EOpOuterProduct;
1478 break;
1479 case glslang::EOpDot:
1480 {
qining25262b32016-05-06 17:25:16 -04001481 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001482 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001483 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001484 binOp = glslang::EOpMul;
1485 break;
1486 }
1487 case glslang::EOpMod:
1488 // when an aggregate, this is the floating-point mod built-in function,
1489 // which can be emitted by the one in createBinaryOperation()
1490 binOp = glslang::EOpMod;
1491 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001492 case glslang::EOpEmitVertex:
1493 case glslang::EOpEndPrimitive:
1494 case glslang::EOpBarrier:
1495 case glslang::EOpMemoryBarrier:
1496 case glslang::EOpMemoryBarrierAtomicCounter:
1497 case glslang::EOpMemoryBarrierBuffer:
1498 case glslang::EOpMemoryBarrierImage:
1499 case glslang::EOpMemoryBarrierShared:
1500 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001501 case glslang::EOpAllMemoryBarrierWithGroupSync:
1502 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1503 case glslang::EOpWorkgroupMemoryBarrier:
1504 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001505 noReturnValue = true;
1506 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1507 break;
1508
John Kessenich426394d2015-07-23 10:22:48 -06001509 case glslang::EOpAtomicAdd:
1510 case glslang::EOpAtomicMin:
1511 case glslang::EOpAtomicMax:
1512 case glslang::EOpAtomicAnd:
1513 case glslang::EOpAtomicOr:
1514 case glslang::EOpAtomicXor:
1515 case glslang::EOpAtomicExchange:
1516 case glslang::EOpAtomicCompSwap:
1517 atomic = true;
1518 break;
1519
John Kessenich140f3df2015-06-26 16:58:36 -06001520 default:
1521 break;
1522 }
1523
1524 //
1525 // See if it maps to a regular operation.
1526 //
John Kessenich140f3df2015-06-26 16:58:36 -06001527 if (binOp != glslang::EOpNull) {
1528 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1529 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1530 assert(left && right);
1531
1532 builder.clearAccessChain();
1533 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001534 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001535
1536 builder.clearAccessChain();
1537 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001538 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001539
qining25262b32016-05-06 17:25:16 -04001540 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001541 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001542 left->getType().getBasicType(), reduceComparison);
1543
1544 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001545 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001546 builder.clearAccessChain();
1547 builder.setAccessChainRValue(result);
1548
1549 return false;
1550 }
1551
John Kessenich426394d2015-07-23 10:22:48 -06001552 //
1553 // Create the list of operands.
1554 //
John Kessenich140f3df2015-06-26 16:58:36 -06001555 glslang::TIntermSequence& glslangOperands = node->getSequence();
1556 std::vector<spv::Id> operands;
1557 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001558 // special case l-value operands; there are just a few
1559 bool lvalue = false;
1560 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001561 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001562 case glslang::EOpModf:
1563 if (arg == 1)
1564 lvalue = true;
1565 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001566 case glslang::EOpInterpolateAtSample:
1567 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001568#ifdef AMD_EXTENSIONS
1569 case glslang::EOpInterpolateAtVertex:
1570#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001571 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001572 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001573
1574 // Does it need a swizzle inversion? If so, evaluation is inverted;
1575 // operate first on the swizzle base, then apply the swizzle.
1576 if (glslangOperands[0]->getAsOperator() &&
1577 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1578 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1579 }
Rex Xu7a26c172015-12-08 17:12:09 +08001580 break;
Rex Xud4782c12015-09-06 16:30:11 +08001581 case glslang::EOpAtomicAdd:
1582 case glslang::EOpAtomicMin:
1583 case glslang::EOpAtomicMax:
1584 case glslang::EOpAtomicAnd:
1585 case glslang::EOpAtomicOr:
1586 case glslang::EOpAtomicXor:
1587 case glslang::EOpAtomicExchange:
1588 case glslang::EOpAtomicCompSwap:
1589 if (arg == 0)
1590 lvalue = true;
1591 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001592 case glslang::EOpAddCarry:
1593 case glslang::EOpSubBorrow:
1594 if (arg == 2)
1595 lvalue = true;
1596 break;
1597 case glslang::EOpUMulExtended:
1598 case glslang::EOpIMulExtended:
1599 if (arg >= 2)
1600 lvalue = true;
1601 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001602 default:
1603 break;
1604 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001605 builder.clearAccessChain();
1606 if (invertedType != spv::NoType && arg == 0)
1607 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1608 else
1609 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001610 if (lvalue)
1611 operands.push_back(builder.accessChainGetLValue());
1612 else
John Kessenich32cfd492016-02-02 12:37:46 -07001613 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001614 }
John Kessenich426394d2015-07-23 10:22:48 -06001615
1616 if (atomic) {
1617 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001618 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001619 } else {
1620 // Pass through to generic operations.
1621 switch (glslangOperands.size()) {
1622 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001623 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001624 break;
1625 case 1:
qining25262b32016-05-06 17:25:16 -04001626 result = createUnaryOperation(
1627 node->getOp(), precision,
1628 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001629 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001630 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001631 break;
1632 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001633 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001634 break;
1635 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001636 if (invertedType)
1637 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001638 }
1639
1640 if (noReturnValue)
1641 return false;
1642
1643 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001644 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001645 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001646 } else {
1647 builder.clearAccessChain();
1648 builder.setAccessChainRValue(result);
1649 return false;
1650 }
1651}
1652
1653bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1654{
1655 // This path handles both if-then-else and ?:
1656 // The if-then-else has a node type of void, while
1657 // ?: has a non-void node type
1658 spv::Id result = 0;
1659 if (node->getBasicType() != glslang::EbtVoid) {
1660 // don't handle this as just on-the-fly temporaries, because there will be two names
1661 // and better to leave SSA to later passes
1662 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1663 }
1664
1665 // emit the condition before doing anything with selection
1666 node->getCondition()->traverse(this);
1667
1668 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001669 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001670
1671 if (node->getTrueBlock()) {
1672 // emit the "then" statement
1673 node->getTrueBlock()->traverse(this);
1674 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001675 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001676 }
1677
1678 if (node->getFalseBlock()) {
1679 ifBuilder.makeBeginElse();
1680 // emit the "else" statement
1681 node->getFalseBlock()->traverse(this);
1682 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001683 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001684 }
1685
1686 ifBuilder.makeEndIf();
1687
1688 if (result) {
1689 // GLSL only has r-values as the result of a :?, but
1690 // if we have an l-value, that can be more efficient if it will
1691 // become the base of a complex r-value expression, because the
1692 // next layer copies r-values into memory to use the access-chain mechanism
1693 builder.clearAccessChain();
1694 builder.setAccessChainLValue(result);
1695 }
1696
1697 return false;
1698}
1699
1700bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1701{
1702 // emit and get the condition before doing anything with switch
1703 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001704 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001705
1706 // browse the children to sort out code segments
1707 int defaultSegment = -1;
1708 std::vector<TIntermNode*> codeSegments;
1709 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1710 std::vector<int> caseValues;
1711 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1712 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1713 TIntermNode* child = *c;
1714 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001715 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001716 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001717 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001718 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1719 } else
1720 codeSegments.push_back(child);
1721 }
1722
qining25262b32016-05-06 17:25:16 -04001723 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001724 // statements between the last case and the end of the switch statement
1725 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1726 (int)codeSegments.size() == defaultSegment)
1727 codeSegments.push_back(nullptr);
1728
1729 // make the switch statement
1730 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001731 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001732
1733 // emit all the code in the segments
1734 breakForLoop.push(false);
1735 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1736 builder.nextSwitchSegment(segmentBlocks, s);
1737 if (codeSegments[s])
1738 codeSegments[s]->traverse(this);
1739 else
1740 builder.addSwitchBreak();
1741 }
1742 breakForLoop.pop();
1743
1744 builder.endSwitch(segmentBlocks);
1745
1746 return false;
1747}
1748
1749void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1750{
1751 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001752 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001753
1754 builder.clearAccessChain();
1755 builder.setAccessChainRValue(constant);
1756}
1757
1758bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1759{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001760 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001761 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001762 // Spec requires back edges to target header blocks, and every header block
1763 // must dominate its merge block. Make a header block first to ensure these
1764 // conditions are met. By definition, it will contain OpLoopMerge, followed
1765 // by a block-ending branch. But we don't want to put any other body/test
1766 // instructions in it, since the body/test may have arbitrary instructions,
1767 // including merges of its own.
1768 builder.setBuildPoint(&blocks.head);
1769 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001770 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001771 spv::Block& test = builder.makeNewBlock();
1772 builder.createBranch(&test);
1773
1774 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001775 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001776 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001777 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001778 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1779
1780 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001781 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001782 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001783 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001784 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001785 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001786
1787 builder.setBuildPoint(&blocks.continue_target);
1788 if (node->getTerminal())
1789 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001790 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001791 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001792 builder.createBranch(&blocks.body);
1793
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001794 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001795 builder.setBuildPoint(&blocks.body);
1796 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001797 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001798 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001799 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001800
1801 builder.setBuildPoint(&blocks.continue_target);
1802 if (node->getTerminal())
1803 node->getTerminal()->traverse(this);
1804 if (node->getTest()) {
1805 node->getTest()->traverse(this);
1806 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001807 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001808 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001809 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001810 // TODO: unless there was a break/return/discard instruction
1811 // somewhere in the body, this is an infinite loop, so we should
1812 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001813 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001814 }
John Kessenich140f3df2015-06-26 16:58:36 -06001815 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001816 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001817 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001818 return false;
1819}
1820
1821bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1822{
1823 if (node->getExpression())
1824 node->getExpression()->traverse(this);
1825
1826 switch (node->getFlowOp()) {
1827 case glslang::EOpKill:
1828 builder.makeDiscard();
1829 break;
1830 case glslang::EOpBreak:
1831 if (breakForLoop.top())
1832 builder.createLoopExit();
1833 else
1834 builder.addSwitchBreak();
1835 break;
1836 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001837 builder.createLoopContinue();
1838 break;
1839 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001840 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001841 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001842 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001843 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001844
1845 builder.clearAccessChain();
1846 break;
1847
1848 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001849 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001850 break;
1851 }
1852
1853 return false;
1854}
1855
1856spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1857{
qining25262b32016-05-06 17:25:16 -04001858 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001859 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001860 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001861 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001862 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001863 }
1864
1865 // Now, handle actual variables
1866 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1867 spv::Id spvType = convertGlslangToSpvType(node->getType());
1868
1869 const char* name = node->getName().c_str();
1870 if (glslang::IsAnonymous(name))
1871 name = "";
1872
1873 return builder.createVariable(storageClass, spvType, name);
1874}
1875
1876// Return type Id of the sampled type.
1877spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1878{
1879 switch (sampler.type) {
1880 case glslang::EbtFloat: return builder.makeFloatType(32);
1881 case glslang::EbtInt: return builder.makeIntType(32);
1882 case glslang::EbtUint: return builder.makeUintType(32);
1883 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001884 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001885 return builder.makeFloatType(32);
1886 }
1887}
1888
John Kessenich8c8505c2016-07-26 12:50:38 -06001889// If node is a swizzle operation, return the type that should be used if
1890// the swizzle base is first consumed by another operation, before the swizzle
1891// is applied.
1892spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1893{
1894 if (node.getAsOperator() &&
1895 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1896 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1897 else
1898 return spv::NoType;
1899}
1900
1901// When inverting a swizzle with a parent op, this function
1902// will apply the swizzle operation to a completed parent operation.
1903spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1904{
1905 std::vector<unsigned> swizzle;
1906 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1907 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1908}
1909
1910
1911// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1912void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1913{
1914 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1915 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1916 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1917}
1918
John Kessenich3ac051e2015-12-20 11:29:16 -07001919// Convert from a glslang type to an SPV type, by calling into a
1920// recursive version of this function. This establishes the inherited
1921// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001922spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1923{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001924 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001925}
1926
1927// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001928// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001929// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001930spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001931{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001932 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001933
1934 switch (type.getBasicType()) {
1935 case glslang::EbtVoid:
1936 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001937 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001938 break;
1939 case glslang::EbtFloat:
1940 spvType = builder.makeFloatType(32);
1941 break;
1942 case glslang::EbtDouble:
1943 spvType = builder.makeFloatType(64);
1944 break;
1945 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001946 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1947 // a 32-bit int where non-0 means true.
1948 if (explicitLayout != glslang::ElpNone)
1949 spvType = builder.makeUintType(32);
1950 else
1951 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001952 break;
1953 case glslang::EbtInt:
1954 spvType = builder.makeIntType(32);
1955 break;
1956 case glslang::EbtUint:
1957 spvType = builder.makeUintType(32);
1958 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001959 case glslang::EbtInt64:
1960 builder.addCapability(spv::CapabilityInt64);
1961 spvType = builder.makeIntType(64);
1962 break;
1963 case glslang::EbtUint64:
1964 builder.addCapability(spv::CapabilityInt64);
1965 spvType = builder.makeUintType(64);
1966 break;
John Kessenich426394d2015-07-23 10:22:48 -06001967 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06001968 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06001969 spvType = builder.makeUintType(32);
1970 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001971 case glslang::EbtSampler:
1972 {
1973 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001974 if (sampler.sampler) {
1975 // pure sampler
1976 spvType = builder.makeSamplerType();
1977 } else {
1978 // an image is present, make its type
1979 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1980 sampler.image ? 2 : 1, TranslateImageFormat(type));
1981 if (sampler.combined) {
1982 // already has both image and sampler, make the combined type
1983 spvType = builder.makeSampledImageType(spvType);
1984 }
John Kessenich55e7d112015-11-15 21:33:39 -07001985 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001986 }
John Kessenich140f3df2015-06-26 16:58:36 -06001987 break;
1988 case glslang::EbtStruct:
1989 case glslang::EbtBlock:
1990 {
1991 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06001992 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001993
1994 // Try to share structs for different layouts, but not yet for other
1995 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06001996 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06001997 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07001998 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001999 break;
2000
2001 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002002 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002003 memberRemapper[glslangMembers].resize(glslangMembers->size());
2004 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002005 }
2006 break;
2007 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002008 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002009 break;
2010 }
2011
2012 if (type.isMatrix())
2013 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2014 else {
2015 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2016 if (type.getVectorSize() > 1)
2017 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2018 }
2019
2020 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002021 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2022
John Kessenichc9a80832015-09-12 12:17:44 -06002023 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002024 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002025 // We need to decorate array strides for types needing explicit layout, except blocks.
2026 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002027 // Use a dummy glslang type for querying internal strides of
2028 // arrays of arrays, but using just a one-dimensional array.
2029 glslang::TType simpleArrayType(type, 0); // deference type of the array
2030 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2031 simpleArrayType.getArraySizes().dereference();
2032
2033 // Will compute the higher-order strides here, rather than making a whole
2034 // pile of types and doing repetitive recursion on their contents.
2035 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2036 }
John Kessenichf8842e52016-01-04 19:22:56 -07002037
2038 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002039 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002040 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002041 if (stride > 0)
2042 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002043 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002044 }
2045 } else {
2046 // single-dimensional array, and don't yet have stride
2047
John Kessenichf8842e52016-01-04 19:22:56 -07002048 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002049 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2050 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002051 }
John Kessenich31ed4832015-09-09 17:51:38 -06002052
John Kessenichc9a80832015-09-12 12:17:44 -06002053 // Do the outer dimension, which might not be known for a runtime-sized array
2054 if (type.isRuntimeSizedArray()) {
2055 spvType = builder.makeRuntimeArray(spvType);
2056 } else {
2057 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002058 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002059 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002060 if (stride > 0)
2061 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002062 }
2063
2064 return spvType;
2065}
2066
John Kessenich6090df02016-06-30 21:18:02 -06002067
2068// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2069// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2070// Mutually recursive with convertGlslangToSpvType().
2071spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2072 const glslang::TTypeList* glslangMembers,
2073 glslang::TLayoutPacking explicitLayout,
2074 const glslang::TQualifier& qualifier)
2075{
2076 // Create a vector of struct types for SPIR-V to consume
2077 std::vector<spv::Id> spvMembers;
2078 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2079 int locationOffset = 0; // for use across struct members, when they are called recursively
2080 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2081 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2082 if (glslangMember.hiddenMember()) {
2083 ++memberDelta;
2084 if (type.getBasicType() == glslang::EbtBlock)
2085 memberRemapper[glslangMembers][i] = -1;
2086 } else {
2087 if (type.getBasicType() == glslang::EbtBlock)
2088 memberRemapper[glslangMembers][i] = i - memberDelta;
2089 // modify just this child's view of the qualifier
2090 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2091 InheritQualifiers(memberQualifier, qualifier);
2092
2093 // manually inherit location; it's more complex
2094 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2095 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2096 if (qualifier.hasLocation())
2097 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2098
2099 // recurse
2100 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2101 }
2102 }
2103
2104 // Make the SPIR-V type
2105 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002106 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002107 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2108
2109 // Decorate it
2110 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2111
2112 return spvType;
2113}
2114
2115void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2116 const glslang::TTypeList* glslangMembers,
2117 glslang::TLayoutPacking explicitLayout,
2118 const glslang::TQualifier& qualifier,
2119 spv::Id spvType)
2120{
2121 // Name and decorate the non-hidden members
2122 int offset = -1;
2123 int locationOffset = 0; // for use within the members of this struct
2124 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2125 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2126 int member = i;
2127 if (type.getBasicType() == glslang::EbtBlock)
2128 member = memberRemapper[glslangMembers][i];
2129
2130 // modify just this child's view of the qualifier
2131 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2132 InheritQualifiers(memberQualifier, qualifier);
2133
2134 // using -1 above to indicate a hidden member
2135 if (member >= 0) {
2136 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2137 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2138 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2139 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2140 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2141 if (type.getBasicType() == glslang::EbtBlock) {
2142 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2143 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2144 }
2145 }
2146 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2147
2148 if (qualifier.storage == glslang::EvqBuffer) {
2149 std::vector<spv::Decoration> memory;
2150 TranslateMemoryDecoration(memberQualifier, memory);
2151 for (unsigned int i = 0; i < memory.size(); ++i)
2152 addMemberDecoration(spvType, member, memory[i]);
2153 }
2154
John Kessenich2f47bc92016-06-30 21:47:35 -06002155 // Compute location decoration; tricky based on whether inheritance is at play and
2156 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002157 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2158 // probably move to the linker stage of the front end proper, and just have the
2159 // answer sitting already distributed throughout the individual member locations.
2160 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002161 // Ignore member locations if the container is an array, as that's
2162 // ill-specified and decisions have been made to not allow this anyway.
2163 // The object itself must have a location, and that comes out from decorating the object,
2164 // not the type (this code decorates types).
2165 if (! type.isArray()) {
2166 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2167 // struct members should not have explicit locations
2168 assert(type.getBasicType() != glslang::EbtStruct);
2169 location = memberQualifier.layoutLocation;
2170 } else if (type.getBasicType() != glslang::EbtBlock) {
2171 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2172 // The members, and their nested types, must not themselves have Location decorations.
2173 } else if (qualifier.hasLocation()) // inheritance
2174 location = qualifier.layoutLocation + locationOffset;
2175 }
John Kessenich6090df02016-06-30 21:18:02 -06002176 if (location >= 0)
2177 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2178
John Kessenich2f47bc92016-06-30 21:47:35 -06002179 if (qualifier.hasLocation()) // track for upcoming inheritance
2180 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2181
John Kessenich6090df02016-06-30 21:18:02 -06002182 // component, XFB, others
2183 if (glslangMember.getQualifier().hasComponent())
2184 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2185 if (glslangMember.getQualifier().hasXfbOffset())
2186 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2187 else if (explicitLayout != glslang::ElpNone) {
2188 // figure out what to do with offset, which is accumulating
2189 int nextOffset;
2190 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2191 if (offset >= 0)
2192 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2193 offset = nextOffset;
2194 }
2195
2196 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2197 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2198
2199 // built-in variable decorations
2200 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002201 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002202 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2203 }
2204 }
2205
2206 // Decorate the structure
2207 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2208 addDecoration(spvType, TranslateBlockDecoration(type));
2209 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2210 builder.addCapability(spv::CapabilityGeometryStreams);
2211 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2212 }
2213 if (glslangIntermediate->getXfbMode()) {
2214 builder.addCapability(spv::CapabilityTransformFeedback);
2215 if (type.getQualifier().hasXfbStride())
2216 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2217 if (type.getQualifier().hasXfbBuffer())
2218 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2219 }
2220}
2221
John Kessenich6c292d32016-02-15 20:58:50 -07002222// Turn the expression forming the array size into an id.
2223// This is not quite trivial, because of specialization constants.
2224// Sometimes, a raw constant is turned into an Id, and sometimes
2225// a specialization constant expression is.
2226spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2227{
2228 // First, see if this is sized with a node, meaning a specialization constant:
2229 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2230 if (specNode != nullptr) {
2231 builder.clearAccessChain();
2232 specNode->traverse(this);
2233 return accessChainLoad(specNode->getAsTyped()->getType());
2234 }
qining25262b32016-05-06 17:25:16 -04002235
John Kessenich6c292d32016-02-15 20:58:50 -07002236 // Otherwise, need a compile-time (front end) size, get it:
2237 int size = arraySizes.getDimSize(dim);
2238 assert(size > 0);
2239 return builder.makeUintConstant(size);
2240}
2241
John Kessenich103bef92016-02-08 21:38:15 -07002242// Wrap the builder's accessChainLoad to:
2243// - localize handling of RelaxedPrecision
2244// - use the SPIR-V inferred type instead of another conversion of the glslang type
2245// (avoids unnecessary work and possible type punning for structures)
2246// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002247spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2248{
John Kessenich103bef92016-02-08 21:38:15 -07002249 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2250 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2251
2252 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002253 if (type.getBasicType() == glslang::EbtBool) {
2254 if (builder.isScalarType(nominalTypeId)) {
2255 // Conversion for bool
2256 spv::Id boolType = builder.makeBoolType();
2257 if (nominalTypeId != boolType)
2258 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2259 } else if (builder.isVectorType(nominalTypeId)) {
2260 // Conversion for bvec
2261 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2262 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2263 if (nominalTypeId != bvecType)
2264 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2265 }
2266 }
John Kessenich103bef92016-02-08 21:38:15 -07002267
2268 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002269}
2270
Rex Xu27253232016-02-23 17:51:09 +08002271// Wrap the builder's accessChainStore to:
2272// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002273//
2274// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002275void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2276{
2277 // Need to convert to abstract types when necessary
2278 if (type.getBasicType() == glslang::EbtBool) {
2279 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2280
2281 if (builder.isScalarType(nominalTypeId)) {
2282 // Conversion for bool
2283 spv::Id boolType = builder.makeBoolType();
2284 if (nominalTypeId != boolType) {
2285 spv::Id zero = builder.makeUintConstant(0);
2286 spv::Id one = builder.makeUintConstant(1);
2287 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2288 }
2289 } else if (builder.isVectorType(nominalTypeId)) {
2290 // Conversion for bvec
2291 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2292 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2293 if (nominalTypeId != bvecType) {
2294 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2295 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2296 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2297 }
2298 }
2299 }
2300
2301 builder.accessChainStore(rvalue);
2302}
2303
John Kessenich4bf71552016-09-02 11:20:21 -06002304// For storing when types match at the glslang level, but not might match at the
2305// SPIR-V level.
2306//
2307// This especially happens when a single glslang type expands to multiple
2308// SPIR-V types, like a struct that is used in an member-undecorated way as well
2309// as in a member-decorated way.
2310//
2311// NOTE: This function can handle any store request; if it's not special it
2312// simplifies to a simple OpStore.
2313//
2314// Implicitly uses the existing builder.accessChain as the storage target.
2315void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2316{
John Kessenichb3e24e42016-09-11 12:33:43 -06002317 // we only do the complex path here if it's an aggregate
2318 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002319 accessChainStore(type, rValue);
2320 return;
2321 }
2322
John Kessenichb3e24e42016-09-11 12:33:43 -06002323 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002324 spv::Id rType = builder.getTypeId(rValue);
2325 spv::Id lValue = builder.accessChainGetLValue();
2326 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2327 if (lType == rType) {
2328 accessChainStore(type, rValue);
2329 return;
2330 }
2331
John Kessenichb3e24e42016-09-11 12:33:43 -06002332 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002333 // where the two types were the same type in GLSL. This requires member
2334 // by member copy, recursively.
2335
John Kessenichb3e24e42016-09-11 12:33:43 -06002336 // If an array, copy element by element.
2337 if (type.isArray()) {
2338 glslang::TType glslangElementType(type, 0);
2339 spv::Id elementRType = builder.getContainedTypeId(rType);
2340 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2341 // get the source member
2342 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002343
John Kessenichb3e24e42016-09-11 12:33:43 -06002344 // set up the target storage
2345 builder.clearAccessChain();
2346 builder.setAccessChainLValue(lValue);
2347 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002348
John Kessenichb3e24e42016-09-11 12:33:43 -06002349 // store the member
2350 multiTypeStore(glslangElementType, elementRValue);
2351 }
2352 } else {
2353 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002354
John Kessenichb3e24e42016-09-11 12:33:43 -06002355 // loop over structure members
2356 const glslang::TTypeList& members = *type.getStruct();
2357 for (int m = 0; m < (int)members.size(); ++m) {
2358 const glslang::TType& glslangMemberType = *members[m].type;
2359
2360 // get the source member
2361 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2362 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2363
2364 // set up the target storage
2365 builder.clearAccessChain();
2366 builder.setAccessChainLValue(lValue);
2367 builder.accessChainPush(builder.makeIntConstant(m));
2368
2369 // store the member
2370 multiTypeStore(glslangMemberType, memberRValue);
2371 }
John Kessenich4bf71552016-09-02 11:20:21 -06002372 }
2373}
2374
John Kessenichf85e8062015-12-19 13:57:10 -07002375// Decide whether or not this type should be
2376// decorated with offsets and strides, and if so
2377// whether std140 or std430 rules should be applied.
2378glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002379{
John Kessenichf85e8062015-12-19 13:57:10 -07002380 // has to be a block
2381 if (type.getBasicType() != glslang::EbtBlock)
2382 return glslang::ElpNone;
2383
2384 // has to be a uniform or buffer block
2385 if (type.getQualifier().storage != glslang::EvqUniform &&
2386 type.getQualifier().storage != glslang::EvqBuffer)
2387 return glslang::ElpNone;
2388
2389 // return the layout to use
2390 switch (type.getQualifier().layoutPacking) {
2391 case glslang::ElpStd140:
2392 case glslang::ElpStd430:
2393 return type.getQualifier().layoutPacking;
2394 default:
2395 return glslang::ElpNone;
2396 }
John Kessenich31ed4832015-09-09 17:51:38 -06002397}
2398
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002399// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002400int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002401{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002402 int size;
John Kessenich49987892015-12-29 17:11:44 -07002403 int stride;
2404 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002405
2406 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002407}
2408
John Kessenich49987892015-12-29 17:11:44 -07002409// 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 -07002410// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002411int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002412{
John Kessenich49987892015-12-29 17:11:44 -07002413 glslang::TType elementType;
2414 elementType.shallowCopy(matrixType);
2415 elementType.clearArraySizes();
2416
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002417 int size;
John Kessenich49987892015-12-29 17:11:44 -07002418 int stride;
2419 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2420
2421 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002422}
2423
John Kessenich5e4b1242015-08-06 22:53:06 -06002424// Given a member type of a struct, realign the current offset for it, and compute
2425// the next (not yet aligned) offset for the next member, which will get aligned
2426// on the next call.
2427// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2428// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2429// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002430void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002431 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002432{
2433 // this will get a positive value when deemed necessary
2434 nextOffset = -1;
2435
John Kessenich5e4b1242015-08-06 22:53:06 -06002436 // override anything in currentOffset with user-set offset
2437 if (memberType.getQualifier().hasOffset())
2438 currentOffset = memberType.getQualifier().layoutOffset;
2439
2440 // It could be that current linker usage in glslang updated all the layoutOffset,
2441 // in which case the following code does not matter. But, that's not quite right
2442 // once cross-compilation unit GLSL validation is done, as the original user
2443 // settings are needed in layoutOffset, and then the following will come into play.
2444
John Kessenichf85e8062015-12-19 13:57:10 -07002445 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002446 if (! memberType.getQualifier().hasOffset())
2447 currentOffset = -1;
2448
2449 return;
2450 }
2451
John Kessenichf85e8062015-12-19 13:57:10 -07002452 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002453 if (currentOffset < 0)
2454 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002455
John Kessenich5e4b1242015-08-06 22:53:06 -06002456 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2457 // but possibly not yet correctly aligned.
2458
2459 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002460 int dummyStride;
2461 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002462 glslang::RoundToPow2(currentOffset, memberAlignment);
2463 nextOffset = currentOffset + memberSize;
2464}
2465
David Netoa901ffe2016-06-08 14:11:40 +01002466void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002467{
David Netoa901ffe2016-06-08 14:11:40 +01002468 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2469 switch (glslangBuiltIn)
2470 {
2471 case glslang::EbvClipDistance:
2472 case glslang::EbvCullDistance:
2473 case glslang::EbvPointSize:
2474 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2475 // Alternately, we could just call this for any glslang built-in, since the
2476 // capability already guards against duplicates.
2477 TranslateBuiltInDecoration(glslangBuiltIn, false);
2478 break;
2479 default:
2480 // Capabilities were already generated when the struct was declared.
2481 break;
2482 }
John Kessenichebb50532016-05-16 19:22:05 -06002483}
2484
John Kessenich6fccb3c2016-09-19 16:01:41 -06002485bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002486{
John Kessenicheee9d532016-09-19 18:09:30 -06002487 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002488}
2489
2490// Make all the functions, skeletally, without actually visiting their bodies.
2491void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2492{
2493 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2494 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002495 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002496 continue;
2497
2498 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002499 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002500 //
qining25262b32016-05-06 17:25:16 -04002501 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002502 // function. What it is an address of varies:
2503 //
John Kessenich4bf71552016-09-02 11:20:21 -06002504 // - "in" parameters not marked as "const" can be written to without modifying the calling
2505 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002506 //
2507 // - "const in" parameters can just be the r-value, as no writes need occur.
2508 //
John Kessenich4bf71552016-09-02 11:20:21 -06002509 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2510 // 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 -06002511
2512 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002513 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002514 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2515
2516 for (int p = 0; p < (int)parameters.size(); ++p) {
2517 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2518 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002519 if (paramType.isOpaque())
2520 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2521 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002522 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2523 else
John Kessenich4bf71552016-09-02 11:20:21 -06002524 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002525 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002526 paramTypes.push_back(typeId);
2527 }
2528
2529 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002530 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2531 convertGlslangToSpvType(glslFunction->getType()),
2532 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002533
2534 // Track function to emit/call later
2535 functionMap[glslFunction->getName().c_str()] = function;
2536
2537 // Set the parameter id's
2538 for (int p = 0; p < (int)parameters.size(); ++p) {
2539 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2540 // give a name too
2541 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2542 }
2543 }
2544}
2545
2546// Process all the initializers, while skipping the functions and link objects
2547void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2548{
2549 builder.setBuildPoint(shaderEntry->getLastBlock());
2550 for (int i = 0; i < (int)initializers.size(); ++i) {
2551 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2552 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2553
2554 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002555 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002556 initializer->traverse(this);
2557 }
2558 }
2559}
2560
2561// Process all the functions, while skipping initializers.
2562void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2563{
2564 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2565 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2566 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2567 node->traverse(this);
2568 }
2569}
2570
2571void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2572{
qining25262b32016-05-06 17:25:16 -04002573 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002574 // that called makeFunctions().
2575 spv::Function* function = functionMap[node->getName().c_str()];
2576 spv::Block* functionBlock = function->getEntryBlock();
2577 builder.setBuildPoint(functionBlock);
2578}
2579
Rex Xu04db3f52015-09-16 11:44:02 +08002580void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002581{
Rex Xufc618912015-09-09 16:42:49 +08002582 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002583
2584 glslang::TSampler sampler = {};
2585 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002586 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002587 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2588 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2589 }
2590
John Kessenich140f3df2015-06-26 16:58:36 -06002591 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2592 builder.clearAccessChain();
2593 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002594
2595 // Special case l-value operands
2596 bool lvalue = false;
2597 switch (node.getOp()) {
2598 case glslang::EOpImageAtomicAdd:
2599 case glslang::EOpImageAtomicMin:
2600 case glslang::EOpImageAtomicMax:
2601 case glslang::EOpImageAtomicAnd:
2602 case glslang::EOpImageAtomicOr:
2603 case glslang::EOpImageAtomicXor:
2604 case glslang::EOpImageAtomicExchange:
2605 case glslang::EOpImageAtomicCompSwap:
2606 if (i == 0)
2607 lvalue = true;
2608 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002609 case glslang::EOpSparseImageLoad:
2610 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2611 lvalue = true;
2612 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002613 case glslang::EOpSparseTexture:
2614 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2615 lvalue = true;
2616 break;
2617 case glslang::EOpSparseTextureClamp:
2618 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2619 lvalue = true;
2620 break;
2621 case glslang::EOpSparseTextureLod:
2622 case glslang::EOpSparseTextureOffset:
2623 if (i == 3)
2624 lvalue = true;
2625 break;
2626 case glslang::EOpSparseTextureFetch:
2627 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2628 lvalue = true;
2629 break;
2630 case glslang::EOpSparseTextureFetchOffset:
2631 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2632 lvalue = true;
2633 break;
2634 case glslang::EOpSparseTextureLodOffset:
2635 case glslang::EOpSparseTextureGrad:
2636 case glslang::EOpSparseTextureOffsetClamp:
2637 if (i == 4)
2638 lvalue = true;
2639 break;
2640 case glslang::EOpSparseTextureGradOffset:
2641 case glslang::EOpSparseTextureGradClamp:
2642 if (i == 5)
2643 lvalue = true;
2644 break;
2645 case glslang::EOpSparseTextureGradOffsetClamp:
2646 if (i == 6)
2647 lvalue = true;
2648 break;
2649 case glslang::EOpSparseTextureGather:
2650 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2651 lvalue = true;
2652 break;
2653 case glslang::EOpSparseTextureGatherOffset:
2654 case glslang::EOpSparseTextureGatherOffsets:
2655 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2656 lvalue = true;
2657 break;
Rex Xufc618912015-09-09 16:42:49 +08002658 default:
2659 break;
2660 }
2661
Rex Xu6b86d492015-09-16 17:48:22 +08002662 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002663 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002664 else
John Kessenich32cfd492016-02-02 12:37:46 -07002665 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002666 }
2667}
2668
John Kessenichfc51d282015-08-19 13:34:18 -06002669void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002670{
John Kessenichfc51d282015-08-19 13:34:18 -06002671 builder.clearAccessChain();
2672 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002673 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002674}
John Kessenich140f3df2015-06-26 16:58:36 -06002675
John Kessenichfc51d282015-08-19 13:34:18 -06002676spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2677{
Rex Xufc618912015-09-09 16:42:49 +08002678 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002679 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002680 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002681 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002682
John Kessenichfc51d282015-08-19 13:34:18 -06002683 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002684 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2685 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2686 std::vector<spv::Id> arguments;
2687 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002688 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002689 else
2690 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002691 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002692
2693 spv::Builder::TextureParameters params = { };
2694 params.sampler = arguments[0];
2695
Rex Xu04db3f52015-09-16 11:44:02 +08002696 glslang::TCrackedTextureOp cracked;
2697 node->crackTexture(sampler, cracked);
2698
John Kessenichfc51d282015-08-19 13:34:18 -06002699 // Check for queries
2700 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002701 // a sampled image needs to have the image extracted first
2702 if (builder.isSampledImage(params.sampler))
2703 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002704 switch (node->getOp()) {
2705 case glslang::EOpImageQuerySize:
2706 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002707 if (arguments.size() > 1) {
2708 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002709 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002710 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002711 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002712 case glslang::EOpImageQuerySamples:
2713 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002714 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002715 case glslang::EOpTextureQueryLod:
2716 params.coords = arguments[1];
2717 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2718 case glslang::EOpTextureQueryLevels:
2719 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002720 case glslang::EOpSparseTexelsResident:
2721 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002722 default:
2723 assert(0);
2724 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002725 }
John Kessenich140f3df2015-06-26 16:58:36 -06002726 }
2727
Rex Xufc618912015-09-09 16:42:49 +08002728 // Check for image functions other than queries
2729 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002730 std::vector<spv::Id> operands;
2731 auto opIt = arguments.begin();
2732 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002733
2734 // Handle subpass operations
2735 // TODO: GLSL should change to have the "MS" only on the type rather than the
2736 // built-in function.
2737 if (cracked.subpass) {
2738 // add on the (0,0) coordinate
2739 spv::Id zero = builder.makeIntConstant(0);
2740 std::vector<spv::Id> comps;
2741 comps.push_back(zero);
2742 comps.push_back(zero);
2743 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2744 if (sampler.ms) {
2745 operands.push_back(spv::ImageOperandsSampleMask);
2746 operands.push_back(*(opIt++));
2747 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002748 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002749 }
2750
John Kessenich56bab042015-09-16 10:54:31 -06002751 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002752 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002753 if (sampler.ms) {
2754 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002755 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002756 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002757 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2758 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002759 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002760 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002761 if (sampler.ms) {
2762 operands.push_back(*(opIt + 1));
2763 operands.push_back(spv::ImageOperandsSampleMask);
2764 operands.push_back(*opIt);
2765 } else
2766 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002767 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002768 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2769 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002770 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002771 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2772 builder.addCapability(spv::CapabilitySparseResidency);
2773 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2774 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2775
2776 if (sampler.ms) {
2777 operands.push_back(spv::ImageOperandsSampleMask);
2778 operands.push_back(*opIt++);
2779 }
2780
2781 // Create the return type that was a special structure
2782 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002783 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002784 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2785 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2786
2787 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2788
2789 // Decode the return type
2790 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2791 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002792 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002793 // Process image atomic operations
2794
2795 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2796 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002797 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002798
John Kessenich8c8505c2016-07-26 12:50:38 -06002799 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002800 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002801
2802 std::vector<spv::Id> operands;
2803 operands.push_back(pointer);
2804 for (; opIt != arguments.end(); ++opIt)
2805 operands.push_back(*opIt);
2806
John Kessenich8c8505c2016-07-26 12:50:38 -06002807 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002808 }
2809 }
2810
2811 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002812 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002813 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2814
John Kessenichfc51d282015-08-19 13:34:18 -06002815 // check for bias argument
2816 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002817 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002818 int nonBiasArgCount = 2;
2819 if (cracked.offset)
2820 ++nonBiasArgCount;
2821 if (cracked.grad)
2822 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002823 if (cracked.lodClamp)
2824 ++nonBiasArgCount;
2825 if (sparse)
2826 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002827
2828 if ((int)arguments.size() > nonBiasArgCount)
2829 bias = true;
2830 }
2831
John Kessenicha5c33d62016-06-02 23:45:21 -06002832 // See if the sampler param should really be just the SPV image part
2833 if (cracked.fetch) {
2834 // a fetch needs to have the image extracted first
2835 if (builder.isSampledImage(params.sampler))
2836 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2837 }
2838
John Kessenichfc51d282015-08-19 13:34:18 -06002839 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002840
John Kessenichfc51d282015-08-19 13:34:18 -06002841 params.coords = arguments[1];
2842 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002843 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002844
2845 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002846 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002847 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002848 ++extraArgs;
2849 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002850 params.Dref = arguments[2];
2851 ++extraArgs;
2852 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002853 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002854 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002855 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002856 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002857 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002858 dRefComp = builder.getNumComponents(params.coords) - 1;
2859 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002860 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2861 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002862
2863 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002864 if (cracked.lod) {
2865 params.lod = arguments[2];
2866 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002867 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2868 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2869 noImplicitLod = true;
2870 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002871
2872 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002873 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002874 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002875 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002876 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002877
2878 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002879 if (cracked.grad) {
2880 params.gradX = arguments[2 + extraArgs];
2881 params.gradY = arguments[3 + extraArgs];
2882 extraArgs += 2;
2883 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002884
2885 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002886 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002887 params.offset = arguments[2 + extraArgs];
2888 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002889 } else if (cracked.offsets) {
2890 params.offsets = arguments[2 + extraArgs];
2891 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002892 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002893
2894 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002895 if (cracked.lodClamp) {
2896 params.lodClamp = arguments[2 + extraArgs];
2897 ++extraArgs;
2898 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002899
2900 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002901 if (sparse) {
2902 params.texelOut = arguments[2 + extraArgs];
2903 ++extraArgs;
2904 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002905
2906 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002907 if (bias) {
2908 params.bias = arguments[2 + extraArgs];
2909 ++extraArgs;
2910 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002911
2912 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002913 if (cracked.gather && ! sampler.shadow) {
2914 // default component is 0, if missing, otherwise an argument
2915 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002916 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002917 ++extraArgs;
2918 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002919 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002920 }
2921 }
John Kessenichfc51d282015-08-19 13:34:18 -06002922
John Kessenich65336482016-06-16 14:06:26 -06002923 // projective component (might not to move)
2924 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2925 // are divided by the last component of P."
2926 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2927 // unused components will appear after all used components."
2928 if (cracked.proj) {
2929 int projSourceComp = builder.getNumComponents(params.coords) - 1;
2930 int projTargetComp;
2931 switch (sampler.dim) {
2932 case glslang::Esd1D: projTargetComp = 1; break;
2933 case glslang::Esd2D: projTargetComp = 2; break;
2934 case glslang::EsdRect: projTargetComp = 2; break;
2935 default: projTargetComp = projSourceComp; break;
2936 }
2937 // copy the projective coordinate if we have to
2938 if (projTargetComp != projSourceComp) {
2939 spv::Id projComp = builder.createCompositeExtract(params.coords,
2940 builder.getScalarTypeId(builder.getTypeId(params.coords)),
2941 projSourceComp);
2942 params.coords = builder.createCompositeInsert(projComp, params.coords,
2943 builder.getTypeId(params.coords), projTargetComp);
2944 }
2945 }
2946
John Kessenich8c8505c2016-07-26 12:50:38 -06002947 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002948}
2949
2950spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2951{
2952 // Grab the function's pointer from the previously created function
2953 spv::Function* function = functionMap[node->getName().c_str()];
2954 if (! function)
2955 return 0;
2956
2957 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2958 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2959
2960 // See comments in makeFunctions() for details about the semantics for parameter passing.
2961 //
2962 // These imply we need a four step process:
2963 // 1. Evaluate the arguments
2964 // 2. Allocate and make copies of in, out, and inout arguments
2965 // 3. Make the call
2966 // 4. Copy back the results
2967
2968 // 1. Evaluate the arguments
2969 std::vector<spv::Builder::AccessChain> lValues;
2970 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002971 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002973 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002974 // build l-value
2975 builder.clearAccessChain();
2976 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002977 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06002978 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07002979 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002980 // save l-value
2981 lValues.push_back(builder.getAccessChain());
2982 } else {
2983 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002984 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002985 }
2986 }
2987
2988 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2989 // copy the original into that space.
2990 //
2991 // Also, build up the list of actual arguments to pass in for the call
2992 int lValueCount = 0;
2993 int rValueCount = 0;
2994 std::vector<spv::Id> spvArgs;
2995 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002996 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06002997 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07002998 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07002999 builder.setAccessChain(lValues[lValueCount]);
3000 arg = builder.accessChainGetLValue();
3001 ++lValueCount;
3002 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003003 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003004 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3005 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3006 // need to copy the input into output space
3007 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003008 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003009 builder.clearAccessChain();
3010 builder.setAccessChainLValue(arg);
3011 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003012 }
3013 ++lValueCount;
3014 } else {
3015 arg = rValues[rValueCount];
3016 ++rValueCount;
3017 }
3018 spvArgs.push_back(arg);
3019 }
3020
3021 // 3. Make the call.
3022 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003023 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003024
3025 // 4. Copy back out an "out" arguments.
3026 lValueCount = 0;
3027 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003028 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003029 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3030 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3031 spv::Id copy = builder.createLoad(spvArgs[a]);
3032 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003033 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003034 }
3035 ++lValueCount;
3036 }
3037 }
3038
3039 return result;
3040}
3041
3042// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003043spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3044 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003045 spv::Id typeId, spv::Id left, spv::Id right,
3046 glslang::TBasicType typeProxy, bool reduceComparison)
3047{
Rex Xu8ff43de2016-04-22 16:51:45 +08003048 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08003050 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003051
3052 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003053 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003054 bool comparison = false;
3055
3056 switch (op) {
3057 case glslang::EOpAdd:
3058 case glslang::EOpAddAssign:
3059 if (isFloat)
3060 binOp = spv::OpFAdd;
3061 else
3062 binOp = spv::OpIAdd;
3063 break;
3064 case glslang::EOpSub:
3065 case glslang::EOpSubAssign:
3066 if (isFloat)
3067 binOp = spv::OpFSub;
3068 else
3069 binOp = spv::OpISub;
3070 break;
3071 case glslang::EOpMul:
3072 case glslang::EOpMulAssign:
3073 if (isFloat)
3074 binOp = spv::OpFMul;
3075 else
3076 binOp = spv::OpIMul;
3077 break;
3078 case glslang::EOpVectorTimesScalar:
3079 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003080 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003081 if (builder.isVector(right))
3082 std::swap(left, right);
3083 assert(builder.isScalar(right));
3084 needMatchingVectors = false;
3085 binOp = spv::OpVectorTimesScalar;
3086 } else
3087 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
3089 case glslang::EOpVectorTimesMatrix:
3090 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003091 binOp = spv::OpVectorTimesMatrix;
3092 break;
3093 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003094 binOp = spv::OpMatrixTimesVector;
3095 break;
3096 case glslang::EOpMatrixTimesScalar:
3097 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003098 binOp = spv::OpMatrixTimesScalar;
3099 break;
3100 case glslang::EOpMatrixTimesMatrix:
3101 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003102 binOp = spv::OpMatrixTimesMatrix;
3103 break;
3104 case glslang::EOpOuterProduct:
3105 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003106 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003107 break;
3108
3109 case glslang::EOpDiv:
3110 case glslang::EOpDivAssign:
3111 if (isFloat)
3112 binOp = spv::OpFDiv;
3113 else if (isUnsigned)
3114 binOp = spv::OpUDiv;
3115 else
3116 binOp = spv::OpSDiv;
3117 break;
3118 case glslang::EOpMod:
3119 case glslang::EOpModAssign:
3120 if (isFloat)
3121 binOp = spv::OpFMod;
3122 else if (isUnsigned)
3123 binOp = spv::OpUMod;
3124 else
3125 binOp = spv::OpSMod;
3126 break;
3127 case glslang::EOpRightShift:
3128 case glslang::EOpRightShiftAssign:
3129 if (isUnsigned)
3130 binOp = spv::OpShiftRightLogical;
3131 else
3132 binOp = spv::OpShiftRightArithmetic;
3133 break;
3134 case glslang::EOpLeftShift:
3135 case glslang::EOpLeftShiftAssign:
3136 binOp = spv::OpShiftLeftLogical;
3137 break;
3138 case glslang::EOpAnd:
3139 case glslang::EOpAndAssign:
3140 binOp = spv::OpBitwiseAnd;
3141 break;
3142 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003143 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003144 binOp = spv::OpLogicalAnd;
3145 break;
3146 case glslang::EOpInclusiveOr:
3147 case glslang::EOpInclusiveOrAssign:
3148 binOp = spv::OpBitwiseOr;
3149 break;
3150 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003151 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003152 binOp = spv::OpLogicalOr;
3153 break;
3154 case glslang::EOpExclusiveOr:
3155 case glslang::EOpExclusiveOrAssign:
3156 binOp = spv::OpBitwiseXor;
3157 break;
3158 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003159 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003160 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003161 break;
3162
3163 case glslang::EOpLessThan:
3164 case glslang::EOpGreaterThan:
3165 case glslang::EOpLessThanEqual:
3166 case glslang::EOpGreaterThanEqual:
3167 case glslang::EOpEqual:
3168 case glslang::EOpNotEqual:
3169 case glslang::EOpVectorEqual:
3170 case glslang::EOpVectorNotEqual:
3171 comparison = true;
3172 break;
3173 default:
3174 break;
3175 }
3176
John Kessenich7c1aa102015-10-15 13:29:11 -06003177 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003178 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003179 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003180 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003181 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003182
3183 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003184 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003185 builder.promoteScalar(precision, left, right);
3186
qining25262b32016-05-06 17:25:16 -04003187 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3188 addDecoration(result, noContraction);
3189 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003190 }
3191
3192 if (! comparison)
3193 return 0;
3194
John Kessenich7c1aa102015-10-15 13:29:11 -06003195 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003196
John Kessenich4583b612016-08-07 19:14:22 -06003197 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3198 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003199 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003200
3201 switch (op) {
3202 case glslang::EOpLessThan:
3203 if (isFloat)
3204 binOp = spv::OpFOrdLessThan;
3205 else if (isUnsigned)
3206 binOp = spv::OpULessThan;
3207 else
3208 binOp = spv::OpSLessThan;
3209 break;
3210 case glslang::EOpGreaterThan:
3211 if (isFloat)
3212 binOp = spv::OpFOrdGreaterThan;
3213 else if (isUnsigned)
3214 binOp = spv::OpUGreaterThan;
3215 else
3216 binOp = spv::OpSGreaterThan;
3217 break;
3218 case glslang::EOpLessThanEqual:
3219 if (isFloat)
3220 binOp = spv::OpFOrdLessThanEqual;
3221 else if (isUnsigned)
3222 binOp = spv::OpULessThanEqual;
3223 else
3224 binOp = spv::OpSLessThanEqual;
3225 break;
3226 case glslang::EOpGreaterThanEqual:
3227 if (isFloat)
3228 binOp = spv::OpFOrdGreaterThanEqual;
3229 else if (isUnsigned)
3230 binOp = spv::OpUGreaterThanEqual;
3231 else
3232 binOp = spv::OpSGreaterThanEqual;
3233 break;
3234 case glslang::EOpEqual:
3235 case glslang::EOpVectorEqual:
3236 if (isFloat)
3237 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003238 else if (isBool)
3239 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003240 else
3241 binOp = spv::OpIEqual;
3242 break;
3243 case glslang::EOpNotEqual:
3244 case glslang::EOpVectorNotEqual:
3245 if (isFloat)
3246 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003247 else if (isBool)
3248 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003249 else
3250 binOp = spv::OpINotEqual;
3251 break;
3252 default:
3253 break;
3254 }
3255
qining25262b32016-05-06 17:25:16 -04003256 if (binOp != spv::OpNop) {
3257 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3258 addDecoration(result, noContraction);
3259 return builder.setPrecision(result, precision);
3260 }
John Kessenich140f3df2015-06-26 16:58:36 -06003261
3262 return 0;
3263}
3264
John Kessenich04bb8a02015-12-12 12:28:14 -07003265//
3266// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3267// These can be any of:
3268//
3269// matrix * scalar
3270// scalar * matrix
3271// matrix * matrix linear algebraic
3272// matrix * vector
3273// vector * matrix
3274// matrix * matrix componentwise
3275// matrix op matrix op in {+, -, /}
3276// matrix op scalar op in {+, -, /}
3277// scalar op matrix op in {+, -, /}
3278//
qining25262b32016-05-06 17:25:16 -04003279spv::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 -07003280{
3281 bool firstClass = true;
3282
3283 // First, handle first-class matrix operations (* and matrix/scalar)
3284 switch (op) {
3285 case spv::OpFDiv:
3286 if (builder.isMatrix(left) && builder.isScalar(right)) {
3287 // turn matrix / scalar into a multiply...
3288 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3289 op = spv::OpMatrixTimesScalar;
3290 } else
3291 firstClass = false;
3292 break;
3293 case spv::OpMatrixTimesScalar:
3294 if (builder.isMatrix(right))
3295 std::swap(left, right);
3296 assert(builder.isScalar(right));
3297 break;
3298 case spv::OpVectorTimesMatrix:
3299 assert(builder.isVector(left));
3300 assert(builder.isMatrix(right));
3301 break;
3302 case spv::OpMatrixTimesVector:
3303 assert(builder.isMatrix(left));
3304 assert(builder.isVector(right));
3305 break;
3306 case spv::OpMatrixTimesMatrix:
3307 assert(builder.isMatrix(left));
3308 assert(builder.isMatrix(right));
3309 break;
3310 default:
3311 firstClass = false;
3312 break;
3313 }
3314
qining25262b32016-05-06 17:25:16 -04003315 if (firstClass) {
3316 spv::Id result = builder.createBinOp(op, typeId, left, right);
3317 addDecoration(result, noContraction);
3318 return builder.setPrecision(result, precision);
3319 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003320
LoopDawg592860c2016-06-09 08:57:35 -06003321 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003322 // The result type of all of them is the same type as the (a) matrix operand.
3323 // The algorithm is to:
3324 // - break the matrix(es) into vectors
3325 // - smear any scalar to a vector
3326 // - do vector operations
3327 // - make a matrix out the vector results
3328 switch (op) {
3329 case spv::OpFAdd:
3330 case spv::OpFSub:
3331 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003332 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003333 case spv::OpFMul:
3334 {
3335 // one time set up...
3336 bool leftMat = builder.isMatrix(left);
3337 bool rightMat = builder.isMatrix(right);
3338 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3339 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3340 spv::Id scalarType = builder.getScalarTypeId(typeId);
3341 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3342 std::vector<spv::Id> results;
3343 spv::Id smearVec = spv::NoResult;
3344 if (builder.isScalar(left))
3345 smearVec = builder.smearScalar(precision, left, vecType);
3346 else if (builder.isScalar(right))
3347 smearVec = builder.smearScalar(precision, right, vecType);
3348
3349 // do each vector op
3350 for (unsigned int c = 0; c < numCols; ++c) {
3351 std::vector<unsigned int> indexes;
3352 indexes.push_back(c);
3353 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3354 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003355 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3356 addDecoration(result, noContraction);
3357 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003358 }
3359
3360 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003361 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003362 }
3363 default:
3364 assert(0);
3365 return spv::NoResult;
3366 }
3367}
3368
qining25262b32016-05-06 17:25:16 -04003369spv::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 -06003370{
3371 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003372 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003373 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003374 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003375 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06003376
3377 switch (op) {
3378 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003379 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003380 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003381 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003382 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003383 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003384 unaryOp = spv::OpSNegate;
3385 break;
3386
3387 case glslang::EOpLogicalNot:
3388 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003389 unaryOp = spv::OpLogicalNot;
3390 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003391 case glslang::EOpBitwiseNot:
3392 unaryOp = spv::OpNot;
3393 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003394
John Kessenich140f3df2015-06-26 16:58:36 -06003395 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003396 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003399 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003400 break;
3401 case glslang::EOpTranspose:
3402 unaryOp = spv::OpTranspose;
3403 break;
3404
3405 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003410 break;
3411 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003412 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003415 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003416 break;
3417 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003418 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003419 break;
3420 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003421 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003422 break;
3423 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003424 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003425 break;
3426 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003428 break;
3429
3430 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003431 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003432 break;
3433 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003434 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003435 break;
3436 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003437 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003438 break;
3439 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003440 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003441 break;
3442 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003443 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003444 break;
3445 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003446 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003447 break;
3448
3449 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003450 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003453 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003454 break;
3455
3456 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003457 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003458 break;
3459 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003460 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003461 break;
3462 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003463 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003464 break;
3465 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003466 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003469 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003470 break;
3471 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003472 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003473 break;
3474
3475 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003476 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003477 break;
3478 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003482 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003483 break;
3484 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003485 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003488 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003489 break;
3490 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003491 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493
3494 case glslang::EOpIsNan:
3495 unaryOp = spv::OpIsNan;
3496 break;
3497 case glslang::EOpIsInf:
3498 unaryOp = spv::OpIsInf;
3499 break;
LoopDawg592860c2016-06-09 08:57:35 -06003500 case glslang::EOpIsFinite:
3501 unaryOp = spv::OpIsFinite;
3502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003503
Rex Xucbc426e2015-12-15 16:03:10 +08003504 case glslang::EOpFloatBitsToInt:
3505 case glslang::EOpFloatBitsToUint:
3506 case glslang::EOpIntBitsToFloat:
3507 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003508 case glslang::EOpDoubleBitsToInt64:
3509 case glslang::EOpDoubleBitsToUint64:
3510 case glslang::EOpInt64BitsToDouble:
3511 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003512 unaryOp = spv::OpBitcast;
3513 break;
3514
John Kessenich140f3df2015-06-26 16:58:36 -06003515 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003517 break;
3518 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003519 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003520 break;
3521 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003522 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 break;
3524 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003526 break;
3527 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003528 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003529 break;
3530 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003531 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003532 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003533 case glslang::EOpPackSnorm4x8:
3534 libCall = spv::GLSLstd450PackSnorm4x8;
3535 break;
3536 case glslang::EOpUnpackSnorm4x8:
3537 libCall = spv::GLSLstd450UnpackSnorm4x8;
3538 break;
3539 case glslang::EOpPackUnorm4x8:
3540 libCall = spv::GLSLstd450PackUnorm4x8;
3541 break;
3542 case glslang::EOpUnpackUnorm4x8:
3543 libCall = spv::GLSLstd450UnpackUnorm4x8;
3544 break;
3545 case glslang::EOpPackDouble2x32:
3546 libCall = spv::GLSLstd450PackDouble2x32;
3547 break;
3548 case glslang::EOpUnpackDouble2x32:
3549 libCall = spv::GLSLstd450UnpackDouble2x32;
3550 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003551
Rex Xu8ff43de2016-04-22 16:51:45 +08003552 case glslang::EOpPackInt2x32:
3553 case glslang::EOpUnpackInt2x32:
3554 case glslang::EOpPackUint2x32:
3555 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003556 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003557 break;
3558
John Kessenich140f3df2015-06-26 16:58:36 -06003559 case glslang::EOpDPdx:
3560 unaryOp = spv::OpDPdx;
3561 break;
3562 case glslang::EOpDPdy:
3563 unaryOp = spv::OpDPdy;
3564 break;
3565 case glslang::EOpFwidth:
3566 unaryOp = spv::OpFwidth;
3567 break;
3568 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003569 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003570 unaryOp = spv::OpDPdxFine;
3571 break;
3572 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003573 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003574 unaryOp = spv::OpDPdyFine;
3575 break;
3576 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003577 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003578 unaryOp = spv::OpFwidthFine;
3579 break;
3580 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003581 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003582 unaryOp = spv::OpDPdxCoarse;
3583 break;
3584 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003585 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003586 unaryOp = spv::OpDPdyCoarse;
3587 break;
3588 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003589 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003590 unaryOp = spv::OpFwidthCoarse;
3591 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003592 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003593 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003594 libCall = spv::GLSLstd450InterpolateAtCentroid;
3595 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003596 case glslang::EOpAny:
3597 unaryOp = spv::OpAny;
3598 break;
3599 case glslang::EOpAll:
3600 unaryOp = spv::OpAll;
3601 break;
3602
3603 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003604 if (isFloat)
3605 libCall = spv::GLSLstd450FAbs;
3606 else
3607 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003608 break;
3609 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003610 if (isFloat)
3611 libCall = spv::GLSLstd450FSign;
3612 else
3613 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 break;
3615
John Kessenichfc51d282015-08-19 13:34:18 -06003616 case glslang::EOpAtomicCounterIncrement:
3617 case glslang::EOpAtomicCounterDecrement:
3618 case glslang::EOpAtomicCounter:
3619 {
3620 // Handle all of the atomics in one place, in createAtomicOperation()
3621 std::vector<spv::Id> operands;
3622 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003623 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003624 }
3625
John Kessenichfc51d282015-08-19 13:34:18 -06003626 case glslang::EOpBitFieldReverse:
3627 unaryOp = spv::OpBitReverse;
3628 break;
3629 case glslang::EOpBitCount:
3630 unaryOp = spv::OpBitCount;
3631 break;
3632 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003633 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003634 break;
3635 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003636 if (isUnsigned)
3637 libCall = spv::GLSLstd450FindUMsb;
3638 else
3639 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003640 break;
3641
Rex Xu574ab042016-04-14 16:53:07 +08003642 case glslang::EOpBallot:
3643 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003644 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003645 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003646 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003647#ifdef AMD_EXTENSIONS
3648 case glslang::EOpMinInvocations:
3649 case glslang::EOpMaxInvocations:
3650 case glslang::EOpAddInvocations:
3651 case glslang::EOpMinInvocationsNonUniform:
3652 case glslang::EOpMaxInvocationsNonUniform:
3653 case glslang::EOpAddInvocationsNonUniform:
3654#endif
Rex Xu51596642016-09-21 18:56:12 +08003655 {
3656 std::vector<spv::Id> operands;
3657 operands.push_back(operand);
3658 return createInvocationsOperation(op, typeId, operands, typeProxy);
3659 }
Rex Xu9d93a232016-05-05 12:30:44 +08003660
3661#ifdef AMD_EXTENSIONS
3662 case glslang::EOpMbcnt:
3663 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3664 libCall = spv::MbcntAMD;
3665 break;
3666
3667 case glslang::EOpCubeFaceIndex:
3668 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3669 libCall = spv::CubeFaceIndexAMD;
3670 break;
3671
3672 case glslang::EOpCubeFaceCoord:
3673 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3674 libCall = spv::CubeFaceCoordAMD;
3675 break;
3676#endif
Rex Xu338b1852016-05-05 20:38:33 +08003677
John Kessenich140f3df2015-06-26 16:58:36 -06003678 default:
3679 return 0;
3680 }
3681
3682 spv::Id id;
3683 if (libCall >= 0) {
3684 std::vector<spv::Id> args;
3685 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003686 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003687 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003688 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003689 }
John Kessenich140f3df2015-06-26 16:58:36 -06003690
qining25262b32016-05-06 17:25:16 -04003691 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003692 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003693}
3694
John Kessenich7a53f762016-01-20 11:19:27 -07003695// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003696spv::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 -07003697{
3698 // Handle unary operations vector by vector.
3699 // The result type is the same type as the original type.
3700 // The algorithm is to:
3701 // - break the matrix into vectors
3702 // - apply the operation to each vector
3703 // - make a matrix out the vector results
3704
3705 // get the types sorted out
3706 int numCols = builder.getNumColumns(operand);
3707 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003708 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3709 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003710 std::vector<spv::Id> results;
3711
3712 // do each vector op
3713 for (int c = 0; c < numCols; ++c) {
3714 std::vector<unsigned int> indexes;
3715 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003716 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3717 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3718 addDecoration(destVec, noContraction);
3719 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003720 }
3721
3722 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003723 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003724}
3725
Rex Xu73e3ce72016-04-27 18:48:17 +08003726spv::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 -06003727{
3728 spv::Op convOp = spv::OpNop;
3729 spv::Id zero = 0;
3730 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003731 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003732
3733 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3734
3735 switch (op) {
3736 case glslang::EOpConvIntToBool:
3737 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003738 case glslang::EOpConvInt64ToBool:
3739 case glslang::EOpConvUint64ToBool:
3740 zero = (op == glslang::EOpConvInt64ToBool ||
3741 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003742 zero = makeSmearedConstant(zero, vectorSize);
3743 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3744
3745 case glslang::EOpConvFloatToBool:
3746 zero = builder.makeFloatConstant(0.0F);
3747 zero = makeSmearedConstant(zero, vectorSize);
3748 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3749
3750 case glslang::EOpConvDoubleToBool:
3751 zero = builder.makeDoubleConstant(0.0);
3752 zero = makeSmearedConstant(zero, vectorSize);
3753 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3754
3755 case glslang::EOpConvBoolToFloat:
3756 convOp = spv::OpSelect;
3757 zero = builder.makeFloatConstant(0.0);
3758 one = builder.makeFloatConstant(1.0);
3759 break;
3760 case glslang::EOpConvBoolToDouble:
3761 convOp = spv::OpSelect;
3762 zero = builder.makeDoubleConstant(0.0);
3763 one = builder.makeDoubleConstant(1.0);
3764 break;
3765 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003766 case glslang::EOpConvBoolToInt64:
3767 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3768 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003769 convOp = spv::OpSelect;
3770 break;
3771 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003772 case glslang::EOpConvBoolToUint64:
3773 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3774 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003775 convOp = spv::OpSelect;
3776 break;
3777
3778 case glslang::EOpConvIntToFloat:
3779 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003780 case glslang::EOpConvInt64ToFloat:
3781 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003782 convOp = spv::OpConvertSToF;
3783 break;
3784
3785 case glslang::EOpConvUintToFloat:
3786 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003787 case glslang::EOpConvUint64ToFloat:
3788 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003789 convOp = spv::OpConvertUToF;
3790 break;
3791
3792 case glslang::EOpConvDoubleToFloat:
3793 case glslang::EOpConvFloatToDouble:
3794 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003795 if (builder.isMatrixType(destType))
3796 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003797 break;
3798
3799 case glslang::EOpConvFloatToInt:
3800 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003801 case glslang::EOpConvFloatToInt64:
3802 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003803 convOp = spv::OpConvertFToS;
3804 break;
3805
3806 case glslang::EOpConvUintToInt:
3807 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003808 case glslang::EOpConvUint64ToInt64:
3809 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003810 if (builder.isInSpecConstCodeGenMode()) {
3811 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003812 zero = (op == glslang::EOpConvUint64ToInt64 ||
3813 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003814 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003815 // Use OpIAdd, instead of OpBitcast to do the conversion when
3816 // generating for OpSpecConstantOp instruction.
3817 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3818 }
3819 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003820 convOp = spv::OpBitcast;
3821 break;
3822
3823 case glslang::EOpConvFloatToUint:
3824 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003825 case glslang::EOpConvFloatToUint64:
3826 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003827 convOp = spv::OpConvertFToU;
3828 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003829
3830 case glslang::EOpConvIntToInt64:
3831 case glslang::EOpConvInt64ToInt:
3832 convOp = spv::OpSConvert;
3833 break;
3834
3835 case glslang::EOpConvUintToUint64:
3836 case glslang::EOpConvUint64ToUint:
3837 convOp = spv::OpUConvert;
3838 break;
3839
3840 case glslang::EOpConvIntToUint64:
3841 case glslang::EOpConvInt64ToUint:
3842 case glslang::EOpConvUint64ToInt:
3843 case glslang::EOpConvUintToInt64:
3844 // OpSConvert/OpUConvert + OpBitCast
3845 switch (op) {
3846 case glslang::EOpConvIntToUint64:
3847 convOp = spv::OpSConvert;
3848 type = builder.makeIntType(64);
3849 break;
3850 case glslang::EOpConvInt64ToUint:
3851 convOp = spv::OpSConvert;
3852 type = builder.makeIntType(32);
3853 break;
3854 case glslang::EOpConvUint64ToInt:
3855 convOp = spv::OpUConvert;
3856 type = builder.makeUintType(32);
3857 break;
3858 case glslang::EOpConvUintToInt64:
3859 convOp = spv::OpUConvert;
3860 type = builder.makeUintType(64);
3861 break;
3862 default:
3863 assert(0);
3864 break;
3865 }
3866
3867 if (vectorSize > 0)
3868 type = builder.makeVectorType(type, vectorSize);
3869
3870 operand = builder.createUnaryOp(convOp, type, operand);
3871
3872 if (builder.isInSpecConstCodeGenMode()) {
3873 // Build zero scalar or vector for OpIAdd.
3874 zero = (op == glslang::EOpConvIntToUint64 ||
3875 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3876 zero = makeSmearedConstant(zero, vectorSize);
3877 // Use OpIAdd, instead of OpBitcast to do the conversion when
3878 // generating for OpSpecConstantOp instruction.
3879 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3880 }
3881 // For normal run-time conversion instruction, use OpBitcast.
3882 convOp = spv::OpBitcast;
3883 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003884 default:
3885 break;
3886 }
3887
3888 spv::Id result = 0;
3889 if (convOp == spv::OpNop)
3890 return result;
3891
3892 if (convOp == spv::OpSelect) {
3893 zero = makeSmearedConstant(zero, vectorSize);
3894 one = makeSmearedConstant(one, vectorSize);
3895 result = builder.createTriOp(convOp, destType, operand, one, zero);
3896 } else
3897 result = builder.createUnaryOp(convOp, destType, operand);
3898
John Kessenich32cfd492016-02-02 12:37:46 -07003899 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003900}
3901
3902spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3903{
3904 if (vectorSize == 0)
3905 return constant;
3906
3907 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3908 std::vector<spv::Id> components;
3909 for (int c = 0; c < vectorSize; ++c)
3910 components.push_back(constant);
3911 return builder.makeCompositeConstant(vectorTypeId, components);
3912}
3913
John Kessenich426394d2015-07-23 10:22:48 -06003914// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003915spv::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 -06003916{
3917 spv::Op opCode = spv::OpNop;
3918
3919 switch (op) {
3920 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003921 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003922 opCode = spv::OpAtomicIAdd;
3923 break;
3924 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003925 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003926 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003927 break;
3928 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003929 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003930 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003931 break;
3932 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003933 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003934 opCode = spv::OpAtomicAnd;
3935 break;
3936 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003937 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003938 opCode = spv::OpAtomicOr;
3939 break;
3940 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003941 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003942 opCode = spv::OpAtomicXor;
3943 break;
3944 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003945 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003946 opCode = spv::OpAtomicExchange;
3947 break;
3948 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003949 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003950 opCode = spv::OpAtomicCompareExchange;
3951 break;
3952 case glslang::EOpAtomicCounterIncrement:
3953 opCode = spv::OpAtomicIIncrement;
3954 break;
3955 case glslang::EOpAtomicCounterDecrement:
3956 opCode = spv::OpAtomicIDecrement;
3957 break;
3958 case glslang::EOpAtomicCounter:
3959 opCode = spv::OpAtomicLoad;
3960 break;
3961 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003962 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003963 break;
3964 }
3965
3966 // Sort out the operands
3967 // - mapping from glslang -> SPV
3968 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003969 // - compare-exchange swaps the value and comparator
3970 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003971 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3972 auto opIt = operands.begin(); // walk the glslang operands
3973 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003974 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3975 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3976 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003977 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3978 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003979 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003980 spvAtomicOperands.push_back(*(opIt + 1));
3981 spvAtomicOperands.push_back(*opIt);
3982 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003983 }
John Kessenich426394d2015-07-23 10:22:48 -06003984
John Kessenich3e60a6f2015-09-14 22:45:16 -06003985 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003986 for (; opIt != operands.end(); ++opIt)
3987 spvAtomicOperands.push_back(*opIt);
3988
3989 return builder.createOp(opCode, typeId, spvAtomicOperands);
3990}
3991
John Kessenich91cef522016-05-05 16:45:40 -06003992// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08003993spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06003994{
Rex Xu9d93a232016-05-05 12:30:44 +08003995 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
3996 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3997
Rex Xu51596642016-09-21 18:56:12 +08003998 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06003999
Rex Xu51596642016-09-21 18:56:12 +08004000 std::vector<spv::Id> spvGroupOperands;
4001 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4002 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4003 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4004 } else {
4005 builder.addCapability(spv::CapabilityGroups);
4006
4007 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004008#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004009 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4010 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4011 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004012#endif
Rex Xu51596642016-09-21 18:56:12 +08004013 }
4014
4015 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4016 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004017
4018 switch (op) {
4019 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004020 opCode = spv::OpGroupAny;
4021 break;
John Kessenich91cef522016-05-05 16:45:40 -06004022 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004023 opCode = spv::OpGroupAll;
4024 break;
John Kessenich91cef522016-05-05 16:45:40 -06004025 case glslang::EOpAllInvocationsEqual:
4026 {
Rex Xu51596642016-09-21 18:56:12 +08004027 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4028 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004029
4030 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4031 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4032 }
Rex Xu51596642016-09-21 18:56:12 +08004033
4034 case glslang::EOpReadInvocation:
4035 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004036 if (builder.isVectorType(typeId))
4037 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004038 break;
4039 case glslang::EOpReadFirstInvocation:
4040 opCode = spv::OpSubgroupFirstInvocationKHR;
4041 break;
4042 case glslang::EOpBallot:
4043 {
4044 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4045 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4046 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4047 //
4048 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4049 //
4050 spv::Id uintType = builder.makeUintType(32);
4051 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4052 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4053
4054 std::vector<spv::Id> components;
4055 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4056 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4057
4058 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4059 return builder.createUnaryOp(spv::OpBitcast, typeId,
4060 builder.createCompositeConstruct(uvec2Type, components));
4061 }
4062
Rex Xu9d93a232016-05-05 12:30:44 +08004063#ifdef AMD_EXTENSIONS
4064 case glslang::EOpMinInvocations:
4065 case glslang::EOpMaxInvocations:
4066 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004067 if (op == glslang::EOpMinInvocations) {
4068 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004069 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004070 else {
4071 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004072 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004073 else
Rex Xu51596642016-09-21 18:56:12 +08004074 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004075 }
4076 } else if (op == glslang::EOpMaxInvocations) {
4077 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004078 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004079 else {
4080 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004081 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004082 else
Rex Xu51596642016-09-21 18:56:12 +08004083 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004084 }
4085 } else {
4086 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004087 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004088 else
Rex Xu51596642016-09-21 18:56:12 +08004089 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004090 }
4091
Rex Xu2bbbe062016-08-23 15:41:05 +08004092 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004093 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004094
4095 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004096 case glslang::EOpMinInvocationsNonUniform:
4097 case glslang::EOpMaxInvocationsNonUniform:
4098 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004099 if (op == glslang::EOpMinInvocationsNonUniform) {
4100 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004101 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004102 else {
4103 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004104 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004105 else
Rex Xu51596642016-09-21 18:56:12 +08004106 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004107 }
4108 }
4109 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4110 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004111 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004112 else {
4113 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004114 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004115 else
Rex Xu51596642016-09-21 18:56:12 +08004116 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004117 }
4118 }
4119 else {
4120 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004121 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004122 else
Rex Xu51596642016-09-21 18:56:12 +08004123 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004124 }
4125
Rex Xu2bbbe062016-08-23 15:41:05 +08004126 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004127 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004128
4129 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004130#endif
John Kessenich91cef522016-05-05 16:45:40 -06004131 default:
4132 logger->missingFunctionality("invocation operation");
4133 return spv::NoResult;
4134 }
Rex Xu51596642016-09-21 18:56:12 +08004135
4136 assert(opCode != spv::OpNop);
4137 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004138}
4139
Rex Xu2bbbe062016-08-23 15:41:05 +08004140// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004141spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004142{
Rex Xub7072052016-09-26 15:53:40 +08004143#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004144 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4145 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004146 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004147 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4148 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4149 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004150#else
4151 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4152 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4153 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4154#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004155
4156 // Handle group invocation operations scalar by scalar.
4157 // The result type is the same type as the original type.
4158 // The algorithm is to:
4159 // - break the vector into scalars
4160 // - apply the operation to each scalar
4161 // - make a vector out the scalar results
4162
4163 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004164 int numComponents = builder.getNumComponents(operands[0]);
4165 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004166 std::vector<spv::Id> results;
4167
4168 // do each scalar op
4169 for (int comp = 0; comp < numComponents; ++comp) {
4170 std::vector<unsigned int> indexes;
4171 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004172 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004173
Rex Xub7072052016-09-26 15:53:40 +08004174 std::vector<spv::Id> spvGroupOperands;
4175 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4176 if (op == spv::OpGroupBroadcast) {
4177 spvGroupOperands.push_back(scalar);
4178 spvGroupOperands.push_back(operands[1]);
4179 } else {
4180 spvGroupOperands.push_back(spv::GroupOperationReduce);
4181 spvGroupOperands.push_back(scalar);
4182 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004183
Rex Xub7072052016-09-26 15:53:40 +08004184 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004185 }
4186
4187 // put the pieces together
4188 return builder.createCompositeConstruct(typeId, results);
4189}
Rex Xu2bbbe062016-08-23 15:41:05 +08004190
John Kessenich5e4b1242015-08-06 22:53:06 -06004191spv::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 -06004192{
Rex Xu8ff43de2016-04-22 16:51:45 +08004193 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06004194 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
4195
John Kessenich140f3df2015-06-26 16:58:36 -06004196 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004197 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004198 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004199 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004200 spv::Id typeId0 = 0;
4201 if (consumedOperands > 0)
4202 typeId0 = builder.getTypeId(operands[0]);
4203 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004204
4205 switch (op) {
4206 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004207 if (isFloat)
4208 libCall = spv::GLSLstd450FMin;
4209 else if (isUnsigned)
4210 libCall = spv::GLSLstd450UMin;
4211 else
4212 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004213 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004214 break;
4215 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004216 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004217 break;
4218 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004219 if (isFloat)
4220 libCall = spv::GLSLstd450FMax;
4221 else if (isUnsigned)
4222 libCall = spv::GLSLstd450UMax;
4223 else
4224 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004225 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004226 break;
4227 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004228 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004229 break;
4230 case glslang::EOpDot:
4231 opCode = spv::OpDot;
4232 break;
4233 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004234 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004235 break;
4236
4237 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004238 if (isFloat)
4239 libCall = spv::GLSLstd450FClamp;
4240 else if (isUnsigned)
4241 libCall = spv::GLSLstd450UClamp;
4242 else
4243 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004244 builder.promoteScalar(precision, operands.front(), operands[1]);
4245 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004246 break;
4247 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004248 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4249 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004250 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004251 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004252 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004253 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004254 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004255 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004256 break;
4257 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004258 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004259 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004260 break;
4261 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004262 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004263 builder.promoteScalar(precision, operands[0], operands[2]);
4264 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004265 break;
4266
4267 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004268 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004269 break;
4270 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004271 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004272 break;
4273 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004274 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004275 break;
4276 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004277 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004278 break;
4279 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004280 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004281 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004282 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004283 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004284 libCall = spv::GLSLstd450InterpolateAtSample;
4285 break;
4286 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004287 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004288 libCall = spv::GLSLstd450InterpolateAtOffset;
4289 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004290 case glslang::EOpAddCarry:
4291 opCode = spv::OpIAddCarry;
4292 typeId = builder.makeStructResultType(typeId0, typeId0);
4293 consumedOperands = 2;
4294 break;
4295 case glslang::EOpSubBorrow:
4296 opCode = spv::OpISubBorrow;
4297 typeId = builder.makeStructResultType(typeId0, typeId0);
4298 consumedOperands = 2;
4299 break;
4300 case glslang::EOpUMulExtended:
4301 opCode = spv::OpUMulExtended;
4302 typeId = builder.makeStructResultType(typeId0, typeId0);
4303 consumedOperands = 2;
4304 break;
4305 case glslang::EOpIMulExtended:
4306 opCode = spv::OpSMulExtended;
4307 typeId = builder.makeStructResultType(typeId0, typeId0);
4308 consumedOperands = 2;
4309 break;
4310 case glslang::EOpBitfieldExtract:
4311 if (isUnsigned)
4312 opCode = spv::OpBitFieldUExtract;
4313 else
4314 opCode = spv::OpBitFieldSExtract;
4315 break;
4316 case glslang::EOpBitfieldInsert:
4317 opCode = spv::OpBitFieldInsert;
4318 break;
4319
4320 case glslang::EOpFma:
4321 libCall = spv::GLSLstd450Fma;
4322 break;
4323 case glslang::EOpFrexp:
4324 libCall = spv::GLSLstd450FrexpStruct;
4325 if (builder.getNumComponents(operands[0]) == 1)
4326 frexpIntType = builder.makeIntegerType(32, true);
4327 else
4328 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4329 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4330 consumedOperands = 1;
4331 break;
4332 case glslang::EOpLdexp:
4333 libCall = spv::GLSLstd450Ldexp;
4334 break;
4335
Rex Xu574ab042016-04-14 16:53:07 +08004336 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004337 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004338
Rex Xu9d93a232016-05-05 12:30:44 +08004339#ifdef AMD_EXTENSIONS
4340 case glslang::EOpSwizzleInvocations:
4341 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4342 libCall = spv::SwizzleInvocationsAMD;
4343 break;
4344 case glslang::EOpSwizzleInvocationsMasked:
4345 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4346 libCall = spv::SwizzleInvocationsMaskedAMD;
4347 break;
4348 case glslang::EOpWriteInvocation:
4349 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4350 libCall = spv::WriteInvocationAMD;
4351 break;
4352
4353 case glslang::EOpMin3:
4354 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4355 if (isFloat)
4356 libCall = spv::FMin3AMD;
4357 else {
4358 if (isUnsigned)
4359 libCall = spv::UMin3AMD;
4360 else
4361 libCall = spv::SMin3AMD;
4362 }
4363 break;
4364 case glslang::EOpMax3:
4365 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4366 if (isFloat)
4367 libCall = spv::FMax3AMD;
4368 else {
4369 if (isUnsigned)
4370 libCall = spv::UMax3AMD;
4371 else
4372 libCall = spv::SMax3AMD;
4373 }
4374 break;
4375 case glslang::EOpMid3:
4376 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4377 if (isFloat)
4378 libCall = spv::FMid3AMD;
4379 else {
4380 if (isUnsigned)
4381 libCall = spv::UMid3AMD;
4382 else
4383 libCall = spv::SMid3AMD;
4384 }
4385 break;
4386
4387 case glslang::EOpInterpolateAtVertex:
4388 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4389 libCall = spv::InterpolateAtVertexAMD;
4390 break;
4391#endif
4392
John Kessenich140f3df2015-06-26 16:58:36 -06004393 default:
4394 return 0;
4395 }
4396
4397 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004398 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004399 // Use an extended instruction from the standard library.
4400 // Construct the call arguments, without modifying the original operands vector.
4401 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4402 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004403 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004404 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004405 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004406 case 0:
4407 // should all be handled by visitAggregate and createNoArgOperation
4408 assert(0);
4409 return 0;
4410 case 1:
4411 // should all be handled by createUnaryOperation
4412 assert(0);
4413 return 0;
4414 case 2:
4415 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4416 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004417 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004418 // anything 3 or over doesn't have l-value operands, so all should be consumed
4419 assert(consumedOperands == operands.size());
4420 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004421 break;
4422 }
4423 }
4424
John Kessenich55e7d112015-11-15 21:33:39 -07004425 // Decode the return types that were structures
4426 switch (op) {
4427 case glslang::EOpAddCarry:
4428 case glslang::EOpSubBorrow:
4429 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4430 id = builder.createCompositeExtract(id, typeId0, 0);
4431 break;
4432 case glslang::EOpUMulExtended:
4433 case glslang::EOpIMulExtended:
4434 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4435 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4436 break;
4437 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004438 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004439 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4440 id = builder.createCompositeExtract(id, typeId0, 0);
4441 break;
4442 default:
4443 break;
4444 }
4445
John Kessenich32cfd492016-02-02 12:37:46 -07004446 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004447}
4448
Rex Xu9d93a232016-05-05 12:30:44 +08004449// Intrinsics with no arguments (or no return value, and no precision).
4450spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004451{
4452 // TODO: get the barrier operands correct
4453
4454 switch (op) {
4455 case glslang::EOpEmitVertex:
4456 builder.createNoResultOp(spv::OpEmitVertex);
4457 return 0;
4458 case glslang::EOpEndPrimitive:
4459 builder.createNoResultOp(spv::OpEndPrimitive);
4460 return 0;
4461 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004462 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004463 return 0;
4464 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004465 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004466 return 0;
4467 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004468 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004469 return 0;
4470 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004471 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004472 return 0;
4473 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004474 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004475 return 0;
4476 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004477 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004478 return 0;
4479 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004480 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004481 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004482 case glslang::EOpAllMemoryBarrierWithGroupSync:
4483 // Control barrier with non-"None" semantic is also a memory barrier.
4484 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4485 return 0;
4486 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4487 // Control barrier with non-"None" semantic is also a memory barrier.
4488 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4489 return 0;
4490 case glslang::EOpWorkgroupMemoryBarrier:
4491 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4492 return 0;
4493 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4494 // Control barrier with non-"None" semantic is also a memory barrier.
4495 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4496 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004497#ifdef AMD_EXTENSIONS
4498 case glslang::EOpTime:
4499 {
4500 std::vector<spv::Id> args; // Dummy arguments
4501 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4502 return builder.setPrecision(id, precision);
4503 }
4504#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004505 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004506 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004507 return 0;
4508 }
4509}
4510
4511spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4512{
John Kessenich2f273362015-07-18 22:34:27 -06004513 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004514 spv::Id id;
4515 if (symbolValues.end() != iter) {
4516 id = iter->second;
4517 return id;
4518 }
4519
4520 // it was not found, create it
4521 id = createSpvVariable(symbol);
4522 symbolValues[symbol->getId()] = id;
4523
Rex Xuc884b4a2016-06-29 15:03:44 +08004524 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004525 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004526 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004527 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004528 if (symbol->getType().getQualifier().hasSpecConstantId())
4529 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004530 if (symbol->getQualifier().hasIndex())
4531 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4532 if (symbol->getQualifier().hasComponent())
4533 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4534 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004535 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004536 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004537 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004538 if (symbol->getQualifier().hasXfbBuffer())
4539 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4540 if (symbol->getQualifier().hasXfbOffset())
4541 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4542 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004543 // atomic counters use this:
4544 if (symbol->getQualifier().hasOffset())
4545 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004546 }
4547
scygan2c864272016-05-18 18:09:17 +02004548 if (symbol->getQualifier().hasLocation())
4549 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004550 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004551 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004552 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004553 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004554 }
John Kessenich140f3df2015-06-26 16:58:36 -06004555 if (symbol->getQualifier().hasSet())
4556 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004557 else if (IsDescriptorResource(symbol->getType())) {
4558 // default to 0
4559 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4560 }
John Kessenich140f3df2015-06-26 16:58:36 -06004561 if (symbol->getQualifier().hasBinding())
4562 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004563 if (symbol->getQualifier().hasAttachment())
4564 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004565 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004566 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004567 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004568 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004569 if (symbol->getQualifier().hasXfbBuffer())
4570 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4571 }
4572
Rex Xu1da878f2016-02-21 20:59:01 +08004573 if (symbol->getType().isImage()) {
4574 std::vector<spv::Decoration> memory;
4575 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4576 for (unsigned int i = 0; i < memory.size(); ++i)
4577 addDecoration(id, memory[i]);
4578 }
4579
John Kessenich140f3df2015-06-26 16:58:36 -06004580 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004581 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004582 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004583 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004584
John Kessenich140f3df2015-06-26 16:58:36 -06004585 return id;
4586}
4587
John Kessenich55e7d112015-11-15 21:33:39 -07004588// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004589void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4590{
John Kessenich4016e382016-07-15 11:53:56 -06004591 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004592 builder.addDecoration(id, dec);
4593}
4594
John Kessenich55e7d112015-11-15 21:33:39 -07004595// If 'dec' is valid, add a one-operand decoration to an object
4596void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4597{
John Kessenich4016e382016-07-15 11:53:56 -06004598 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004599 builder.addDecoration(id, dec, value);
4600}
4601
4602// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004603void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4604{
John Kessenich4016e382016-07-15 11:53:56 -06004605 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004606 builder.addMemberDecoration(id, (unsigned)member, dec);
4607}
4608
John Kessenich92187592016-02-01 13:45:25 -07004609// If 'dec' is valid, add a one-operand decoration to a struct member
4610void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4611{
John Kessenich4016e382016-07-15 11:53:56 -06004612 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004613 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4614}
4615
John Kessenich55e7d112015-11-15 21:33:39 -07004616// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004617// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004618//
4619// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4620//
4621// Recursively walk the nodes. The nodes form a tree whose leaves are
4622// regular constants, which themselves are trees that createSpvConstant()
4623// recursively walks. So, this function walks the "top" of the tree:
4624// - emit specialization constant-building instructions for specConstant
4625// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004626spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004627{
John Kessenich7cc0e282016-03-20 00:46:02 -06004628 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004629
qining4f4bb812016-04-03 23:55:17 -04004630 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004631 if (! node.getQualifier().specConstant) {
4632 // hand off to the non-spec-constant path
4633 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4634 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004635 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004636 nextConst, false);
4637 }
4638
4639 // We now know we have a specialization constant to build
4640
John Kessenichd94c0032016-05-30 19:29:40 -06004641 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004642 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4643 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4644 std::vector<spv::Id> dimConstId;
4645 for (int dim = 0; dim < 3; ++dim) {
4646 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4647 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4648 if (specConst)
4649 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4650 }
4651 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4652 }
4653
4654 // An AST node labelled as specialization constant should be a symbol node.
4655 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4656 if (auto* sn = node.getAsSymbolNode()) {
4657 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004658 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4659 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4660 // will set the builder into spec constant op instruction generating mode.
4661 sub_tree->traverse(this);
4662 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004663 } else if (auto* const_union_array = &sn->getConstArray()){
4664 int nextConst = 0;
4665 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004666 }
4667 }
qining4f4bb812016-04-03 23:55:17 -04004668
4669 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4670 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004671 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004672 exit(1);
4673 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004674}
4675
John Kessenich140f3df2015-06-26 16:58:36 -06004676// Use 'consts' as the flattened glslang source of scalar constants to recursively
4677// build the aggregate SPIR-V constant.
4678//
4679// If there are not enough elements present in 'consts', 0 will be substituted;
4680// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4681//
qining08408382016-03-21 09:51:37 -04004682spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004683{
4684 // vector of constants for SPIR-V
4685 std::vector<spv::Id> spvConsts;
4686
4687 // Type is used for struct and array constants
4688 spv::Id typeId = convertGlslangToSpvType(glslangType);
4689
4690 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004691 glslang::TType elementType(glslangType, 0);
4692 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004693 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004694 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004695 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004696 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004697 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004698 } else if (glslangType.getStruct()) {
4699 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4700 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004701 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004702 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004703 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4704 bool zero = nextConst >= consts.size();
4705 switch (glslangType.getBasicType()) {
4706 case glslang::EbtInt:
4707 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4708 break;
4709 case glslang::EbtUint:
4710 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4711 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004712 case glslang::EbtInt64:
4713 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4714 break;
4715 case glslang::EbtUint64:
4716 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4717 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004718 case glslang::EbtFloat:
4719 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4720 break;
4721 case glslang::EbtDouble:
4722 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4723 break;
4724 case glslang::EbtBool:
4725 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4726 break;
4727 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004728 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004729 break;
4730 }
4731 ++nextConst;
4732 }
4733 } else {
4734 // we have a non-aggregate (scalar) constant
4735 bool zero = nextConst >= consts.size();
4736 spv::Id scalar = 0;
4737 switch (glslangType.getBasicType()) {
4738 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004739 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004740 break;
4741 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004742 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004743 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004744 case glslang::EbtInt64:
4745 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4746 break;
4747 case glslang::EbtUint64:
4748 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4749 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004750 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004751 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004752 break;
4753 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004754 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004755 break;
4756 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004757 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004758 break;
4759 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004760 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004761 break;
4762 }
4763 ++nextConst;
4764 return scalar;
4765 }
4766
4767 return builder.makeCompositeConstant(typeId, spvConsts);
4768}
4769
John Kessenich7c1aa102015-10-15 13:29:11 -06004770// Return true if the node is a constant or symbol whose reading has no
4771// non-trivial observable cost or effect.
4772bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4773{
4774 // don't know what this is
4775 if (node == nullptr)
4776 return false;
4777
4778 // a constant is safe
4779 if (node->getAsConstantUnion() != nullptr)
4780 return true;
4781
4782 // not a symbol means non-trivial
4783 if (node->getAsSymbolNode() == nullptr)
4784 return false;
4785
4786 // a symbol, depends on what's being read
4787 switch (node->getType().getQualifier().storage) {
4788 case glslang::EvqTemporary:
4789 case glslang::EvqGlobal:
4790 case glslang::EvqIn:
4791 case glslang::EvqInOut:
4792 case glslang::EvqConst:
4793 case glslang::EvqConstReadOnly:
4794 case glslang::EvqUniform:
4795 return true;
4796 default:
4797 return false;
4798 }
qining25262b32016-05-06 17:25:16 -04004799}
John Kessenich7c1aa102015-10-15 13:29:11 -06004800
4801// A node is trivial if it is a single operation with no side effects.
4802// Error on the side of saying non-trivial.
4803// Return true if trivial.
4804bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4805{
4806 if (node == nullptr)
4807 return false;
4808
4809 // symbols and constants are trivial
4810 if (isTrivialLeaf(node))
4811 return true;
4812
4813 // otherwise, it needs to be a simple operation or one or two leaf nodes
4814
4815 // not a simple operation
4816 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4817 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4818 if (binaryNode == nullptr && unaryNode == nullptr)
4819 return false;
4820
4821 // not on leaf nodes
4822 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4823 return false;
4824
4825 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4826 return false;
4827 }
4828
4829 switch (node->getAsOperator()->getOp()) {
4830 case glslang::EOpLogicalNot:
4831 case glslang::EOpConvIntToBool:
4832 case glslang::EOpConvUintToBool:
4833 case glslang::EOpConvFloatToBool:
4834 case glslang::EOpConvDoubleToBool:
4835 case glslang::EOpEqual:
4836 case glslang::EOpNotEqual:
4837 case glslang::EOpLessThan:
4838 case glslang::EOpGreaterThan:
4839 case glslang::EOpLessThanEqual:
4840 case glslang::EOpGreaterThanEqual:
4841 case glslang::EOpIndexDirect:
4842 case glslang::EOpIndexDirectStruct:
4843 case glslang::EOpLogicalXor:
4844 case glslang::EOpAny:
4845 case glslang::EOpAll:
4846 return true;
4847 default:
4848 return false;
4849 }
4850}
4851
4852// Emit short-circuiting code, where 'right' is never evaluated unless
4853// the left side is true (for &&) or false (for ||).
4854spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4855{
4856 spv::Id boolTypeId = builder.makeBoolType();
4857
4858 // emit left operand
4859 builder.clearAccessChain();
4860 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004861 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004862
4863 // Operands to accumulate OpPhi operands
4864 std::vector<spv::Id> phiOperands;
4865 // accumulate left operand's phi information
4866 phiOperands.push_back(leftId);
4867 phiOperands.push_back(builder.getBuildPoint()->getId());
4868
4869 // Make the two kinds of operation symmetric with a "!"
4870 // || => emit "if (! left) result = right"
4871 // && => emit "if ( left) result = right"
4872 //
4873 // TODO: this runtime "not" for || could be avoided by adding functionality
4874 // to 'builder' to have an "else" without an "then"
4875 if (op == glslang::EOpLogicalOr)
4876 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4877
4878 // make an "if" based on the left value
4879 spv::Builder::If ifBuilder(leftId, builder);
4880
4881 // emit right operand as the "then" part of the "if"
4882 builder.clearAccessChain();
4883 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004884 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004885
4886 // accumulate left operand's phi information
4887 phiOperands.push_back(rightId);
4888 phiOperands.push_back(builder.getBuildPoint()->getId());
4889
4890 // finish the "if"
4891 ifBuilder.makeEndIf();
4892
4893 // phi together the two results
4894 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4895}
4896
Rex Xu9d93a232016-05-05 12:30:44 +08004897// Return type Id of the imported set of extended instructions corresponds to the name.
4898// Import this set if it has not been imported yet.
4899spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
4900{
4901 if (extBuiltinMap.find(name) != extBuiltinMap.end())
4902 return extBuiltinMap[name];
4903 else {
Rex Xu51596642016-09-21 18:56:12 +08004904 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08004905 spv::Id extBuiltins = builder.import(name);
4906 extBuiltinMap[name] = extBuiltins;
4907 return extBuiltins;
4908 }
4909}
4910
John Kessenich140f3df2015-06-26 16:58:36 -06004911}; // end anonymous namespace
4912
4913namespace glslang {
4914
John Kessenich68d78fd2015-07-12 19:28:10 -06004915void GetSpirvVersion(std::string& version)
4916{
John Kessenich9e55f632015-07-15 10:03:39 -06004917 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004918 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004919 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004920 version = buf;
4921}
4922
John Kessenich140f3df2015-06-26 16:58:36 -06004923// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004924void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06004925{
4926 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004927 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004928 for (int i = 0; i < (int)spirv.size(); ++i) {
4929 unsigned int word = spirv[i];
4930 out.write((const char*)&word, 4);
4931 }
4932 out.close();
4933}
4934
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05004935// Write SPIR-V out to a text file with 32-bit hexadecimal words
4936void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
4937{
4938 std::ofstream out;
4939 out.open(baseName, std::ios::binary | std::ios::out);
4940 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
4941 const int WORDS_PER_LINE = 8;
4942 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
4943 out << "\t";
4944 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
4945 const unsigned int word = spirv[i + j];
4946 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
4947 if (i + j + 1 < (int)spirv.size()) {
4948 out << ",";
4949 }
4950 }
4951 out << std::endl;
4952 }
4953 out.close();
4954}
4955
John Kessenich140f3df2015-06-26 16:58:36 -06004956//
4957// Set up the glslang traversal
4958//
4959void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4960{
Lei Zhang17535f72016-05-04 15:55:59 -04004961 spv::SpvBuildLogger logger;
4962 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004963}
4964
Lei Zhang17535f72016-05-04 15:55:59 -04004965void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004966{
John Kessenich140f3df2015-06-26 16:58:36 -06004967 TIntermNode* root = intermediate.getTreeRoot();
4968
4969 if (root == 0)
4970 return;
4971
4972 glslang::GetThreadPoolAllocator().push();
4973
Lei Zhang17535f72016-05-04 15:55:59 -04004974 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004975
4976 root->traverse(&it);
4977
4978 it.dumpSpv(spirv);
4979
4980 glslang::GetThreadPoolAllocator().pop();
4981}
4982
4983}; // end namespace glslang