blob: 15af947c29b810a3cf45296872a354de9a1c181a [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 Kessenichfca82622016-11-26 13:23:20 -0700102 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600103
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 Kessenichfca82622016-11-26 13:23:20 -0700114 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700115 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600116
117protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800118 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800119 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100120 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700121 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600122 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
123 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600124 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
125 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
126 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600127 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700128 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600129 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
130 glslang::TLayoutPacking, const glslang::TQualifier&);
131 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
132 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700133 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700134 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800135 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600136 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700137 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700138 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
139 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
140 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 +0100141 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600142
John Kessenich6fccb3c2016-09-19 16:01:41 -0600143 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600144 void makeFunctions(const glslang::TIntermSequence&);
145 void makeGlobalInitializers(const glslang::TIntermSequence&);
146 void visitFunctions(const glslang::TIntermSequence&);
147 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800148 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600149 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
150 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
152
qining25262b32016-05-06 17:25:16 -0400153 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);
154 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
155 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 +0800156 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 +0800157 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 -0600158 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800159 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 +0800160 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xub7072052016-09-26 15:53:40 +0800161 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600162 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 +0800163 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
165 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700166 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700168 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400169 spv::Id createSpvConstant(const glslang::TIntermTyped&);
170 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600171 bool isTrivialLeaf(const glslang::TIntermTyped* node);
172 bool isTrivial(const glslang::TIntermTyped* node);
173 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800174 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600175
176 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600177 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700178 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600179 int sequenceDepth;
180
Lei Zhang17535f72016-05-04 15:55:59 -0400181 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400182
John Kessenich140f3df2015-06-26 16:58:36 -0600183 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
184 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700185 bool inEntryPoint;
186 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700187 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 -0700188 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600189 const glslang::TIntermediate* glslangIntermediate;
190 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800191 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600192
John Kessenich2f273362015-07-18 22:34:27 -0600193 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600194 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600195 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700196 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600197 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 -0600198 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600199};
200
201//
202// Helper functions for translating glslang representations to SPIR-V enumerants.
203//
204
205// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700206spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600207{
John Kessenich66e2faf2016-03-12 18:34:36 -0700208 switch (source) {
209 case glslang::EShSourceGlsl:
210 switch (profile) {
211 case ENoProfile:
212 case ECoreProfile:
213 case ECompatibilityProfile:
214 return spv::SourceLanguageGLSL;
215 case EEsProfile:
216 return spv::SourceLanguageESSL;
217 default:
218 return spv::SourceLanguageUnknown;
219 }
220 case glslang::EShSourceHlsl:
Dan Baker55d5f2d2016-08-15 16:05:45 -0400221 //Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
222 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600223 default:
224 return spv::SourceLanguageUnknown;
225 }
226}
227
228// Translate glslang language (stage) to SPIR-V execution model.
229spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
230{
231 switch (stage) {
232 case EShLangVertex: return spv::ExecutionModelVertex;
233 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
234 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
235 case EShLangGeometry: return spv::ExecutionModelGeometry;
236 case EShLangFragment: return spv::ExecutionModelFragment;
237 case EShLangCompute: return spv::ExecutionModelGLCompute;
238 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700239 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600240 return spv::ExecutionModelFragment;
241 }
242}
243
244// Translate glslang type to SPIR-V storage class.
245spv::StorageClass TranslateStorageClass(const glslang::TType& type)
246{
247 if (type.getQualifier().isPipeInput())
248 return spv::StorageClassInput;
249 else if (type.getQualifier().isPipeOutput())
250 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700251 else if (type.getBasicType() == glslang::EbtSampler)
252 return spv::StorageClassUniformConstant;
253 else if (type.getBasicType() == glslang::EbtAtomicUint)
254 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600255 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700256 if (type.getQualifier().layoutPushConstant)
257 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 if (type.getBasicType() == glslang::EbtBlock)
259 return spv::StorageClassUniform;
260 else
261 return spv::StorageClassUniformConstant;
John Kessenich5aa59e22016-06-17 15:50:47 -0600262 // 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 -0600263 } else {
264 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700265 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
266 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600267 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
268 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400269 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700270 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600271 return spv::StorageClassFunction;
272 }
273 }
274}
275
276// Translate glslang sampler type to SPIR-V dimensionality.
277spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
278{
279 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700280 case glslang::Esd1D: return spv::Dim1D;
281 case glslang::Esd2D: return spv::Dim2D;
282 case glslang::Esd3D: return spv::Dim3D;
283 case glslang::EsdCube: return spv::DimCube;
284 case glslang::EsdRect: return spv::DimRect;
285 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700286 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600287 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700288 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600289 return spv::Dim2D;
290 }
291}
292
John Kessenichf6640762016-08-01 19:44:00 -0600293// Translate glslang precision to SPIR-V precision decorations.
294spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600295{
John Kessenichf6640762016-08-01 19:44:00 -0600296 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700297 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600298 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600299 default:
300 return spv::NoPrecision;
301 }
302}
303
John Kessenichf6640762016-08-01 19:44:00 -0600304// Translate glslang type to SPIR-V precision decorations.
305spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
306{
307 return TranslatePrecisionDecoration(type.getQualifier().precision);
308}
309
John Kessenich140f3df2015-06-26 16:58:36 -0600310// Translate glslang type to SPIR-V block decorations.
311spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
312{
313 if (type.getBasicType() == glslang::EbtBlock) {
314 switch (type.getQualifier().storage) {
315 case glslang::EvqUniform: return spv::DecorationBlock;
316 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
317 case glslang::EvqVaryingIn: return spv::DecorationBlock;
318 case glslang::EvqVaryingOut: return spv::DecorationBlock;
319 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700320 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600321 break;
322 }
323 }
324
John Kessenich4016e382016-07-15 11:53:56 -0600325 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600326}
327
Rex Xu1da878f2016-02-21 20:59:01 +0800328// Translate glslang type to SPIR-V memory decorations.
329void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
330{
331 if (qualifier.coherent)
332 memory.push_back(spv::DecorationCoherent);
333 if (qualifier.volatil)
334 memory.push_back(spv::DecorationVolatile);
335 if (qualifier.restrict)
336 memory.push_back(spv::DecorationRestrict);
337 if (qualifier.readonly)
338 memory.push_back(spv::DecorationNonWritable);
339 if (qualifier.writeonly)
340 memory.push_back(spv::DecorationNonReadable);
341}
342
John Kessenich140f3df2015-06-26 16:58:36 -0600343// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700344spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600345{
346 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700347 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600348 case glslang::ElmRowMajor:
349 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600351 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 default:
353 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600354 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600355 }
356 } else {
357 switch (type.getBasicType()) {
358 default:
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 break;
361 case glslang::EbtBlock:
362 switch (type.getQualifier().storage) {
363 case glslang::EvqUniform:
364 case glslang::EvqBuffer:
365 switch (type.getQualifier().layoutPacking) {
366 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
368 default:
John Kessenich4016e382016-07-15 11:53:56 -0600369 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 }
371 case glslang::EvqVaryingIn:
372 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700373 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600374 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600375 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 }
379 }
380 }
381}
382
383// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600384// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700385// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800386spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600387{
Rex Xubbceed72016-05-21 09:40:44 +0800388 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700389 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600390 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800391 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700393 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600394 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800395#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800396 else if (qualifier.explicitInterp) {
397 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800398 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800399 }
Rex Xu9d93a232016-05-05 12:30:44 +0800400#endif
Rex Xubbceed72016-05-21 09:40:44 +0800401 else
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800403}
404
405// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600406// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800407// should be applied.
408spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
409{
410 if (qualifier.patch)
411 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700412 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600413 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700414 else if (qualifier.sample) {
415 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700417 } else
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600419}
420
John Kessenich92187592016-02-01 13:45:25 -0700421// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700422spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600423{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600425 return spv::DecorationInvariant;
426 else
John Kessenich4016e382016-07-15 11:53:56 -0600427 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600428}
429
qining9220dbb2016-05-04 17:34:38 -0400430// If glslang type is noContraction, return SPIR-V NoContraction decoration.
431spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
432{
433 if (qualifier.noContraction)
434 return spv::DecorationNoContraction;
435 else
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400437}
438
David Netoa901ffe2016-06-08 14:11:40 +0100439// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
440// associated capabilities when required. For some built-in variables, a capability
441// is generated only when using the variable in an executable instruction, but not when
442// just declaring a struct member variable with it. This is true for PointSize,
443// ClipDistance, and CullDistance.
444spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600445{
446 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700447 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600448 // Defer adding the capability until the built-in is actually used.
449 if (! memberDeclaration) {
450 switch (glslangIntermediate->getStage()) {
451 case EShLangGeometry:
452 builder.addCapability(spv::CapabilityGeometryPointSize);
453 break;
454 case EShLangTessControl:
455 case EShLangTessEvaluation:
456 builder.addCapability(spv::CapabilityTessellationPointSize);
457 break;
458 default:
459 break;
460 }
John Kessenich92187592016-02-01 13:45:25 -0700461 }
462 return spv::BuiltInPointSize;
463
John Kessenichebb50532016-05-16 19:22:05 -0600464 // These *Distance capabilities logically belong here, but if the member is declared and
465 // then never used, consumers of SPIR-V prefer the capability not be declared.
466 // They are now generated when used, rather than here when declared.
467 // Potentially, the specification should be more clear what the minimum
468 // use needed is to trigger the capability.
469 //
John Kessenich92187592016-02-01 13:45:25 -0700470 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100471 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600472 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700473 return spv::BuiltInClipDistance;
474
475 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100476 if (!memberDeclaration)
John Kessenich78a45572016-07-08 14:05:15 -0600477 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700478 return spv::BuiltInCullDistance;
479
480 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500481 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700482 return spv::BuiltInViewportIndex;
483
John Kessenich5e801132016-02-15 11:09:46 -0700484 case glslang::EbvSampleId:
485 builder.addCapability(spv::CapabilitySampleRateShading);
486 return spv::BuiltInSampleId;
487
488 case glslang::EbvSamplePosition:
489 builder.addCapability(spv::CapabilitySampleRateShading);
490 return spv::BuiltInSamplePosition;
491
492 case glslang::EbvSampleMask:
493 builder.addCapability(spv::CapabilitySampleRateShading);
494 return spv::BuiltInSampleMask;
495
John Kessenich78a45572016-07-08 14:05:15 -0600496 case glslang::EbvLayer:
497 builder.addCapability(spv::CapabilityGeometry);
498 return spv::BuiltInLayer;
499
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600501 case glslang::EbvVertexId: return spv::BuiltInVertexId;
502 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700503 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
504 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800505
John Kessenichda581a22015-10-14 14:10:30 -0600506 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800507 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
508 builder.addCapability(spv::CapabilityDrawParameters);
509 return spv::BuiltInBaseVertex;
510
John Kessenichda581a22015-10-14 14:10:30 -0600511 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800512 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
513 builder.addCapability(spv::CapabilityDrawParameters);
514 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200515
John Kessenichda581a22015-10-14 14:10:30 -0600516 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800517 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
518 builder.addCapability(spv::CapabilityDrawParameters);
519 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200520
521 case glslang::EbvPrimitiveId:
522 if (glslangIntermediate->getStage() == EShLangFragment)
523 builder.addCapability(spv::CapabilityGeometry);
524 return spv::BuiltInPrimitiveId;
525
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
528 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
529 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
530 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
531 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
532 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
533 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600534 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
535 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
536 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
537 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
538 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
539 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
540 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
541 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800542
Rex Xu574ab042016-04-14 16:53:07 +0800543 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800544 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800545 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
546 return spv::BuiltInSubgroupSize;
547
Rex Xu574ab042016-04-14 16:53:07 +0800548 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800549 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
551 return spv::BuiltInSubgroupLocalInvocationId;
552
Rex Xu574ab042016-04-14 16:53:07 +0800553 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800554 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
555 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
556 return spv::BuiltInSubgroupEqMaskKHR;
557
Rex Xu574ab042016-04-14 16:53:07 +0800558 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800559 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
560 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
561 return spv::BuiltInSubgroupGeMaskKHR;
562
Rex Xu574ab042016-04-14 16:53:07 +0800563 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800564 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
565 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
566 return spv::BuiltInSubgroupGtMaskKHR;
567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupLeMaskKHR;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLtMaskKHR;
577
Rex Xu9d93a232016-05-05 12:30:44 +0800578#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800579 case glslang::EbvBaryCoordNoPersp:
580 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
581 return spv::BuiltInBaryCoordNoPerspAMD;
582
583 case glslang::EbvBaryCoordNoPerspCentroid:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
586
587 case glslang::EbvBaryCoordNoPerspSample:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordNoPerspSampleAMD;
590
591 case glslang::EbvBaryCoordSmooth:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordSmoothAMD;
594
595 case glslang::EbvBaryCoordSmoothCentroid:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothCentroidAMD;
598
599 case glslang::EbvBaryCoordSmoothSample:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordSmoothSampleAMD;
602
603 case glslang::EbvBaryCoordPullModel:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800606#endif
John Kessenich4016e382016-07-15 11:53:56 -0600607 default: return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600608 }
609}
610
Rex Xufc618912015-09-09 16:42:49 +0800611// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700612spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800613{
614 assert(type.getBasicType() == glslang::EbtSampler);
615
John Kessenich5d0fa972016-02-15 11:57:00 -0700616 // Check for capabilities
617 switch (type.getQualifier().layoutFormat) {
618 case glslang::ElfRg32f:
619 case glslang::ElfRg16f:
620 case glslang::ElfR11fG11fB10f:
621 case glslang::ElfR16f:
622 case glslang::ElfRgba16:
623 case glslang::ElfRgb10A2:
624 case glslang::ElfRg16:
625 case glslang::ElfRg8:
626 case glslang::ElfR16:
627 case glslang::ElfR8:
628 case glslang::ElfRgba16Snorm:
629 case glslang::ElfRg16Snorm:
630 case glslang::ElfRg8Snorm:
631 case glslang::ElfR16Snorm:
632 case glslang::ElfR8Snorm:
633
634 case glslang::ElfRg32i:
635 case glslang::ElfRg16i:
636 case glslang::ElfRg8i:
637 case glslang::ElfR16i:
638 case glslang::ElfR8i:
639
640 case glslang::ElfRgb10a2ui:
641 case glslang::ElfRg32ui:
642 case glslang::ElfRg16ui:
643 case glslang::ElfRg8ui:
644 case glslang::ElfR16ui:
645 case glslang::ElfR8ui:
646 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
647 break;
648
649 default:
650 break;
651 }
652
653 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800654 switch (type.getQualifier().layoutFormat) {
655 case glslang::ElfNone: return spv::ImageFormatUnknown;
656 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
657 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
658 case glslang::ElfR32f: return spv::ImageFormatR32f;
659 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
660 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
661 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
662 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
663 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
664 case glslang::ElfR16f: return spv::ImageFormatR16f;
665 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
666 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
667 case glslang::ElfRg16: return spv::ImageFormatRg16;
668 case glslang::ElfRg8: return spv::ImageFormatRg8;
669 case glslang::ElfR16: return spv::ImageFormatR16;
670 case glslang::ElfR8: return spv::ImageFormatR8;
671 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
672 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
673 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
674 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
675 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
676 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
677 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
678 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
679 case glslang::ElfR32i: return spv::ImageFormatR32i;
680 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
681 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
682 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
683 case glslang::ElfR16i: return spv::ImageFormatR16i;
684 case glslang::ElfR8i: return spv::ImageFormatR8i;
685 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
686 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
687 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
688 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
689 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
690 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
691 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
692 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
693 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
694 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600695 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800696 }
697}
698
qining25262b32016-05-06 17:25:16 -0400699// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700700// descriptor set.
701bool IsDescriptorResource(const glslang::TType& type)
702{
John Kessenichf7497e22016-03-08 21:36:22 -0700703 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700704 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700705 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700706
707 // non block...
708 // basically samplerXXX/subpass/sampler/texture are all included
709 // if they are the global-scope-class, not the function parameter
710 // (or local, if they ever exist) class.
711 if (type.getBasicType() == glslang::EbtSampler)
712 return type.getQualifier().isUniformOrBuffer();
713
714 // None of the above.
715 return false;
716}
717
John Kesseniche0b6cad2015-12-24 10:30:13 -0700718void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
719{
720 if (child.layoutMatrix == glslang::ElmNone)
721 child.layoutMatrix = parent.layoutMatrix;
722
723 if (parent.invariant)
724 child.invariant = true;
725 if (parent.nopersp)
726 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800727#ifdef AMD_EXTENSIONS
728 if (parent.explicitInterp)
729 child.explicitInterp = true;
730#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700731 if (parent.flat)
732 child.flat = true;
733 if (parent.centroid)
734 child.centroid = true;
735 if (parent.patch)
736 child.patch = true;
737 if (parent.sample)
738 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800739 if (parent.coherent)
740 child.coherent = true;
741 if (parent.volatil)
742 child.volatil = true;
743 if (parent.restrict)
744 child.restrict = true;
745 if (parent.readonly)
746 child.readonly = true;
747 if (parent.writeonly)
748 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700749}
750
John Kessenichf2b7f332016-09-01 17:05:23 -0600751bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700752{
John Kessenich7b9fa252016-01-21 18:56:57 -0700753 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600754 // - struct members might inherit from a struct declaration
755 // (note that non-block structs don't explicitly inherit,
756 // only implicitly, meaning no decoration involved)
757 // - affect decorations on the struct members
758 // (note smooth does not, and expecting something like volatile
759 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700760 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600761 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700762}
763
John Kessenich140f3df2015-06-26 16:58:36 -0600764//
765// Implement the TGlslangToSpvTraverser class.
766//
767
Lei Zhang17535f72016-05-04 15:55:59 -0400768TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600769 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
770 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400771 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700772 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600773 glslangIntermediate(glslangIntermediate)
774{
775 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
776
777 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700778 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600779 stdBuiltins = builder.import("GLSL.std.450");
780 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600781 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
782 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600783
784 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600785 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
786 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600787 builder.addSourceExtension(it->c_str());
788
789 // Add the top-level modes for this shader.
790
John Kessenich92187592016-02-01 13:45:25 -0700791 if (glslangIntermediate->getXfbMode()) {
792 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600793 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700794 }
John Kessenich140f3df2015-06-26 16:58:36 -0600795
796 unsigned int mode;
797 switch (glslangIntermediate->getStage()) {
798 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600799 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600800 break;
801
802 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600803 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600804 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
805 break;
806
807 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600808 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600809 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700810 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
811 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
812 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; 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);
817
John Kesseniche6903322015-10-13 16:29:02 -0600818 switch (glslangIntermediate->getVertexSpacing()) {
819 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
820 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
821 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600822 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600823 }
John Kessenich4016e382016-07-15 11:53:56 -0600824 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600825 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
826
827 switch (glslangIntermediate->getVertexOrder()) {
828 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
829 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600830 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600831 }
John Kessenich4016e382016-07-15 11:53:56 -0600832 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600833 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
834
835 if (glslangIntermediate->getPointMode())
836 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600837 break;
838
839 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600840 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600841 switch (glslangIntermediate->getInputPrimitive()) {
842 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
843 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
844 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700845 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600846 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600847 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600848 }
John Kessenich4016e382016-07-15 11:53:56 -0600849 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600850 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600851
John Kessenich140f3df2015-06-26 16:58:36 -0600852 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
853
854 switch (glslangIntermediate->getOutputPrimitive()) {
855 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
856 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
857 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600858 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600859 }
John Kessenich4016e382016-07-15 11:53:56 -0600860 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600861 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
862 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
863 break;
864
865 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600866 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600867 if (glslangIntermediate->getPixelCenterInteger())
868 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600869
John Kessenich140f3df2015-06-26 16:58:36 -0600870 if (glslangIntermediate->getOriginUpperLeft())
871 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600872 else
873 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600874
875 if (glslangIntermediate->getEarlyFragmentTests())
876 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
877
878 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600879 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
880 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600881 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600882 }
John Kessenich4016e382016-07-15 11:53:56 -0600883 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600884 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
885
886 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
887 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600888 break;
889
890 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600891 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600892 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
893 glslangIntermediate->getLocalSize(1),
894 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600895 break;
896
897 default:
898 break;
899 }
John Kessenich140f3df2015-06-26 16:58:36 -0600900}
901
John Kessenichfca82622016-11-26 13:23:20 -0700902// Finish creating SPV, after the traversal is complete.
903void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700904{
John Kessenich517fe7a2016-11-26 13:31:47 -0700905 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700906 builder.setBuildPoint(shaderEntry->getLastBlock());
907 builder.leaveFunction();
908 }
909
John Kessenich7ba63412015-12-20 17:37:07 -0700910 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100911 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
912 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700913
qiningda397332016-03-09 19:54:03 -0500914 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700915}
916
John Kessenichfca82622016-11-26 13:23:20 -0700917// Write the SPV into 'out'.
918void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600919{
John Kessenichfca82622016-11-26 13:23:20 -0700920 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600921}
922
923//
924// Implement the traversal functions.
925//
926// Return true from interior nodes to have the external traversal
927// continue on to children. Return false if children were
928// already processed.
929//
930
931//
qining25262b32016-05-06 17:25:16 -0400932// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600933// - uniform/input reads
934// - output writes
935// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
936// - something simple that degenerates into the last bullet
937//
938void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
939{
qining75d1d802016-04-06 14:42:01 -0400940 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
941 if (symbol->getType().getQualifier().isSpecConstant())
942 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
943
John Kessenich140f3df2015-06-26 16:58:36 -0600944 // getSymbolId() will set up all the IO decorations on the first call.
945 // Formal function parameters were mapped during makeFunctions().
946 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700947
948 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
949 if (builder.isPointer(id)) {
950 spv::StorageClass sc = builder.getStorageClass(id);
951 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
952 iOSet.insert(id);
953 }
954
955 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700956 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600957 // Prepare to generate code for the access
958
959 // L-value chains will be computed left to right. We're on the symbol now,
960 // which is the left-most part of the access chain, so now is "clear" time,
961 // followed by setting the base.
962 builder.clearAccessChain();
963
964 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700965 // except for
John Kessenich4bf71552016-09-02 11:20:21 -0600966 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -0700967 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -0600968 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -0700969 // These are also pure R-values.
970 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -0600971 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -0600972 builder.setAccessChainRValue(id);
973 else
974 builder.setAccessChainLValue(id);
975 }
976}
977
978bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
979{
qining40887662016-04-03 22:20:42 -0400980 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
981 if (node->getType().getQualifier().isSpecConstant())
982 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
983
John Kessenich140f3df2015-06-26 16:58:36 -0600984 // First, handle special cases
985 switch (node->getOp()) {
986 case glslang::EOpAssign:
987 case glslang::EOpAddAssign:
988 case glslang::EOpSubAssign:
989 case glslang::EOpMulAssign:
990 case glslang::EOpVectorTimesMatrixAssign:
991 case glslang::EOpVectorTimesScalarAssign:
992 case glslang::EOpMatrixTimesScalarAssign:
993 case glslang::EOpMatrixTimesMatrixAssign:
994 case glslang::EOpDivAssign:
995 case glslang::EOpModAssign:
996 case glslang::EOpAndAssign:
997 case glslang::EOpInclusiveOrAssign:
998 case glslang::EOpExclusiveOrAssign:
999 case glslang::EOpLeftShiftAssign:
1000 case glslang::EOpRightShiftAssign:
1001 // A bin-op assign "a += b" means the same thing as "a = a + b"
1002 // where a is evaluated before b. For a simple assignment, GLSL
1003 // says to evaluate the left before the right. So, always, left
1004 // node then right node.
1005 {
1006 // get the left l-value, save it away
1007 builder.clearAccessChain();
1008 node->getLeft()->traverse(this);
1009 spv::Builder::AccessChain lValue = builder.getAccessChain();
1010
1011 // evaluate the right
1012 builder.clearAccessChain();
1013 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001014 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001015
1016 if (node->getOp() != glslang::EOpAssign) {
1017 // the left is also an r-value
1018 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001019 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001020
1021 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001022 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001023 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001024 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1025 node->getType().getBasicType());
1026
1027 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001028 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001029 }
1030
1031 // store the result
1032 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001033 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001034
1035 // assignments are expressions having an rValue after they are evaluated...
1036 builder.clearAccessChain();
1037 builder.setAccessChainRValue(rValue);
1038 }
1039 return false;
1040 case glslang::EOpIndexDirect:
1041 case glslang::EOpIndexDirectStruct:
1042 {
1043 // Get the left part of the access chain.
1044 node->getLeft()->traverse(this);
1045
1046 // Add the next element in the chain
1047
David Netoa901ffe2016-06-08 14:11:40 +01001048 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001049 if (! node->getLeft()->getType().isArray() &&
1050 node->getLeft()->getType().isVector() &&
1051 node->getOp() == glslang::EOpIndexDirect) {
1052 // This is essentially a hard-coded vector swizzle of size 1,
1053 // so short circuit the access-chain stuff with a swizzle.
1054 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001055 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001056 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001057 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001058 int spvIndex = glslangIndex;
1059 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1060 node->getOp() == glslang::EOpIndexDirectStruct)
1061 {
1062 // This may be, e.g., an anonymous block-member selection, which generally need
1063 // index remapping due to hidden members in anonymous blocks.
1064 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1065 assert(remapper.size() > 0);
1066 spvIndex = remapper[glslangIndex];
1067 }
John Kessenichebb50532016-05-16 19:22:05 -06001068
David Netoa901ffe2016-06-08 14:11:40 +01001069 // normal case for indexing array or structure or block
1070 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1071
1072 // Add capabilities here for accessing PointSize and clip/cull distance.
1073 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001074 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001075 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001076 }
1077 }
1078 return false;
1079 case glslang::EOpIndexIndirect:
1080 {
1081 // Structure or array or vector indirection.
1082 // Will use native SPIR-V access-chain for struct and array indirection;
1083 // matrices are arrays of vectors, so will also work for a matrix.
1084 // Will use the access chain's 'component' for variable index into a vector.
1085
1086 // This adapter is building access chains left to right.
1087 // Set up the access chain to the left.
1088 node->getLeft()->traverse(this);
1089
1090 // save it so that computing the right side doesn't trash it
1091 spv::Builder::AccessChain partial = builder.getAccessChain();
1092
1093 // compute the next index in the chain
1094 builder.clearAccessChain();
1095 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001096 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001097
1098 // restore the saved access chain
1099 builder.setAccessChain(partial);
1100
1101 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001102 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001103 else
John Kessenichfa668da2015-09-13 14:46:30 -06001104 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001105 }
1106 return false;
1107 case glslang::EOpVectorSwizzle:
1108 {
1109 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001110 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001111 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001112 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001113 }
1114 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -06001115 case glslang::EOpLogicalOr:
1116 case glslang::EOpLogicalAnd:
1117 {
1118
1119 // These may require short circuiting, but can sometimes be done as straight
1120 // binary operations. The right operand must be short circuited if it has
1121 // side effects, and should probably be if it is complex.
1122 if (isTrivial(node->getRight()->getAsTyped()))
1123 break; // handle below as a normal binary operation
1124 // otherwise, we need to do dynamic short circuiting on the right operand
1125 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1126 builder.clearAccessChain();
1127 builder.setAccessChainRValue(result);
1128 }
1129 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001130 default:
1131 break;
1132 }
1133
1134 // Assume generic binary op...
1135
John Kessenich32cfd492016-02-02 12:37:46 -07001136 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001137 builder.clearAccessChain();
1138 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001139 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001140
John Kessenich32cfd492016-02-02 12:37:46 -07001141 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001142 builder.clearAccessChain();
1143 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001144 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001145
John Kessenich32cfd492016-02-02 12:37:46 -07001146 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001147 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001148 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001149 convertGlslangToSpvType(node->getType()), left, right,
1150 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001151
John Kessenich50e57562015-12-21 21:21:11 -07001152 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001153 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001154 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001155 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001156 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001157 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001158 return false;
1159 }
John Kessenich140f3df2015-06-26 16:58:36 -06001160}
1161
1162bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1163{
qining40887662016-04-03 22:20:42 -04001164 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1165 if (node->getType().getQualifier().isSpecConstant())
1166 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1167
John Kessenichfc51d282015-08-19 13:34:18 -06001168 spv::Id result = spv::NoResult;
1169
1170 // try texturing first
1171 result = createImageTextureFunctionCall(node);
1172 if (result != spv::NoResult) {
1173 builder.clearAccessChain();
1174 builder.setAccessChainRValue(result);
1175
1176 return false; // done with this node
1177 }
1178
1179 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001180
1181 if (node->getOp() == glslang::EOpArrayLength) {
1182 // Quite special; won't want to evaluate the operand.
1183
1184 // Normal .length() would have been constant folded by the front-end.
1185 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001186 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001187 assert(node->getOperand()->getType().isRuntimeSizedArray());
1188 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1189 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001190 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1191 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001192
1193 builder.clearAccessChain();
1194 builder.setAccessChainRValue(length);
1195
1196 return false;
1197 }
1198
John Kessenichfc51d282015-08-19 13:34:18 -06001199 // Start by evaluating the operand
1200
John Kessenich8c8505c2016-07-26 12:50:38 -06001201 // Does it need a swizzle inversion? If so, evaluation is inverted;
1202 // operate first on the swizzle base, then apply the swizzle.
1203 spv::Id invertedType = spv::NoType;
1204 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1205 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1206 invertedType = getInvertedSwizzleType(*node->getOperand());
1207
John Kessenich140f3df2015-06-26 16:58:36 -06001208 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001209 if (invertedType != spv::NoType)
1210 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1211 else
1212 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001213
Rex Xufc618912015-09-09 16:42:49 +08001214 spv::Id operand = spv::NoResult;
1215
1216 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1217 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001218 node->getOp() == glslang::EOpAtomicCounter ||
1219 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001220 operand = builder.accessChainGetLValue(); // Special case l-value operands
1221 else
John Kessenich32cfd492016-02-02 12:37:46 -07001222 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
John Kessenichf6640762016-08-01 19:44:00 -06001224 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001225 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001226
1227 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001228 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001229 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001230
1231 // if not, then possibly an operation
1232 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001233 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001234
1235 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001236 if (invertedType)
1237 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1238
John Kessenich140f3df2015-06-26 16:58:36 -06001239 builder.clearAccessChain();
1240 builder.setAccessChainRValue(result);
1241
1242 return false; // done with this node
1243 }
1244
1245 // it must be a special case, check...
1246 switch (node->getOp()) {
1247 case glslang::EOpPostIncrement:
1248 case glslang::EOpPostDecrement:
1249 case glslang::EOpPreIncrement:
1250 case glslang::EOpPreDecrement:
1251 {
1252 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001253 spv::Id one = 0;
1254 if (node->getBasicType() == glslang::EbtFloat)
1255 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001256 else if (node->getBasicType() == glslang::EbtDouble)
1257 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001258#ifdef AMD_EXTENSIONS
1259 else if (node->getBasicType() == glslang::EbtFloat16)
1260 one = builder.makeFloat16Constant(1.0F);
1261#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001262 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1263 one = builder.makeInt64Constant(1);
1264 else
1265 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001266 glslang::TOperator op;
1267 if (node->getOp() == glslang::EOpPreIncrement ||
1268 node->getOp() == glslang::EOpPostIncrement)
1269 op = glslang::EOpAdd;
1270 else
1271 op = glslang::EOpSub;
1272
John Kessenichf6640762016-08-01 19:44:00 -06001273 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001274 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001275 convertGlslangToSpvType(node->getType()), operand, one,
1276 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001277 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001278
1279 // The result of operation is always stored, but conditionally the
1280 // consumed result. The consumed result is always an r-value.
1281 builder.accessChainStore(result);
1282 builder.clearAccessChain();
1283 if (node->getOp() == glslang::EOpPreIncrement ||
1284 node->getOp() == glslang::EOpPreDecrement)
1285 builder.setAccessChainRValue(result);
1286 else
1287 builder.setAccessChainRValue(operand);
1288 }
1289
1290 return false;
1291
1292 case glslang::EOpEmitStreamVertex:
1293 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1294 return false;
1295 case glslang::EOpEndStreamPrimitive:
1296 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1297 return false;
1298
1299 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001300 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001301 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001302 }
John Kessenich140f3df2015-06-26 16:58:36 -06001303}
1304
1305bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1306{
qining27e04a02016-04-14 16:40:20 -04001307 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1308 if (node->getType().getQualifier().isSpecConstant())
1309 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1310
John Kessenichfc51d282015-08-19 13:34:18 -06001311 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001312 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1313 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001314
1315 // try texturing
1316 result = createImageTextureFunctionCall(node);
1317 if (result != spv::NoResult) {
1318 builder.clearAccessChain();
1319 builder.setAccessChainRValue(result);
1320
1321 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001322 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001323 // "imageStore" is a special case, which has no result
1324 return false;
1325 }
John Kessenichfc51d282015-08-19 13:34:18 -06001326
John Kessenich140f3df2015-06-26 16:58:36 -06001327 glslang::TOperator binOp = glslang::EOpNull;
1328 bool reduceComparison = true;
1329 bool isMatrix = false;
1330 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001331 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001332
1333 assert(node->getOp());
1334
John Kessenichf6640762016-08-01 19:44:00 -06001335 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001336
1337 switch (node->getOp()) {
1338 case glslang::EOpSequence:
1339 {
1340 if (preVisit)
1341 ++sequenceDepth;
1342 else
1343 --sequenceDepth;
1344
1345 if (sequenceDepth == 1) {
1346 // If this is the parent node of all the functions, we want to see them
1347 // early, so all call points have actual SPIR-V functions to reference.
1348 // In all cases, still let the traverser visit the children for us.
1349 makeFunctions(node->getAsAggregate()->getSequence());
1350
John Kessenich6fccb3c2016-09-19 16:01:41 -06001351 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001352 // anything else gets there, so visit out of order, doing them all now.
1353 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1354
John Kessenich6a60c2f2016-12-08 21:01:59 -07001355 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001356 // so do them manually.
1357 visitFunctions(node->getAsAggregate()->getSequence());
1358
1359 return false;
1360 }
1361
1362 return true;
1363 }
1364 case glslang::EOpLinkerObjects:
1365 {
1366 if (visit == glslang::EvPreVisit)
1367 linkageOnly = true;
1368 else
1369 linkageOnly = false;
1370
1371 return true;
1372 }
1373 case glslang::EOpComma:
1374 {
1375 // processing from left to right naturally leaves the right-most
1376 // lying around in the access chain
1377 glslang::TIntermSequence& glslangOperands = node->getSequence();
1378 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1379 glslangOperands[i]->traverse(this);
1380
1381 return false;
1382 }
1383 case glslang::EOpFunction:
1384 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001385 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001386 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001387 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001388 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001389 } else {
1390 handleFunctionEntry(node);
1391 }
1392 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001393 if (inEntryPoint)
1394 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001395 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001396 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001397 }
1398
1399 return true;
1400 case glslang::EOpParameters:
1401 // Parameters will have been consumed by EOpFunction processing, but not
1402 // the body, so we still visited the function node's children, making this
1403 // child redundant.
1404 return false;
1405 case glslang::EOpFunctionCall:
1406 {
1407 if (node->isUserDefined())
1408 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001409 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1410 if (result) {
1411 builder.clearAccessChain();
1412 builder.setAccessChainRValue(result);
1413 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001414 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001415
1416 return false;
1417 }
1418 case glslang::EOpConstructMat2x2:
1419 case glslang::EOpConstructMat2x3:
1420 case glslang::EOpConstructMat2x4:
1421 case glslang::EOpConstructMat3x2:
1422 case glslang::EOpConstructMat3x3:
1423 case glslang::EOpConstructMat3x4:
1424 case glslang::EOpConstructMat4x2:
1425 case glslang::EOpConstructMat4x3:
1426 case glslang::EOpConstructMat4x4:
1427 case glslang::EOpConstructDMat2x2:
1428 case glslang::EOpConstructDMat2x3:
1429 case glslang::EOpConstructDMat2x4:
1430 case glslang::EOpConstructDMat3x2:
1431 case glslang::EOpConstructDMat3x3:
1432 case glslang::EOpConstructDMat3x4:
1433 case glslang::EOpConstructDMat4x2:
1434 case glslang::EOpConstructDMat4x3:
1435 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001436#ifdef AMD_EXTENSIONS
1437 case glslang::EOpConstructF16Mat2x2:
1438 case glslang::EOpConstructF16Mat2x3:
1439 case glslang::EOpConstructF16Mat2x4:
1440 case glslang::EOpConstructF16Mat3x2:
1441 case glslang::EOpConstructF16Mat3x3:
1442 case glslang::EOpConstructF16Mat3x4:
1443 case glslang::EOpConstructF16Mat4x2:
1444 case glslang::EOpConstructF16Mat4x3:
1445 case glslang::EOpConstructF16Mat4x4:
1446#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001447 isMatrix = true;
1448 // fall through
1449 case glslang::EOpConstructFloat:
1450 case glslang::EOpConstructVec2:
1451 case glslang::EOpConstructVec3:
1452 case glslang::EOpConstructVec4:
1453 case glslang::EOpConstructDouble:
1454 case glslang::EOpConstructDVec2:
1455 case glslang::EOpConstructDVec3:
1456 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001457#ifdef AMD_EXTENSIONS
1458 case glslang::EOpConstructFloat16:
1459 case glslang::EOpConstructF16Vec2:
1460 case glslang::EOpConstructF16Vec3:
1461 case glslang::EOpConstructF16Vec4:
1462#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001463 case glslang::EOpConstructBool:
1464 case glslang::EOpConstructBVec2:
1465 case glslang::EOpConstructBVec3:
1466 case glslang::EOpConstructBVec4:
1467 case glslang::EOpConstructInt:
1468 case glslang::EOpConstructIVec2:
1469 case glslang::EOpConstructIVec3:
1470 case glslang::EOpConstructIVec4:
1471 case glslang::EOpConstructUint:
1472 case glslang::EOpConstructUVec2:
1473 case glslang::EOpConstructUVec3:
1474 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001475 case glslang::EOpConstructInt64:
1476 case glslang::EOpConstructI64Vec2:
1477 case glslang::EOpConstructI64Vec3:
1478 case glslang::EOpConstructI64Vec4:
1479 case glslang::EOpConstructUint64:
1480 case glslang::EOpConstructU64Vec2:
1481 case glslang::EOpConstructU64Vec3:
1482 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001483 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001484 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001485 {
1486 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001487 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001488 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001489 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001490 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001491 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001492 std::vector<spv::Id> constituents;
1493 for (int c = 0; c < (int)arguments.size(); ++c)
1494 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001495 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001496 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001497 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001498 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001499 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001500
1501 builder.clearAccessChain();
1502 builder.setAccessChainRValue(constructed);
1503
1504 return false;
1505 }
1506
1507 // These six are component-wise compares with component-wise results.
1508 // Forward on to createBinaryOperation(), requesting a vector result.
1509 case glslang::EOpLessThan:
1510 case glslang::EOpGreaterThan:
1511 case glslang::EOpLessThanEqual:
1512 case glslang::EOpGreaterThanEqual:
1513 case glslang::EOpVectorEqual:
1514 case glslang::EOpVectorNotEqual:
1515 {
1516 // Map the operation to a binary
1517 binOp = node->getOp();
1518 reduceComparison = false;
1519 switch (node->getOp()) {
1520 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1521 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1522 default: binOp = node->getOp(); break;
1523 }
1524
1525 break;
1526 }
1527 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001528 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001529 binOp = glslang::EOpMul;
1530 break;
1531 case glslang::EOpOuterProduct:
1532 // two vectors multiplied to make a matrix
1533 binOp = glslang::EOpOuterProduct;
1534 break;
1535 case glslang::EOpDot:
1536 {
qining25262b32016-05-06 17:25:16 -04001537 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001538 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001539 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001540 binOp = glslang::EOpMul;
1541 break;
1542 }
1543 case glslang::EOpMod:
1544 // when an aggregate, this is the floating-point mod built-in function,
1545 // which can be emitted by the one in createBinaryOperation()
1546 binOp = glslang::EOpMod;
1547 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001548 case glslang::EOpEmitVertex:
1549 case glslang::EOpEndPrimitive:
1550 case glslang::EOpBarrier:
1551 case glslang::EOpMemoryBarrier:
1552 case glslang::EOpMemoryBarrierAtomicCounter:
1553 case glslang::EOpMemoryBarrierBuffer:
1554 case glslang::EOpMemoryBarrierImage:
1555 case glslang::EOpMemoryBarrierShared:
1556 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001557 case glslang::EOpAllMemoryBarrierWithGroupSync:
1558 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1559 case glslang::EOpWorkgroupMemoryBarrier:
1560 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001561 noReturnValue = true;
1562 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1563 break;
1564
John Kessenich426394d2015-07-23 10:22:48 -06001565 case glslang::EOpAtomicAdd:
1566 case glslang::EOpAtomicMin:
1567 case glslang::EOpAtomicMax:
1568 case glslang::EOpAtomicAnd:
1569 case glslang::EOpAtomicOr:
1570 case glslang::EOpAtomicXor:
1571 case glslang::EOpAtomicExchange:
1572 case glslang::EOpAtomicCompSwap:
1573 atomic = true;
1574 break;
1575
John Kessenich140f3df2015-06-26 16:58:36 -06001576 default:
1577 break;
1578 }
1579
1580 //
1581 // See if it maps to a regular operation.
1582 //
John Kessenich140f3df2015-06-26 16:58:36 -06001583 if (binOp != glslang::EOpNull) {
1584 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1585 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1586 assert(left && right);
1587
1588 builder.clearAccessChain();
1589 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001590 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001591
1592 builder.clearAccessChain();
1593 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001594 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001595
qining25262b32016-05-06 17:25:16 -04001596 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001597 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001598 left->getType().getBasicType(), reduceComparison);
1599
1600 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001601 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.clearAccessChain();
1603 builder.setAccessChainRValue(result);
1604
1605 return false;
1606 }
1607
John Kessenich426394d2015-07-23 10:22:48 -06001608 //
1609 // Create the list of operands.
1610 //
John Kessenich140f3df2015-06-26 16:58:36 -06001611 glslang::TIntermSequence& glslangOperands = node->getSequence();
1612 std::vector<spv::Id> operands;
1613 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001614 // special case l-value operands; there are just a few
1615 bool lvalue = false;
1616 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001617 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001618 case glslang::EOpModf:
1619 if (arg == 1)
1620 lvalue = true;
1621 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001622 case glslang::EOpInterpolateAtSample:
1623 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001624#ifdef AMD_EXTENSIONS
1625 case glslang::EOpInterpolateAtVertex:
1626#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001627 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001628 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001629
1630 // Does it need a swizzle inversion? If so, evaluation is inverted;
1631 // operate first on the swizzle base, then apply the swizzle.
1632 if (glslangOperands[0]->getAsOperator() &&
1633 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1634 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1635 }
Rex Xu7a26c172015-12-08 17:12:09 +08001636 break;
Rex Xud4782c12015-09-06 16:30:11 +08001637 case glslang::EOpAtomicAdd:
1638 case glslang::EOpAtomicMin:
1639 case glslang::EOpAtomicMax:
1640 case glslang::EOpAtomicAnd:
1641 case glslang::EOpAtomicOr:
1642 case glslang::EOpAtomicXor:
1643 case glslang::EOpAtomicExchange:
1644 case glslang::EOpAtomicCompSwap:
1645 if (arg == 0)
1646 lvalue = true;
1647 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001648 case glslang::EOpAddCarry:
1649 case glslang::EOpSubBorrow:
1650 if (arg == 2)
1651 lvalue = true;
1652 break;
1653 case glslang::EOpUMulExtended:
1654 case glslang::EOpIMulExtended:
1655 if (arg >= 2)
1656 lvalue = true;
1657 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001658 default:
1659 break;
1660 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001661 builder.clearAccessChain();
1662 if (invertedType != spv::NoType && arg == 0)
1663 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1664 else
1665 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001666 if (lvalue)
1667 operands.push_back(builder.accessChainGetLValue());
1668 else
John Kessenich32cfd492016-02-02 12:37:46 -07001669 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001670 }
John Kessenich426394d2015-07-23 10:22:48 -06001671
1672 if (atomic) {
1673 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001674 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001675 } else {
1676 // Pass through to generic operations.
1677 switch (glslangOperands.size()) {
1678 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001679 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001680 break;
1681 case 1:
qining25262b32016-05-06 17:25:16 -04001682 result = createUnaryOperation(
1683 node->getOp(), precision,
1684 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001685 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001686 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001687 break;
1688 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001689 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001690 break;
1691 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001692 if (invertedType)
1693 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001694 }
1695
1696 if (noReturnValue)
1697 return false;
1698
1699 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001700 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001701 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001702 } else {
1703 builder.clearAccessChain();
1704 builder.setAccessChainRValue(result);
1705 return false;
1706 }
1707}
1708
1709bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1710{
1711 // This path handles both if-then-else and ?:
1712 // The if-then-else has a node type of void, while
1713 // ?: has a non-void node type
1714 spv::Id result = 0;
1715 if (node->getBasicType() != glslang::EbtVoid) {
1716 // don't handle this as just on-the-fly temporaries, because there will be two names
1717 // and better to leave SSA to later passes
1718 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1719 }
1720
1721 // emit the condition before doing anything with selection
1722 node->getCondition()->traverse(this);
1723
1724 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001725 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001726
1727 if (node->getTrueBlock()) {
1728 // emit the "then" statement
1729 node->getTrueBlock()->traverse(this);
1730 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001731 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001732 }
1733
1734 if (node->getFalseBlock()) {
1735 ifBuilder.makeBeginElse();
1736 // emit the "else" statement
1737 node->getFalseBlock()->traverse(this);
1738 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001739 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001740 }
1741
1742 ifBuilder.makeEndIf();
1743
1744 if (result) {
1745 // GLSL only has r-values as the result of a :?, but
1746 // if we have an l-value, that can be more efficient if it will
1747 // become the base of a complex r-value expression, because the
1748 // next layer copies r-values into memory to use the access-chain mechanism
1749 builder.clearAccessChain();
1750 builder.setAccessChainLValue(result);
1751 }
1752
1753 return false;
1754}
1755
1756bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1757{
1758 // emit and get the condition before doing anything with switch
1759 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001760 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001761
1762 // browse the children to sort out code segments
1763 int defaultSegment = -1;
1764 std::vector<TIntermNode*> codeSegments;
1765 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1766 std::vector<int> caseValues;
1767 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1768 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1769 TIntermNode* child = *c;
1770 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001771 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001772 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001773 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001774 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1775 } else
1776 codeSegments.push_back(child);
1777 }
1778
qining25262b32016-05-06 17:25:16 -04001779 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001780 // statements between the last case and the end of the switch statement
1781 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1782 (int)codeSegments.size() == defaultSegment)
1783 codeSegments.push_back(nullptr);
1784
1785 // make the switch statement
1786 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001787 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001788
1789 // emit all the code in the segments
1790 breakForLoop.push(false);
1791 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1792 builder.nextSwitchSegment(segmentBlocks, s);
1793 if (codeSegments[s])
1794 codeSegments[s]->traverse(this);
1795 else
1796 builder.addSwitchBreak();
1797 }
1798 breakForLoop.pop();
1799
1800 builder.endSwitch(segmentBlocks);
1801
1802 return false;
1803}
1804
1805void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1806{
1807 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001808 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001809
1810 builder.clearAccessChain();
1811 builder.setAccessChainRValue(constant);
1812}
1813
1814bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1815{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001816 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001817 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001818 // Spec requires back edges to target header blocks, and every header block
1819 // must dominate its merge block. Make a header block first to ensure these
1820 // conditions are met. By definition, it will contain OpLoopMerge, followed
1821 // by a block-ending branch. But we don't want to put any other body/test
1822 // instructions in it, since the body/test may have arbitrary instructions,
1823 // including merges of its own.
1824 builder.setBuildPoint(&blocks.head);
1825 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001826 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001827 spv::Block& test = builder.makeNewBlock();
1828 builder.createBranch(&test);
1829
1830 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001831 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001832 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001833 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001834 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1835
1836 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001837 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001838 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001839 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001840 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001841 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001842
1843 builder.setBuildPoint(&blocks.continue_target);
1844 if (node->getTerminal())
1845 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001846 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001847 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001848 builder.createBranch(&blocks.body);
1849
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001850 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001851 builder.setBuildPoint(&blocks.body);
1852 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001853 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001854 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001855 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001856
1857 builder.setBuildPoint(&blocks.continue_target);
1858 if (node->getTerminal())
1859 node->getTerminal()->traverse(this);
1860 if (node->getTest()) {
1861 node->getTest()->traverse(this);
1862 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001863 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001864 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001865 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001866 // TODO: unless there was a break/return/discard instruction
1867 // somewhere in the body, this is an infinite loop, so we should
1868 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001869 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001870 }
John Kessenich140f3df2015-06-26 16:58:36 -06001871 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001872 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001873 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001874 return false;
1875}
1876
1877bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1878{
1879 if (node->getExpression())
1880 node->getExpression()->traverse(this);
1881
1882 switch (node->getFlowOp()) {
1883 case glslang::EOpKill:
1884 builder.makeDiscard();
1885 break;
1886 case glslang::EOpBreak:
1887 if (breakForLoop.top())
1888 builder.createLoopExit();
1889 else
1890 builder.addSwitchBreak();
1891 break;
1892 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001893 builder.createLoopContinue();
1894 break;
1895 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06001896 if (node->getExpression()) {
1897 const glslang::TType& glslangReturnType = node->getExpression()->getType();
1898 spv::Id returnId = accessChainLoad(glslangReturnType);
1899 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
1900 builder.clearAccessChain();
1901 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
1902 builder.setAccessChainLValue(copyId);
1903 multiTypeStore(glslangReturnType, returnId);
1904 returnId = builder.createLoad(copyId);
1905 }
1906 builder.makeReturn(false, returnId);
1907 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06001908 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001909
1910 builder.clearAccessChain();
1911 break;
1912
1913 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001914 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001915 break;
1916 }
1917
1918 return false;
1919}
1920
1921spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1922{
qining25262b32016-05-06 17:25:16 -04001923 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06001924 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001925 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001926 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001927 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001928 }
1929
1930 // Now, handle actual variables
1931 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1932 spv::Id spvType = convertGlslangToSpvType(node->getType());
1933
1934 const char* name = node->getName().c_str();
1935 if (glslang::IsAnonymous(name))
1936 name = "";
1937
1938 return builder.createVariable(storageClass, spvType, name);
1939}
1940
1941// Return type Id of the sampled type.
1942spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1943{
1944 switch (sampler.type) {
1945 case glslang::EbtFloat: return builder.makeFloatType(32);
1946 case glslang::EbtInt: return builder.makeIntType(32);
1947 case glslang::EbtUint: return builder.makeUintType(32);
1948 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001949 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001950 return builder.makeFloatType(32);
1951 }
1952}
1953
John Kessenich8c8505c2016-07-26 12:50:38 -06001954// If node is a swizzle operation, return the type that should be used if
1955// the swizzle base is first consumed by another operation, before the swizzle
1956// is applied.
1957spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
1958{
1959 if (node.getAsOperator() &&
1960 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1961 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
1962 else
1963 return spv::NoType;
1964}
1965
1966// When inverting a swizzle with a parent op, this function
1967// will apply the swizzle operation to a completed parent operation.
1968spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
1969{
1970 std::vector<unsigned> swizzle;
1971 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
1972 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
1973}
1974
John Kessenich8c8505c2016-07-26 12:50:38 -06001975// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
1976void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
1977{
1978 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
1979 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
1980 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
1981}
1982
John Kessenich3ac051e2015-12-20 11:29:16 -07001983// Convert from a glslang type to an SPV type, by calling into a
1984// recursive version of this function. This establishes the inherited
1985// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001986spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1987{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001988 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001989}
1990
1991// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001992// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06001993// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07001994spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001995{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001996 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001997
1998 switch (type.getBasicType()) {
1999 case glslang::EbtVoid:
2000 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002001 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002002 break;
2003 case glslang::EbtFloat:
2004 spvType = builder.makeFloatType(32);
2005 break;
2006 case glslang::EbtDouble:
2007 spvType = builder.makeFloatType(64);
2008 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002009#ifdef AMD_EXTENSIONS
2010 case glslang::EbtFloat16:
2011 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2012 builder.addCapability(spv::CapabilityFloat16);
2013 spvType = builder.makeFloatType(16);
2014 break;
2015#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002016 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002017 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2018 // a 32-bit int where non-0 means true.
2019 if (explicitLayout != glslang::ElpNone)
2020 spvType = builder.makeUintType(32);
2021 else
2022 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002023 break;
2024 case glslang::EbtInt:
2025 spvType = builder.makeIntType(32);
2026 break;
2027 case glslang::EbtUint:
2028 spvType = builder.makeUintType(32);
2029 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002030 case glslang::EbtInt64:
2031 builder.addCapability(spv::CapabilityInt64);
2032 spvType = builder.makeIntType(64);
2033 break;
2034 case glslang::EbtUint64:
2035 builder.addCapability(spv::CapabilityInt64);
2036 spvType = builder.makeUintType(64);
2037 break;
John Kessenich426394d2015-07-23 10:22:48 -06002038 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002039 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002040 spvType = builder.makeUintType(32);
2041 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002042 case glslang::EbtSampler:
2043 {
2044 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002045 if (sampler.sampler) {
2046 // pure sampler
2047 spvType = builder.makeSamplerType();
2048 } else {
2049 // an image is present, make its type
2050 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2051 sampler.image ? 2 : 1, TranslateImageFormat(type));
2052 if (sampler.combined) {
2053 // already has both image and sampler, make the combined type
2054 spvType = builder.makeSampledImageType(spvType);
2055 }
John Kessenich55e7d112015-11-15 21:33:39 -07002056 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002057 }
John Kessenich140f3df2015-06-26 16:58:36 -06002058 break;
2059 case glslang::EbtStruct:
2060 case glslang::EbtBlock:
2061 {
2062 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002063 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002064
2065 // Try to share structs for different layouts, but not yet for other
2066 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002067 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002068 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002069 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002070 break;
2071
2072 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002073 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002074 memberRemapper[glslangMembers].resize(glslangMembers->size());
2075 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002076 }
2077 break;
2078 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002079 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002080 break;
2081 }
2082
2083 if (type.isMatrix())
2084 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2085 else {
2086 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2087 if (type.getVectorSize() > 1)
2088 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2089 }
2090
2091 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002092 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2093
John Kessenichc9a80832015-09-12 12:17:44 -06002094 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002095 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002096 // We need to decorate array strides for types needing explicit layout, except blocks.
2097 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002098 // Use a dummy glslang type for querying internal strides of
2099 // arrays of arrays, but using just a one-dimensional array.
2100 glslang::TType simpleArrayType(type, 0); // deference type of the array
2101 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2102 simpleArrayType.getArraySizes().dereference();
2103
2104 // Will compute the higher-order strides here, rather than making a whole
2105 // pile of types and doing repetitive recursion on their contents.
2106 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2107 }
John Kessenichf8842e52016-01-04 19:22:56 -07002108
2109 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002110 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002111 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002112 if (stride > 0)
2113 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002114 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002115 }
2116 } else {
2117 // single-dimensional array, and don't yet have stride
2118
John Kessenichf8842e52016-01-04 19:22:56 -07002119 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002120 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2121 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002122 }
John Kessenich31ed4832015-09-09 17:51:38 -06002123
John Kessenichc9a80832015-09-12 12:17:44 -06002124 // Do the outer dimension, which might not be known for a runtime-sized array
2125 if (type.isRuntimeSizedArray()) {
2126 spvType = builder.makeRuntimeArray(spvType);
2127 } else {
2128 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002129 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002130 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002131 if (stride > 0)
2132 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002133 }
2134
2135 return spvType;
2136}
2137
John Kessenich6090df02016-06-30 21:18:02 -06002138
2139// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2140// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2141// Mutually recursive with convertGlslangToSpvType().
2142spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2143 const glslang::TTypeList* glslangMembers,
2144 glslang::TLayoutPacking explicitLayout,
2145 const glslang::TQualifier& qualifier)
2146{
2147 // Create a vector of struct types for SPIR-V to consume
2148 std::vector<spv::Id> spvMembers;
2149 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2150 int locationOffset = 0; // for use across struct members, when they are called recursively
2151 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2152 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2153 if (glslangMember.hiddenMember()) {
2154 ++memberDelta;
2155 if (type.getBasicType() == glslang::EbtBlock)
2156 memberRemapper[glslangMembers][i] = -1;
2157 } else {
2158 if (type.getBasicType() == glslang::EbtBlock)
2159 memberRemapper[glslangMembers][i] = i - memberDelta;
2160 // modify just this child's view of the qualifier
2161 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2162 InheritQualifiers(memberQualifier, qualifier);
2163
2164 // manually inherit location; it's more complex
2165 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2166 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2167 if (qualifier.hasLocation())
2168 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2169
2170 // recurse
2171 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2172 }
2173 }
2174
2175 // Make the SPIR-V type
2176 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002177 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002178 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2179
2180 // Decorate it
2181 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2182
2183 return spvType;
2184}
2185
2186void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2187 const glslang::TTypeList* glslangMembers,
2188 glslang::TLayoutPacking explicitLayout,
2189 const glslang::TQualifier& qualifier,
2190 spv::Id spvType)
2191{
2192 // Name and decorate the non-hidden members
2193 int offset = -1;
2194 int locationOffset = 0; // for use within the members of this struct
2195 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2196 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2197 int member = i;
2198 if (type.getBasicType() == glslang::EbtBlock)
2199 member = memberRemapper[glslangMembers][i];
2200
2201 // modify just this child's view of the qualifier
2202 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2203 InheritQualifiers(memberQualifier, qualifier);
2204
2205 // using -1 above to indicate a hidden member
2206 if (member >= 0) {
2207 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2208 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2209 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2210 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
2211 if (type.getQualifier().storage == glslang::EvqVaryingIn || type.getQualifier().storage == glslang::EvqVaryingOut) {
2212 if (type.getBasicType() == glslang::EbtBlock) {
2213 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2214 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2215 }
2216 }
2217 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2218
2219 if (qualifier.storage == glslang::EvqBuffer) {
2220 std::vector<spv::Decoration> memory;
2221 TranslateMemoryDecoration(memberQualifier, memory);
2222 for (unsigned int i = 0; i < memory.size(); ++i)
2223 addMemberDecoration(spvType, member, memory[i]);
2224 }
2225
John Kessenich2f47bc92016-06-30 21:47:35 -06002226 // Compute location decoration; tricky based on whether inheritance is at play and
2227 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002228 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2229 // probably move to the linker stage of the front end proper, and just have the
2230 // answer sitting already distributed throughout the individual member locations.
2231 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002232 // Ignore member locations if the container is an array, as that's
2233 // ill-specified and decisions have been made to not allow this anyway.
2234 // The object itself must have a location, and that comes out from decorating the object,
2235 // not the type (this code decorates types).
2236 if (! type.isArray()) {
2237 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2238 // struct members should not have explicit locations
2239 assert(type.getBasicType() != glslang::EbtStruct);
2240 location = memberQualifier.layoutLocation;
2241 } else if (type.getBasicType() != glslang::EbtBlock) {
2242 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2243 // The members, and their nested types, must not themselves have Location decorations.
2244 } else if (qualifier.hasLocation()) // inheritance
2245 location = qualifier.layoutLocation + locationOffset;
2246 }
John Kessenich6090df02016-06-30 21:18:02 -06002247 if (location >= 0)
2248 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2249
John Kessenich2f47bc92016-06-30 21:47:35 -06002250 if (qualifier.hasLocation()) // track for upcoming inheritance
2251 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2252
John Kessenich6090df02016-06-30 21:18:02 -06002253 // component, XFB, others
2254 if (glslangMember.getQualifier().hasComponent())
2255 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2256 if (glslangMember.getQualifier().hasXfbOffset())
2257 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2258 else if (explicitLayout != glslang::ElpNone) {
2259 // figure out what to do with offset, which is accumulating
2260 int nextOffset;
2261 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2262 if (offset >= 0)
2263 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2264 offset = nextOffset;
2265 }
2266
2267 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2268 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2269
2270 // built-in variable decorations
2271 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002272 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002273 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
2274 }
2275 }
2276
2277 // Decorate the structure
2278 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2279 addDecoration(spvType, TranslateBlockDecoration(type));
2280 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2281 builder.addCapability(spv::CapabilityGeometryStreams);
2282 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2283 }
2284 if (glslangIntermediate->getXfbMode()) {
2285 builder.addCapability(spv::CapabilityTransformFeedback);
2286 if (type.getQualifier().hasXfbStride())
2287 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2288 if (type.getQualifier().hasXfbBuffer())
2289 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2290 }
2291}
2292
John Kessenich6c292d32016-02-15 20:58:50 -07002293// Turn the expression forming the array size into an id.
2294// This is not quite trivial, because of specialization constants.
2295// Sometimes, a raw constant is turned into an Id, and sometimes
2296// a specialization constant expression is.
2297spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2298{
2299 // First, see if this is sized with a node, meaning a specialization constant:
2300 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2301 if (specNode != nullptr) {
2302 builder.clearAccessChain();
2303 specNode->traverse(this);
2304 return accessChainLoad(specNode->getAsTyped()->getType());
2305 }
qining25262b32016-05-06 17:25:16 -04002306
John Kessenich6c292d32016-02-15 20:58:50 -07002307 // Otherwise, need a compile-time (front end) size, get it:
2308 int size = arraySizes.getDimSize(dim);
2309 assert(size > 0);
2310 return builder.makeUintConstant(size);
2311}
2312
John Kessenich103bef92016-02-08 21:38:15 -07002313// Wrap the builder's accessChainLoad to:
2314// - localize handling of RelaxedPrecision
2315// - use the SPIR-V inferred type instead of another conversion of the glslang type
2316// (avoids unnecessary work and possible type punning for structures)
2317// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002318spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2319{
John Kessenich103bef92016-02-08 21:38:15 -07002320 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2321 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2322
2323 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002324 if (type.getBasicType() == glslang::EbtBool) {
2325 if (builder.isScalarType(nominalTypeId)) {
2326 // Conversion for bool
2327 spv::Id boolType = builder.makeBoolType();
2328 if (nominalTypeId != boolType)
2329 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2330 } else if (builder.isVectorType(nominalTypeId)) {
2331 // Conversion for bvec
2332 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2333 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2334 if (nominalTypeId != bvecType)
2335 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2336 }
2337 }
John Kessenich103bef92016-02-08 21:38:15 -07002338
2339 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002340}
2341
Rex Xu27253232016-02-23 17:51:09 +08002342// Wrap the builder's accessChainStore to:
2343// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002344//
2345// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002346void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2347{
2348 // Need to convert to abstract types when necessary
2349 if (type.getBasicType() == glslang::EbtBool) {
2350 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2351
2352 if (builder.isScalarType(nominalTypeId)) {
2353 // Conversion for bool
2354 spv::Id boolType = builder.makeBoolType();
2355 if (nominalTypeId != boolType) {
2356 spv::Id zero = builder.makeUintConstant(0);
2357 spv::Id one = builder.makeUintConstant(1);
2358 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2359 }
2360 } else if (builder.isVectorType(nominalTypeId)) {
2361 // Conversion for bvec
2362 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2363 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2364 if (nominalTypeId != bvecType) {
2365 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2366 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2367 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2368 }
2369 }
2370 }
2371
2372 builder.accessChainStore(rvalue);
2373}
2374
John Kessenich4bf71552016-09-02 11:20:21 -06002375// For storing when types match at the glslang level, but not might match at the
2376// SPIR-V level.
2377//
2378// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002379// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002380// as in a member-decorated way.
2381//
2382// NOTE: This function can handle any store request; if it's not special it
2383// simplifies to a simple OpStore.
2384//
2385// Implicitly uses the existing builder.accessChain as the storage target.
2386void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2387{
John Kessenichb3e24e42016-09-11 12:33:43 -06002388 // we only do the complex path here if it's an aggregate
2389 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002390 accessChainStore(type, rValue);
2391 return;
2392 }
2393
John Kessenichb3e24e42016-09-11 12:33:43 -06002394 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002395 spv::Id rType = builder.getTypeId(rValue);
2396 spv::Id lValue = builder.accessChainGetLValue();
2397 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2398 if (lType == rType) {
2399 accessChainStore(type, rValue);
2400 return;
2401 }
2402
John Kessenichb3e24e42016-09-11 12:33:43 -06002403 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002404 // where the two types were the same type in GLSL. This requires member
2405 // by member copy, recursively.
2406
John Kessenichb3e24e42016-09-11 12:33:43 -06002407 // If an array, copy element by element.
2408 if (type.isArray()) {
2409 glslang::TType glslangElementType(type, 0);
2410 spv::Id elementRType = builder.getContainedTypeId(rType);
2411 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2412 // get the source member
2413 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002414
John Kessenichb3e24e42016-09-11 12:33:43 -06002415 // set up the target storage
2416 builder.clearAccessChain();
2417 builder.setAccessChainLValue(lValue);
2418 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002419
John Kessenichb3e24e42016-09-11 12:33:43 -06002420 // store the member
2421 multiTypeStore(glslangElementType, elementRValue);
2422 }
2423 } else {
2424 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002425
John Kessenichb3e24e42016-09-11 12:33:43 -06002426 // loop over structure members
2427 const glslang::TTypeList& members = *type.getStruct();
2428 for (int m = 0; m < (int)members.size(); ++m) {
2429 const glslang::TType& glslangMemberType = *members[m].type;
2430
2431 // get the source member
2432 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2433 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2434
2435 // set up the target storage
2436 builder.clearAccessChain();
2437 builder.setAccessChainLValue(lValue);
2438 builder.accessChainPush(builder.makeIntConstant(m));
2439
2440 // store the member
2441 multiTypeStore(glslangMemberType, memberRValue);
2442 }
John Kessenich4bf71552016-09-02 11:20:21 -06002443 }
2444}
2445
John Kessenichf85e8062015-12-19 13:57:10 -07002446// Decide whether or not this type should be
2447// decorated with offsets and strides, and if so
2448// whether std140 or std430 rules should be applied.
2449glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002450{
John Kessenichf85e8062015-12-19 13:57:10 -07002451 // has to be a block
2452 if (type.getBasicType() != glslang::EbtBlock)
2453 return glslang::ElpNone;
2454
2455 // has to be a uniform or buffer block
2456 if (type.getQualifier().storage != glslang::EvqUniform &&
2457 type.getQualifier().storage != glslang::EvqBuffer)
2458 return glslang::ElpNone;
2459
2460 // return the layout to use
2461 switch (type.getQualifier().layoutPacking) {
2462 case glslang::ElpStd140:
2463 case glslang::ElpStd430:
2464 return type.getQualifier().layoutPacking;
2465 default:
2466 return glslang::ElpNone;
2467 }
John Kessenich31ed4832015-09-09 17:51:38 -06002468}
2469
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002470// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002471int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002472{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002473 int size;
John Kessenich49987892015-12-29 17:11:44 -07002474 int stride;
2475 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002476
2477 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002478}
2479
John Kessenich49987892015-12-29 17:11:44 -07002480// 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 -07002481// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002482int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002483{
John Kessenich49987892015-12-29 17:11:44 -07002484 glslang::TType elementType;
2485 elementType.shallowCopy(matrixType);
2486 elementType.clearArraySizes();
2487
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002488 int size;
John Kessenich49987892015-12-29 17:11:44 -07002489 int stride;
2490 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2491
2492 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002493}
2494
John Kessenich5e4b1242015-08-06 22:53:06 -06002495// Given a member type of a struct, realign the current offset for it, and compute
2496// the next (not yet aligned) offset for the next member, which will get aligned
2497// on the next call.
2498// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2499// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2500// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002501void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002502 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002503{
2504 // this will get a positive value when deemed necessary
2505 nextOffset = -1;
2506
John Kessenich5e4b1242015-08-06 22:53:06 -06002507 // override anything in currentOffset with user-set offset
2508 if (memberType.getQualifier().hasOffset())
2509 currentOffset = memberType.getQualifier().layoutOffset;
2510
2511 // It could be that current linker usage in glslang updated all the layoutOffset,
2512 // in which case the following code does not matter. But, that's not quite right
2513 // once cross-compilation unit GLSL validation is done, as the original user
2514 // settings are needed in layoutOffset, and then the following will come into play.
2515
John Kessenichf85e8062015-12-19 13:57:10 -07002516 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002517 if (! memberType.getQualifier().hasOffset())
2518 currentOffset = -1;
2519
2520 return;
2521 }
2522
John Kessenichf85e8062015-12-19 13:57:10 -07002523 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002524 if (currentOffset < 0)
2525 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002526
John Kessenich5e4b1242015-08-06 22:53:06 -06002527 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2528 // but possibly not yet correctly aligned.
2529
2530 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002531 int dummyStride;
2532 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002533 glslang::RoundToPow2(currentOffset, memberAlignment);
2534 nextOffset = currentOffset + memberSize;
2535}
2536
David Netoa901ffe2016-06-08 14:11:40 +01002537void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002538{
David Netoa901ffe2016-06-08 14:11:40 +01002539 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2540 switch (glslangBuiltIn)
2541 {
2542 case glslang::EbvClipDistance:
2543 case glslang::EbvCullDistance:
2544 case glslang::EbvPointSize:
2545 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2546 // Alternately, we could just call this for any glslang built-in, since the
2547 // capability already guards against duplicates.
2548 TranslateBuiltInDecoration(glslangBuiltIn, false);
2549 break;
2550 default:
2551 // Capabilities were already generated when the struct was declared.
2552 break;
2553 }
John Kessenichebb50532016-05-16 19:22:05 -06002554}
2555
John Kessenich6fccb3c2016-09-19 16:01:41 -06002556bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002557{
John Kessenicheee9d532016-09-19 18:09:30 -06002558 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002559}
2560
2561// Make all the functions, skeletally, without actually visiting their bodies.
2562void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2563{
2564 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2565 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002566 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002567 continue;
2568
2569 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002570 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002571 //
qining25262b32016-05-06 17:25:16 -04002572 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002573 // function. What it is an address of varies:
2574 //
John Kessenich4bf71552016-09-02 11:20:21 -06002575 // - "in" parameters not marked as "const" can be written to without modifying the calling
2576 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002577 //
2578 // - "const in" parameters can just be the r-value, as no writes need occur.
2579 //
John Kessenich4bf71552016-09-02 11:20:21 -06002580 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2581 // 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 -06002582
2583 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002584 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002585 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2586
2587 for (int p = 0; p < (int)parameters.size(); ++p) {
2588 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2589 spv::Id typeId = convertGlslangToSpvType(paramType);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002590 if (paramType.isOpaque())
2591 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2592 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002593 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2594 else
John Kessenich4bf71552016-09-02 11:20:21 -06002595 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002596 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002597 paramTypes.push_back(typeId);
2598 }
2599
2600 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002601 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2602 convertGlslangToSpvType(glslFunction->getType()),
2603 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002604
2605 // Track function to emit/call later
2606 functionMap[glslFunction->getName().c_str()] = function;
2607
2608 // Set the parameter id's
2609 for (int p = 0; p < (int)parameters.size(); ++p) {
2610 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2611 // give a name too
2612 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2613 }
2614 }
2615}
2616
2617// Process all the initializers, while skipping the functions and link objects
2618void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2619{
2620 builder.setBuildPoint(shaderEntry->getLastBlock());
2621 for (int i = 0; i < (int)initializers.size(); ++i) {
2622 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2623 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2624
2625 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002626 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002627 initializer->traverse(this);
2628 }
2629 }
2630}
2631
2632// Process all the functions, while skipping initializers.
2633void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2634{
2635 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2636 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002637 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002638 node->traverse(this);
2639 }
2640}
2641
2642void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2643{
qining25262b32016-05-06 17:25:16 -04002644 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002645 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002646 currentFunction = functionMap[node->getName().c_str()];
2647 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002648 builder.setBuildPoint(functionBlock);
2649}
2650
Rex Xu04db3f52015-09-16 11:44:02 +08002651void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002652{
Rex Xufc618912015-09-09 16:42:49 +08002653 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002654
2655 glslang::TSampler sampler = {};
2656 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002657 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002658 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2659 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2660 }
2661
John Kessenich140f3df2015-06-26 16:58:36 -06002662 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2663 builder.clearAccessChain();
2664 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002665
2666 // Special case l-value operands
2667 bool lvalue = false;
2668 switch (node.getOp()) {
2669 case glslang::EOpImageAtomicAdd:
2670 case glslang::EOpImageAtomicMin:
2671 case glslang::EOpImageAtomicMax:
2672 case glslang::EOpImageAtomicAnd:
2673 case glslang::EOpImageAtomicOr:
2674 case glslang::EOpImageAtomicXor:
2675 case glslang::EOpImageAtomicExchange:
2676 case glslang::EOpImageAtomicCompSwap:
2677 if (i == 0)
2678 lvalue = true;
2679 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002680 case glslang::EOpSparseImageLoad:
2681 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2682 lvalue = true;
2683 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002684 case glslang::EOpSparseTexture:
2685 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2686 lvalue = true;
2687 break;
2688 case glslang::EOpSparseTextureClamp:
2689 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2690 lvalue = true;
2691 break;
2692 case glslang::EOpSparseTextureLod:
2693 case glslang::EOpSparseTextureOffset:
2694 if (i == 3)
2695 lvalue = true;
2696 break;
2697 case glslang::EOpSparseTextureFetch:
2698 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2699 lvalue = true;
2700 break;
2701 case glslang::EOpSparseTextureFetchOffset:
2702 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2703 lvalue = true;
2704 break;
2705 case glslang::EOpSparseTextureLodOffset:
2706 case glslang::EOpSparseTextureGrad:
2707 case glslang::EOpSparseTextureOffsetClamp:
2708 if (i == 4)
2709 lvalue = true;
2710 break;
2711 case glslang::EOpSparseTextureGradOffset:
2712 case glslang::EOpSparseTextureGradClamp:
2713 if (i == 5)
2714 lvalue = true;
2715 break;
2716 case glslang::EOpSparseTextureGradOffsetClamp:
2717 if (i == 6)
2718 lvalue = true;
2719 break;
2720 case glslang::EOpSparseTextureGather:
2721 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2722 lvalue = true;
2723 break;
2724 case glslang::EOpSparseTextureGatherOffset:
2725 case glslang::EOpSparseTextureGatherOffsets:
2726 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2727 lvalue = true;
2728 break;
Rex Xufc618912015-09-09 16:42:49 +08002729 default:
2730 break;
2731 }
2732
Rex Xu6b86d492015-09-16 17:48:22 +08002733 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002734 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002735 else
John Kessenich32cfd492016-02-02 12:37:46 -07002736 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002737 }
2738}
2739
John Kessenichfc51d282015-08-19 13:34:18 -06002740void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002741{
John Kessenichfc51d282015-08-19 13:34:18 -06002742 builder.clearAccessChain();
2743 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002744 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002745}
John Kessenich140f3df2015-06-26 16:58:36 -06002746
John Kessenichfc51d282015-08-19 13:34:18 -06002747spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2748{
Rex Xufc618912015-09-09 16:42:49 +08002749 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002750 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002751 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002752 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002753
John Kessenichfc51d282015-08-19 13:34:18 -06002754 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002755 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2756 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2757 std::vector<spv::Id> arguments;
2758 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002759 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002760 else
2761 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002762 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002763
2764 spv::Builder::TextureParameters params = { };
2765 params.sampler = arguments[0];
2766
Rex Xu04db3f52015-09-16 11:44:02 +08002767 glslang::TCrackedTextureOp cracked;
2768 node->crackTexture(sampler, cracked);
2769
John Kessenichfc51d282015-08-19 13:34:18 -06002770 // Check for queries
2771 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002772 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2773 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002774 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002775
John Kessenichfc51d282015-08-19 13:34:18 -06002776 switch (node->getOp()) {
2777 case glslang::EOpImageQuerySize:
2778 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002779 if (arguments.size() > 1) {
2780 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002781 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002782 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002783 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002784 case glslang::EOpImageQuerySamples:
2785 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002786 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002787 case glslang::EOpTextureQueryLod:
2788 params.coords = arguments[1];
2789 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2790 case glslang::EOpTextureQueryLevels:
2791 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002792 case glslang::EOpSparseTexelsResident:
2793 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002794 default:
2795 assert(0);
2796 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002797 }
John Kessenich140f3df2015-06-26 16:58:36 -06002798 }
2799
Rex Xufc618912015-09-09 16:42:49 +08002800 // Check for image functions other than queries
2801 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002802 std::vector<spv::Id> operands;
2803 auto opIt = arguments.begin();
2804 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002805
2806 // Handle subpass operations
2807 // TODO: GLSL should change to have the "MS" only on the type rather than the
2808 // built-in function.
2809 if (cracked.subpass) {
2810 // add on the (0,0) coordinate
2811 spv::Id zero = builder.makeIntConstant(0);
2812 std::vector<spv::Id> comps;
2813 comps.push_back(zero);
2814 comps.push_back(zero);
2815 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2816 if (sampler.ms) {
2817 operands.push_back(spv::ImageOperandsSampleMask);
2818 operands.push_back(*(opIt++));
2819 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002820 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002821 }
2822
John Kessenich56bab042015-09-16 10:54:31 -06002823 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002824 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002825 if (sampler.ms) {
2826 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002827 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002828 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002829 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2830 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002831 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002832 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002833 if (sampler.ms) {
2834 operands.push_back(*(opIt + 1));
2835 operands.push_back(spv::ImageOperandsSampleMask);
2836 operands.push_back(*opIt);
2837 } else
2838 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002839 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002840 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2841 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002842 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002843 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2844 builder.addCapability(spv::CapabilitySparseResidency);
2845 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2846 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2847
2848 if (sampler.ms) {
2849 operands.push_back(spv::ImageOperandsSampleMask);
2850 operands.push_back(*opIt++);
2851 }
2852
2853 // Create the return type that was a special structure
2854 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002855 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002856 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2857 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2858
2859 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2860
2861 // Decode the return type
2862 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2863 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002864 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002865 // Process image atomic operations
2866
2867 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2868 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002869 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002870
John Kessenich8c8505c2016-07-26 12:50:38 -06002871 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06002872 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002873
2874 std::vector<spv::Id> operands;
2875 operands.push_back(pointer);
2876 for (; opIt != arguments.end(); ++opIt)
2877 operands.push_back(*opIt);
2878
John Kessenich8c8505c2016-07-26 12:50:38 -06002879 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002880 }
2881 }
2882
2883 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002884 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002885 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2886
John Kessenichfc51d282015-08-19 13:34:18 -06002887 // check for bias argument
2888 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002889 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002890 int nonBiasArgCount = 2;
2891 if (cracked.offset)
2892 ++nonBiasArgCount;
2893 if (cracked.grad)
2894 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002895 if (cracked.lodClamp)
2896 ++nonBiasArgCount;
2897 if (sparse)
2898 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002899
2900 if ((int)arguments.size() > nonBiasArgCount)
2901 bias = true;
2902 }
2903
John Kessenicha5c33d62016-06-02 23:45:21 -06002904 // See if the sampler param should really be just the SPV image part
2905 if (cracked.fetch) {
2906 // a fetch needs to have the image extracted first
2907 if (builder.isSampledImage(params.sampler))
2908 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
2909 }
2910
John Kessenichfc51d282015-08-19 13:34:18 -06002911 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002912
John Kessenichfc51d282015-08-19 13:34:18 -06002913 params.coords = arguments[1];
2914 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002915 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002916
2917 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002918 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002919 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002920 ++extraArgs;
2921 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002922 params.Dref = arguments[2];
2923 ++extraArgs;
2924 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002925 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06002926 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06002927 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06002928 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002929 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06002930 dRefComp = builder.getNumComponents(params.coords) - 1;
2931 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06002932 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2933 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002934
2935 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06002936 if (cracked.lod) {
2937 params.lod = arguments[2];
2938 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002939 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2940 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2941 noImplicitLod = true;
2942 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002943
2944 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07002945 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002946 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002947 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002948 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002949
2950 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06002951 if (cracked.grad) {
2952 params.gradX = arguments[2 + extraArgs];
2953 params.gradY = arguments[3 + extraArgs];
2954 extraArgs += 2;
2955 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002956
2957 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07002958 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002959 params.offset = arguments[2 + extraArgs];
2960 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002961 } else if (cracked.offsets) {
2962 params.offsets = arguments[2 + extraArgs];
2963 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002964 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002965
2966 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08002967 if (cracked.lodClamp) {
2968 params.lodClamp = arguments[2 + extraArgs];
2969 ++extraArgs;
2970 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002971
2972 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08002973 if (sparse) {
2974 params.texelOut = arguments[2 + extraArgs];
2975 ++extraArgs;
2976 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002977
2978 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06002979 if (bias) {
2980 params.bias = arguments[2 + extraArgs];
2981 ++extraArgs;
2982 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06002983
2984 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07002985 if (cracked.gather && ! sampler.shadow) {
2986 // default component is 0, if missing, otherwise an argument
2987 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002988 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07002989 ++extraArgs;
2990 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06002991 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07002992 }
2993 }
John Kessenichfc51d282015-08-19 13:34:18 -06002994
John Kessenich65336482016-06-16 14:06:26 -06002995 // projective component (might not to move)
2996 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
2997 // are divided by the last component of P."
2998 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
2999 // unused components will appear after all used components."
3000 if (cracked.proj) {
3001 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3002 int projTargetComp;
3003 switch (sampler.dim) {
3004 case glslang::Esd1D: projTargetComp = 1; break;
3005 case glslang::Esd2D: projTargetComp = 2; break;
3006 case glslang::EsdRect: projTargetComp = 2; break;
3007 default: projTargetComp = projSourceComp; break;
3008 }
3009 // copy the projective coordinate if we have to
3010 if (projTargetComp != projSourceComp) {
3011 spv::Id projComp = builder.createCompositeExtract(params.coords,
3012 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3013 projSourceComp);
3014 params.coords = builder.createCompositeInsert(projComp, params.coords,
3015 builder.getTypeId(params.coords), projTargetComp);
3016 }
3017 }
3018
John Kessenich8c8505c2016-07-26 12:50:38 -06003019 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003020}
3021
3022spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3023{
3024 // Grab the function's pointer from the previously created function
3025 spv::Function* function = functionMap[node->getName().c_str()];
3026 if (! function)
3027 return 0;
3028
3029 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3030 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3031
3032 // See comments in makeFunctions() for details about the semantics for parameter passing.
3033 //
3034 // These imply we need a four step process:
3035 // 1. Evaluate the arguments
3036 // 2. Allocate and make copies of in, out, and inout arguments
3037 // 3. Make the call
3038 // 4. Copy back the results
3039
3040 // 1. Evaluate the arguments
3041 std::vector<spv::Builder::AccessChain> lValues;
3042 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003043 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003044 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003045 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003046 // build l-value
3047 builder.clearAccessChain();
3048 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003049 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003050 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
Jason Ekstranded15ef12016-06-08 13:54:48 -07003051 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.isOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003052 // save l-value
3053 lValues.push_back(builder.getAccessChain());
3054 } else {
3055 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003056 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003057 }
3058 }
3059
3060 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3061 // copy the original into that space.
3062 //
3063 // Also, build up the list of actual arguments to pass in for the call
3064 int lValueCount = 0;
3065 int rValueCount = 0;
3066 std::vector<spv::Id> spvArgs;
3067 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003068 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003069 spv::Id arg;
Jason Ekstranded15ef12016-06-08 13:54:48 -07003070 if (paramType.isOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003071 builder.setAccessChain(lValues[lValueCount]);
3072 arg = builder.accessChainGetLValue();
3073 ++lValueCount;
3074 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003075 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003076 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3077 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3078 // need to copy the input into output space
3079 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003080 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003081 builder.clearAccessChain();
3082 builder.setAccessChainLValue(arg);
3083 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003084 }
3085 ++lValueCount;
3086 } else {
3087 arg = rValues[rValueCount];
3088 ++rValueCount;
3089 }
3090 spvArgs.push_back(arg);
3091 }
3092
3093 // 3. Make the call.
3094 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003095 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003096
3097 // 4. Copy back out an "out" arguments.
3098 lValueCount = 0;
3099 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003100 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003101 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3102 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3103 spv::Id copy = builder.createLoad(spvArgs[a]);
3104 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003105 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003106 }
3107 ++lValueCount;
3108 }
3109 }
3110
3111 return result;
3112}
3113
3114// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003115spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3116 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003117 spv::Id typeId, spv::Id left, spv::Id right,
3118 glslang::TBasicType typeProxy, bool reduceComparison)
3119{
Rex Xu8ff43de2016-04-22 16:51:45 +08003120 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003121#ifdef AMD_EXTENSIONS
3122 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3123#else
John Kessenich140f3df2015-06-26 16:58:36 -06003124 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003125#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003126 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003127
3128 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003129 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003130 bool comparison = false;
3131
3132 switch (op) {
3133 case glslang::EOpAdd:
3134 case glslang::EOpAddAssign:
3135 if (isFloat)
3136 binOp = spv::OpFAdd;
3137 else
3138 binOp = spv::OpIAdd;
3139 break;
3140 case glslang::EOpSub:
3141 case glslang::EOpSubAssign:
3142 if (isFloat)
3143 binOp = spv::OpFSub;
3144 else
3145 binOp = spv::OpISub;
3146 break;
3147 case glslang::EOpMul:
3148 case glslang::EOpMulAssign:
3149 if (isFloat)
3150 binOp = spv::OpFMul;
3151 else
3152 binOp = spv::OpIMul;
3153 break;
3154 case glslang::EOpVectorTimesScalar:
3155 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003156 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003157 if (builder.isVector(right))
3158 std::swap(left, right);
3159 assert(builder.isScalar(right));
3160 needMatchingVectors = false;
3161 binOp = spv::OpVectorTimesScalar;
3162 } else
3163 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003164 break;
3165 case glslang::EOpVectorTimesMatrix:
3166 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003167 binOp = spv::OpVectorTimesMatrix;
3168 break;
3169 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003170 binOp = spv::OpMatrixTimesVector;
3171 break;
3172 case glslang::EOpMatrixTimesScalar:
3173 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003174 binOp = spv::OpMatrixTimesScalar;
3175 break;
3176 case glslang::EOpMatrixTimesMatrix:
3177 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003178 binOp = spv::OpMatrixTimesMatrix;
3179 break;
3180 case glslang::EOpOuterProduct:
3181 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003182 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003183 break;
3184
3185 case glslang::EOpDiv:
3186 case glslang::EOpDivAssign:
3187 if (isFloat)
3188 binOp = spv::OpFDiv;
3189 else if (isUnsigned)
3190 binOp = spv::OpUDiv;
3191 else
3192 binOp = spv::OpSDiv;
3193 break;
3194 case glslang::EOpMod:
3195 case glslang::EOpModAssign:
3196 if (isFloat)
3197 binOp = spv::OpFMod;
3198 else if (isUnsigned)
3199 binOp = spv::OpUMod;
3200 else
3201 binOp = spv::OpSMod;
3202 break;
3203 case glslang::EOpRightShift:
3204 case glslang::EOpRightShiftAssign:
3205 if (isUnsigned)
3206 binOp = spv::OpShiftRightLogical;
3207 else
3208 binOp = spv::OpShiftRightArithmetic;
3209 break;
3210 case glslang::EOpLeftShift:
3211 case glslang::EOpLeftShiftAssign:
3212 binOp = spv::OpShiftLeftLogical;
3213 break;
3214 case glslang::EOpAnd:
3215 case glslang::EOpAndAssign:
3216 binOp = spv::OpBitwiseAnd;
3217 break;
3218 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003219 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003220 binOp = spv::OpLogicalAnd;
3221 break;
3222 case glslang::EOpInclusiveOr:
3223 case glslang::EOpInclusiveOrAssign:
3224 binOp = spv::OpBitwiseOr;
3225 break;
3226 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003227 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003228 binOp = spv::OpLogicalOr;
3229 break;
3230 case glslang::EOpExclusiveOr:
3231 case glslang::EOpExclusiveOrAssign:
3232 binOp = spv::OpBitwiseXor;
3233 break;
3234 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003235 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003236 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003237 break;
3238
3239 case glslang::EOpLessThan:
3240 case glslang::EOpGreaterThan:
3241 case glslang::EOpLessThanEqual:
3242 case glslang::EOpGreaterThanEqual:
3243 case glslang::EOpEqual:
3244 case glslang::EOpNotEqual:
3245 case glslang::EOpVectorEqual:
3246 case glslang::EOpVectorNotEqual:
3247 comparison = true;
3248 break;
3249 default:
3250 break;
3251 }
3252
John Kessenich7c1aa102015-10-15 13:29:11 -06003253 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003254 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003255 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003256 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003257 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003258
3259 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003260 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003261 builder.promoteScalar(precision, left, right);
3262
qining25262b32016-05-06 17:25:16 -04003263 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3264 addDecoration(result, noContraction);
3265 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003266 }
3267
3268 if (! comparison)
3269 return 0;
3270
John Kessenich7c1aa102015-10-15 13:29:11 -06003271 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003272
John Kessenich4583b612016-08-07 19:14:22 -06003273 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3274 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003275 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003276
3277 switch (op) {
3278 case glslang::EOpLessThan:
3279 if (isFloat)
3280 binOp = spv::OpFOrdLessThan;
3281 else if (isUnsigned)
3282 binOp = spv::OpULessThan;
3283 else
3284 binOp = spv::OpSLessThan;
3285 break;
3286 case glslang::EOpGreaterThan:
3287 if (isFloat)
3288 binOp = spv::OpFOrdGreaterThan;
3289 else if (isUnsigned)
3290 binOp = spv::OpUGreaterThan;
3291 else
3292 binOp = spv::OpSGreaterThan;
3293 break;
3294 case glslang::EOpLessThanEqual:
3295 if (isFloat)
3296 binOp = spv::OpFOrdLessThanEqual;
3297 else if (isUnsigned)
3298 binOp = spv::OpULessThanEqual;
3299 else
3300 binOp = spv::OpSLessThanEqual;
3301 break;
3302 case glslang::EOpGreaterThanEqual:
3303 if (isFloat)
3304 binOp = spv::OpFOrdGreaterThanEqual;
3305 else if (isUnsigned)
3306 binOp = spv::OpUGreaterThanEqual;
3307 else
3308 binOp = spv::OpSGreaterThanEqual;
3309 break;
3310 case glslang::EOpEqual:
3311 case glslang::EOpVectorEqual:
3312 if (isFloat)
3313 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003314 else if (isBool)
3315 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003316 else
3317 binOp = spv::OpIEqual;
3318 break;
3319 case glslang::EOpNotEqual:
3320 case glslang::EOpVectorNotEqual:
3321 if (isFloat)
3322 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003323 else if (isBool)
3324 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003325 else
3326 binOp = spv::OpINotEqual;
3327 break;
3328 default:
3329 break;
3330 }
3331
qining25262b32016-05-06 17:25:16 -04003332 if (binOp != spv::OpNop) {
3333 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3334 addDecoration(result, noContraction);
3335 return builder.setPrecision(result, precision);
3336 }
John Kessenich140f3df2015-06-26 16:58:36 -06003337
3338 return 0;
3339}
3340
John Kessenich04bb8a02015-12-12 12:28:14 -07003341//
3342// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3343// These can be any of:
3344//
3345// matrix * scalar
3346// scalar * matrix
3347// matrix * matrix linear algebraic
3348// matrix * vector
3349// vector * matrix
3350// matrix * matrix componentwise
3351// matrix op matrix op in {+, -, /}
3352// matrix op scalar op in {+, -, /}
3353// scalar op matrix op in {+, -, /}
3354//
qining25262b32016-05-06 17:25:16 -04003355spv::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 -07003356{
3357 bool firstClass = true;
3358
3359 // First, handle first-class matrix operations (* and matrix/scalar)
3360 switch (op) {
3361 case spv::OpFDiv:
3362 if (builder.isMatrix(left) && builder.isScalar(right)) {
3363 // turn matrix / scalar into a multiply...
3364 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3365 op = spv::OpMatrixTimesScalar;
3366 } else
3367 firstClass = false;
3368 break;
3369 case spv::OpMatrixTimesScalar:
3370 if (builder.isMatrix(right))
3371 std::swap(left, right);
3372 assert(builder.isScalar(right));
3373 break;
3374 case spv::OpVectorTimesMatrix:
3375 assert(builder.isVector(left));
3376 assert(builder.isMatrix(right));
3377 break;
3378 case spv::OpMatrixTimesVector:
3379 assert(builder.isMatrix(left));
3380 assert(builder.isVector(right));
3381 break;
3382 case spv::OpMatrixTimesMatrix:
3383 assert(builder.isMatrix(left));
3384 assert(builder.isMatrix(right));
3385 break;
3386 default:
3387 firstClass = false;
3388 break;
3389 }
3390
qining25262b32016-05-06 17:25:16 -04003391 if (firstClass) {
3392 spv::Id result = builder.createBinOp(op, typeId, left, right);
3393 addDecoration(result, noContraction);
3394 return builder.setPrecision(result, precision);
3395 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003396
LoopDawg592860c2016-06-09 08:57:35 -06003397 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003398 // The result type of all of them is the same type as the (a) matrix operand.
3399 // The algorithm is to:
3400 // - break the matrix(es) into vectors
3401 // - smear any scalar to a vector
3402 // - do vector operations
3403 // - make a matrix out the vector results
3404 switch (op) {
3405 case spv::OpFAdd:
3406 case spv::OpFSub:
3407 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003408 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003409 case spv::OpFMul:
3410 {
3411 // one time set up...
3412 bool leftMat = builder.isMatrix(left);
3413 bool rightMat = builder.isMatrix(right);
3414 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3415 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3416 spv::Id scalarType = builder.getScalarTypeId(typeId);
3417 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3418 std::vector<spv::Id> results;
3419 spv::Id smearVec = spv::NoResult;
3420 if (builder.isScalar(left))
3421 smearVec = builder.smearScalar(precision, left, vecType);
3422 else if (builder.isScalar(right))
3423 smearVec = builder.smearScalar(precision, right, vecType);
3424
3425 // do each vector op
3426 for (unsigned int c = 0; c < numCols; ++c) {
3427 std::vector<unsigned int> indexes;
3428 indexes.push_back(c);
3429 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3430 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003431 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3432 addDecoration(result, noContraction);
3433 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003434 }
3435
3436 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003437 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003438 }
3439 default:
3440 assert(0);
3441 return spv::NoResult;
3442 }
3443}
3444
qining25262b32016-05-06 17:25:16 -04003445spv::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 -06003446{
3447 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003448 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003449 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003450 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003451#ifdef AMD_EXTENSIONS
3452 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3453#else
Rex Xu04db3f52015-09-16 11:44:02 +08003454 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003455#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003456
3457 switch (op) {
3458 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003459 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003460 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003461 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003462 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003463 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003464 unaryOp = spv::OpSNegate;
3465 break;
3466
3467 case glslang::EOpLogicalNot:
3468 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003469 unaryOp = spv::OpLogicalNot;
3470 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003471 case glslang::EOpBitwiseNot:
3472 unaryOp = spv::OpNot;
3473 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003474
John Kessenich140f3df2015-06-26 16:58:36 -06003475 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003476 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003477 break;
3478 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 break;
3481 case glslang::EOpTranspose:
3482 unaryOp = spv::OpTranspose;
3483 break;
3484
3485 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003486 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003487 break;
3488 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003489 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003490 break;
3491 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003492 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003493 break;
3494 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003495 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003496 break;
3497 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003498 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003499 break;
3500 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003501 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 break;
3503 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003504 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003505 break;
3506 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003507 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003508 break;
3509
3510 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003511 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003512 break;
3513 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003514 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003515 break;
3516 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003517 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003518 break;
3519 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003520 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003521 break;
3522 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003523 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003524 break;
3525 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003526 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003527 break;
3528
3529 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003530 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003531 break;
3532 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003533 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003534 break;
3535
3536 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003537 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003538 break;
3539 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003540 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003541 break;
3542 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003543 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003544 break;
3545 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003546 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003547 break;
3548 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003549 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003550 break;
3551 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003552 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003553 break;
3554
3555 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003556 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003557 break;
3558 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003559 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003560 break;
3561 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003562 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003563 break;
3564 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003565 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003566 break;
3567 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003568 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003569 break;
3570 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003571 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003572 break;
3573
3574 case glslang::EOpIsNan:
3575 unaryOp = spv::OpIsNan;
3576 break;
3577 case glslang::EOpIsInf:
3578 unaryOp = spv::OpIsInf;
3579 break;
LoopDawg592860c2016-06-09 08:57:35 -06003580 case glslang::EOpIsFinite:
3581 unaryOp = spv::OpIsFinite;
3582 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003583
Rex Xucbc426e2015-12-15 16:03:10 +08003584 case glslang::EOpFloatBitsToInt:
3585 case glslang::EOpFloatBitsToUint:
3586 case glslang::EOpIntBitsToFloat:
3587 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003588 case glslang::EOpDoubleBitsToInt64:
3589 case glslang::EOpDoubleBitsToUint64:
3590 case glslang::EOpInt64BitsToDouble:
3591 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003592 unaryOp = spv::OpBitcast;
3593 break;
3594
John Kessenich140f3df2015-06-26 16:58:36 -06003595 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003596 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003597 break;
3598 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003599 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003600 break;
3601 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003602 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003603 break;
3604 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003605 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003606 break;
3607 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003608 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003609 break;
3610 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003611 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003612 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003613 case glslang::EOpPackSnorm4x8:
3614 libCall = spv::GLSLstd450PackSnorm4x8;
3615 break;
3616 case glslang::EOpUnpackSnorm4x8:
3617 libCall = spv::GLSLstd450UnpackSnorm4x8;
3618 break;
3619 case glslang::EOpPackUnorm4x8:
3620 libCall = spv::GLSLstd450PackUnorm4x8;
3621 break;
3622 case glslang::EOpUnpackUnorm4x8:
3623 libCall = spv::GLSLstd450UnpackUnorm4x8;
3624 break;
3625 case glslang::EOpPackDouble2x32:
3626 libCall = spv::GLSLstd450PackDouble2x32;
3627 break;
3628 case glslang::EOpUnpackDouble2x32:
3629 libCall = spv::GLSLstd450UnpackDouble2x32;
3630 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003631
Rex Xu8ff43de2016-04-22 16:51:45 +08003632 case glslang::EOpPackInt2x32:
3633 case glslang::EOpUnpackInt2x32:
3634 case glslang::EOpPackUint2x32:
3635 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003636 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003637 break;
3638
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003639#ifdef AMD_EXTENSIONS
3640 case glslang::EOpPackFloat2x16:
3641 case glslang::EOpUnpackFloat2x16:
3642 unaryOp = spv::OpBitcast;
3643 break;
3644#endif
3645
John Kessenich140f3df2015-06-26 16:58:36 -06003646 case glslang::EOpDPdx:
3647 unaryOp = spv::OpDPdx;
3648 break;
3649 case glslang::EOpDPdy:
3650 unaryOp = spv::OpDPdy;
3651 break;
3652 case glslang::EOpFwidth:
3653 unaryOp = spv::OpFwidth;
3654 break;
3655 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003656 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003657 unaryOp = spv::OpDPdxFine;
3658 break;
3659 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003660 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003661 unaryOp = spv::OpDPdyFine;
3662 break;
3663 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003664 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003665 unaryOp = spv::OpFwidthFine;
3666 break;
3667 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003668 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003669 unaryOp = spv::OpDPdxCoarse;
3670 break;
3671 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003672 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003673 unaryOp = spv::OpDPdyCoarse;
3674 break;
3675 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003676 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003677 unaryOp = spv::OpFwidthCoarse;
3678 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003679 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003680 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003681 libCall = spv::GLSLstd450InterpolateAtCentroid;
3682 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003683 case glslang::EOpAny:
3684 unaryOp = spv::OpAny;
3685 break;
3686 case glslang::EOpAll:
3687 unaryOp = spv::OpAll;
3688 break;
3689
3690 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003691 if (isFloat)
3692 libCall = spv::GLSLstd450FAbs;
3693 else
3694 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003695 break;
3696 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003697 if (isFloat)
3698 libCall = spv::GLSLstd450FSign;
3699 else
3700 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702
John Kessenichfc51d282015-08-19 13:34:18 -06003703 case glslang::EOpAtomicCounterIncrement:
3704 case glslang::EOpAtomicCounterDecrement:
3705 case glslang::EOpAtomicCounter:
3706 {
3707 // Handle all of the atomics in one place, in createAtomicOperation()
3708 std::vector<spv::Id> operands;
3709 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003710 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003711 }
3712
John Kessenichfc51d282015-08-19 13:34:18 -06003713 case glslang::EOpBitFieldReverse:
3714 unaryOp = spv::OpBitReverse;
3715 break;
3716 case glslang::EOpBitCount:
3717 unaryOp = spv::OpBitCount;
3718 break;
3719 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003720 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003721 break;
3722 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003723 if (isUnsigned)
3724 libCall = spv::GLSLstd450FindUMsb;
3725 else
3726 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003727 break;
3728
Rex Xu574ab042016-04-14 16:53:07 +08003729 case glslang::EOpBallot:
3730 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003731 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003732 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003733 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003734#ifdef AMD_EXTENSIONS
3735 case glslang::EOpMinInvocations:
3736 case glslang::EOpMaxInvocations:
3737 case glslang::EOpAddInvocations:
3738 case glslang::EOpMinInvocationsNonUniform:
3739 case glslang::EOpMaxInvocationsNonUniform:
3740 case glslang::EOpAddInvocationsNonUniform:
3741#endif
Rex Xu51596642016-09-21 18:56:12 +08003742 {
3743 std::vector<spv::Id> operands;
3744 operands.push_back(operand);
3745 return createInvocationsOperation(op, typeId, operands, typeProxy);
3746 }
Rex Xu9d93a232016-05-05 12:30:44 +08003747
3748#ifdef AMD_EXTENSIONS
3749 case glslang::EOpMbcnt:
3750 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3751 libCall = spv::MbcntAMD;
3752 break;
3753
3754 case glslang::EOpCubeFaceIndex:
3755 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3756 libCall = spv::CubeFaceIndexAMD;
3757 break;
3758
3759 case glslang::EOpCubeFaceCoord:
3760 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3761 libCall = spv::CubeFaceCoordAMD;
3762 break;
3763#endif
Rex Xu338b1852016-05-05 20:38:33 +08003764
John Kessenich140f3df2015-06-26 16:58:36 -06003765 default:
3766 return 0;
3767 }
3768
3769 spv::Id id;
3770 if (libCall >= 0) {
3771 std::vector<spv::Id> args;
3772 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003773 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003774 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003775 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003776 }
John Kessenich140f3df2015-06-26 16:58:36 -06003777
qining25262b32016-05-06 17:25:16 -04003778 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003779 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003780}
3781
John Kessenich7a53f762016-01-20 11:19:27 -07003782// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003783spv::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 -07003784{
3785 // Handle unary operations vector by vector.
3786 // The result type is the same type as the original type.
3787 // The algorithm is to:
3788 // - break the matrix into vectors
3789 // - apply the operation to each vector
3790 // - make a matrix out the vector results
3791
3792 // get the types sorted out
3793 int numCols = builder.getNumColumns(operand);
3794 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003795 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3796 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003797 std::vector<spv::Id> results;
3798
3799 // do each vector op
3800 for (int c = 0; c < numCols; ++c) {
3801 std::vector<unsigned int> indexes;
3802 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003803 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3804 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3805 addDecoration(destVec, noContraction);
3806 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003807 }
3808
3809 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003810 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003811}
3812
Rex Xu73e3ce72016-04-27 18:48:17 +08003813spv::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 -06003814{
3815 spv::Op convOp = spv::OpNop;
3816 spv::Id zero = 0;
3817 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003818 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003819
3820 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3821
3822 switch (op) {
3823 case glslang::EOpConvIntToBool:
3824 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003825 case glslang::EOpConvInt64ToBool:
3826 case glslang::EOpConvUint64ToBool:
3827 zero = (op == glslang::EOpConvInt64ToBool ||
3828 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 zero = makeSmearedConstant(zero, vectorSize);
3830 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3831
3832 case glslang::EOpConvFloatToBool:
3833 zero = builder.makeFloatConstant(0.0F);
3834 zero = makeSmearedConstant(zero, vectorSize);
3835 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3836
3837 case glslang::EOpConvDoubleToBool:
3838 zero = builder.makeDoubleConstant(0.0);
3839 zero = makeSmearedConstant(zero, vectorSize);
3840 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3841
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003842#ifdef AMD_EXTENSIONS
3843 case glslang::EOpConvFloat16ToBool:
3844 zero = builder.makeFloat16Constant(0.0F);
3845 zero = makeSmearedConstant(zero, vectorSize);
3846 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3847#endif
3848
John Kessenich140f3df2015-06-26 16:58:36 -06003849 case glslang::EOpConvBoolToFloat:
3850 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003851 zero = builder.makeFloatConstant(0.0F);
3852 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06003853 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003854
John Kessenich140f3df2015-06-26 16:58:36 -06003855 case glslang::EOpConvBoolToDouble:
3856 convOp = spv::OpSelect;
3857 zero = builder.makeDoubleConstant(0.0);
3858 one = builder.makeDoubleConstant(1.0);
3859 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003860
3861#ifdef AMD_EXTENSIONS
3862 case glslang::EOpConvBoolToFloat16:
3863 convOp = spv::OpSelect;
3864 zero = builder.makeFloat16Constant(0.0F);
3865 one = builder.makeFloat16Constant(1.0F);
3866 break;
3867#endif
3868
John Kessenich140f3df2015-06-26 16:58:36 -06003869 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003870 case glslang::EOpConvBoolToInt64:
3871 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3872 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003873 convOp = spv::OpSelect;
3874 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003875
John Kessenich140f3df2015-06-26 16:58:36 -06003876 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003877 case glslang::EOpConvBoolToUint64:
3878 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3879 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003880 convOp = spv::OpSelect;
3881 break;
3882
3883 case glslang::EOpConvIntToFloat:
3884 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003885 case glslang::EOpConvInt64ToFloat:
3886 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003887#ifdef AMD_EXTENSIONS
3888 case glslang::EOpConvIntToFloat16:
3889 case glslang::EOpConvInt64ToFloat16:
3890#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003891 convOp = spv::OpConvertSToF;
3892 break;
3893
3894 case glslang::EOpConvUintToFloat:
3895 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003896 case glslang::EOpConvUint64ToFloat:
3897 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003898#ifdef AMD_EXTENSIONS
3899 case glslang::EOpConvUintToFloat16:
3900 case glslang::EOpConvUint64ToFloat16:
3901#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003902 convOp = spv::OpConvertUToF;
3903 break;
3904
3905 case glslang::EOpConvDoubleToFloat:
3906 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003907#ifdef AMD_EXTENSIONS
3908 case glslang::EOpConvDoubleToFloat16:
3909 case glslang::EOpConvFloat16ToDouble:
3910 case glslang::EOpConvFloatToFloat16:
3911 case glslang::EOpConvFloat16ToFloat:
3912#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003913 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08003914 if (builder.isMatrixType(destType))
3915 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06003916 break;
3917
3918 case glslang::EOpConvFloatToInt:
3919 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003920 case glslang::EOpConvFloatToInt64:
3921 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003922#ifdef AMD_EXTENSIONS
3923 case glslang::EOpConvFloat16ToInt:
3924 case glslang::EOpConvFloat16ToInt64:
3925#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003926 convOp = spv::OpConvertFToS;
3927 break;
3928
3929 case glslang::EOpConvUintToInt:
3930 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003931 case glslang::EOpConvUint64ToInt64:
3932 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003933 if (builder.isInSpecConstCodeGenMode()) {
3934 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08003935 zero = (op == glslang::EOpConvUint64ToInt64 ||
3936 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003937 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003938 // Use OpIAdd, instead of OpBitcast to do the conversion when
3939 // generating for OpSpecConstantOp instruction.
3940 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3941 }
3942 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003943 convOp = spv::OpBitcast;
3944 break;
3945
3946 case glslang::EOpConvFloatToUint:
3947 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003948 case glslang::EOpConvFloatToUint64:
3949 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003950#ifdef AMD_EXTENSIONS
3951 case glslang::EOpConvFloat16ToUint:
3952 case glslang::EOpConvFloat16ToUint64:
3953#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003954 convOp = spv::OpConvertFToU;
3955 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003956
3957 case glslang::EOpConvIntToInt64:
3958 case glslang::EOpConvInt64ToInt:
3959 convOp = spv::OpSConvert;
3960 break;
3961
3962 case glslang::EOpConvUintToUint64:
3963 case glslang::EOpConvUint64ToUint:
3964 convOp = spv::OpUConvert;
3965 break;
3966
3967 case glslang::EOpConvIntToUint64:
3968 case glslang::EOpConvInt64ToUint:
3969 case glslang::EOpConvUint64ToInt:
3970 case glslang::EOpConvUintToInt64:
3971 // OpSConvert/OpUConvert + OpBitCast
3972 switch (op) {
3973 case glslang::EOpConvIntToUint64:
3974 convOp = spv::OpSConvert;
3975 type = builder.makeIntType(64);
3976 break;
3977 case glslang::EOpConvInt64ToUint:
3978 convOp = spv::OpSConvert;
3979 type = builder.makeIntType(32);
3980 break;
3981 case glslang::EOpConvUint64ToInt:
3982 convOp = spv::OpUConvert;
3983 type = builder.makeUintType(32);
3984 break;
3985 case glslang::EOpConvUintToInt64:
3986 convOp = spv::OpUConvert;
3987 type = builder.makeUintType(64);
3988 break;
3989 default:
3990 assert(0);
3991 break;
3992 }
3993
3994 if (vectorSize > 0)
3995 type = builder.makeVectorType(type, vectorSize);
3996
3997 operand = builder.createUnaryOp(convOp, type, operand);
3998
3999 if (builder.isInSpecConstCodeGenMode()) {
4000 // Build zero scalar or vector for OpIAdd.
4001 zero = (op == glslang::EOpConvIntToUint64 ||
4002 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4003 zero = makeSmearedConstant(zero, vectorSize);
4004 // Use OpIAdd, instead of OpBitcast to do the conversion when
4005 // generating for OpSpecConstantOp instruction.
4006 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4007 }
4008 // For normal run-time conversion instruction, use OpBitcast.
4009 convOp = spv::OpBitcast;
4010 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004011 default:
4012 break;
4013 }
4014
4015 spv::Id result = 0;
4016 if (convOp == spv::OpNop)
4017 return result;
4018
4019 if (convOp == spv::OpSelect) {
4020 zero = makeSmearedConstant(zero, vectorSize);
4021 one = makeSmearedConstant(one, vectorSize);
4022 result = builder.createTriOp(convOp, destType, operand, one, zero);
4023 } else
4024 result = builder.createUnaryOp(convOp, destType, operand);
4025
John Kessenich32cfd492016-02-02 12:37:46 -07004026 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004027}
4028
4029spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4030{
4031 if (vectorSize == 0)
4032 return constant;
4033
4034 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4035 std::vector<spv::Id> components;
4036 for (int c = 0; c < vectorSize; ++c)
4037 components.push_back(constant);
4038 return builder.makeCompositeConstant(vectorTypeId, components);
4039}
4040
John Kessenich426394d2015-07-23 10:22:48 -06004041// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004042spv::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 -06004043{
4044 spv::Op opCode = spv::OpNop;
4045
4046 switch (op) {
4047 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004048 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004049 opCode = spv::OpAtomicIAdd;
4050 break;
4051 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004052 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004053 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004054 break;
4055 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004056 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004057 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004058 break;
4059 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004060 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004061 opCode = spv::OpAtomicAnd;
4062 break;
4063 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004064 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004065 opCode = spv::OpAtomicOr;
4066 break;
4067 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004068 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004069 opCode = spv::OpAtomicXor;
4070 break;
4071 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004072 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004073 opCode = spv::OpAtomicExchange;
4074 break;
4075 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004076 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004077 opCode = spv::OpAtomicCompareExchange;
4078 break;
4079 case glslang::EOpAtomicCounterIncrement:
4080 opCode = spv::OpAtomicIIncrement;
4081 break;
4082 case glslang::EOpAtomicCounterDecrement:
4083 opCode = spv::OpAtomicIDecrement;
4084 break;
4085 case glslang::EOpAtomicCounter:
4086 opCode = spv::OpAtomicLoad;
4087 break;
4088 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004089 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004090 break;
4091 }
4092
4093 // Sort out the operands
4094 // - mapping from glslang -> SPV
4095 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004096 // - compare-exchange swaps the value and comparator
4097 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004098 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4099 auto opIt = operands.begin(); // walk the glslang operands
4100 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004101 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4102 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4103 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004104 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4105 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004106 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004107 spvAtomicOperands.push_back(*(opIt + 1));
4108 spvAtomicOperands.push_back(*opIt);
4109 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004110 }
John Kessenich426394d2015-07-23 10:22:48 -06004111
John Kessenich3e60a6f2015-09-14 22:45:16 -06004112 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004113 for (; opIt != operands.end(); ++opIt)
4114 spvAtomicOperands.push_back(*opIt);
4115
4116 return builder.createOp(opCode, typeId, spvAtomicOperands);
4117}
4118
John Kessenich91cef522016-05-05 16:45:40 -06004119// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004120spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004121{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004122#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004123 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004124 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004125#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004126
Rex Xu51596642016-09-21 18:56:12 +08004127 spv::Op opCode = spv::OpNop;
John Kessenich91cef522016-05-05 16:45:40 -06004128
Rex Xu51596642016-09-21 18:56:12 +08004129 std::vector<spv::Id> spvGroupOperands;
4130 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation) {
4131 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4132 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
4133 } else {
4134 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004135#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004136 if (op == glslang::EOpMinInvocationsNonUniform ||
4137 op == glslang::EOpMaxInvocationsNonUniform ||
4138 op == glslang::EOpAddInvocationsNonUniform)
4139 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004140#endif
Rex Xu51596642016-09-21 18:56:12 +08004141
4142 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004143#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +08004144 if (op == glslang::EOpMinInvocations || op == glslang::EOpMaxInvocations || op == glslang::EOpAddInvocations ||
4145 op == glslang::EOpMinInvocationsNonUniform || op == glslang::EOpMaxInvocationsNonUniform || op == glslang::EOpAddInvocationsNonUniform)
4146 spvGroupOperands.push_back(spv::GroupOperationReduce);
Rex Xu9d93a232016-05-05 12:30:44 +08004147#endif
Rex Xu51596642016-09-21 18:56:12 +08004148 }
4149
4150 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4151 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004152
4153 switch (op) {
4154 case glslang::EOpAnyInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004155 opCode = spv::OpGroupAny;
4156 break;
John Kessenich91cef522016-05-05 16:45:40 -06004157 case glslang::EOpAllInvocations:
Rex Xu51596642016-09-21 18:56:12 +08004158 opCode = spv::OpGroupAll;
4159 break;
John Kessenich91cef522016-05-05 16:45:40 -06004160 case glslang::EOpAllInvocationsEqual:
4161 {
Rex Xu51596642016-09-21 18:56:12 +08004162 spv::Id groupAll = builder.createOp(spv::OpGroupAll, typeId, spvGroupOperands);
4163 spv::Id groupAny = builder.createOp(spv::OpGroupAny, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004164
4165 return builder.createBinOp(spv::OpLogicalOr, typeId, groupAll,
4166 builder.createUnaryOp(spv::OpLogicalNot, typeId, groupAny));
4167 }
Rex Xu51596642016-09-21 18:56:12 +08004168
4169 case glslang::EOpReadInvocation:
4170 opCode = spv::OpGroupBroadcast;
Rex Xub7072052016-09-26 15:53:40 +08004171 if (builder.isVectorType(typeId))
4172 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004173 break;
4174 case glslang::EOpReadFirstInvocation:
4175 opCode = spv::OpSubgroupFirstInvocationKHR;
4176 break;
4177 case glslang::EOpBallot:
4178 {
4179 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4180 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4181 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4182 //
4183 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4184 //
4185 spv::Id uintType = builder.makeUintType(32);
4186 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4187 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4188
4189 std::vector<spv::Id> components;
4190 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4191 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4192
4193 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4194 return builder.createUnaryOp(spv::OpBitcast, typeId,
4195 builder.createCompositeConstruct(uvec2Type, components));
4196 }
4197
Rex Xu9d93a232016-05-05 12:30:44 +08004198#ifdef AMD_EXTENSIONS
4199 case glslang::EOpMinInvocations:
4200 case glslang::EOpMaxInvocations:
4201 case glslang::EOpAddInvocations:
Rex Xu9d93a232016-05-05 12:30:44 +08004202 if (op == glslang::EOpMinInvocations) {
4203 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004204 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004205 else {
4206 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004207 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004208 else
Rex Xu51596642016-09-21 18:56:12 +08004209 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004210 }
4211 } else if (op == glslang::EOpMaxInvocations) {
4212 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004213 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004214 else {
4215 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004216 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004217 else
Rex Xu51596642016-09-21 18:56:12 +08004218 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004219 }
4220 } else {
4221 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004222 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004223 else
Rex Xu51596642016-09-21 18:56:12 +08004224 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004225 }
4226
Rex Xu2bbbe062016-08-23 15:41:05 +08004227 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004228 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004229
4230 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004231 case glslang::EOpMinInvocationsNonUniform:
4232 case glslang::EOpMaxInvocationsNonUniform:
4233 case glslang::EOpAddInvocationsNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004234 if (op == glslang::EOpMinInvocationsNonUniform) {
4235 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004236 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004237 else {
4238 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004239 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004240 else
Rex Xu51596642016-09-21 18:56:12 +08004241 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004242 }
4243 }
4244 else if (op == glslang::EOpMaxInvocationsNonUniform) {
4245 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004246 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004247 else {
4248 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004249 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004250 else
Rex Xu51596642016-09-21 18:56:12 +08004251 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004252 }
4253 }
4254 else {
4255 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004256 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004257 else
Rex Xu51596642016-09-21 18:56:12 +08004258 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004259 }
4260
Rex Xu2bbbe062016-08-23 15:41:05 +08004261 if (builder.isVectorType(typeId))
Rex Xub7072052016-09-26 15:53:40 +08004262 return CreateInvocationsVectorOperation(opCode, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004263
4264 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004265#endif
John Kessenich91cef522016-05-05 16:45:40 -06004266 default:
4267 logger->missingFunctionality("invocation operation");
4268 return spv::NoResult;
4269 }
Rex Xu51596642016-09-21 18:56:12 +08004270
4271 assert(opCode != spv::OpNop);
4272 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004273}
4274
Rex Xu2bbbe062016-08-23 15:41:05 +08004275// Create group invocation operations on a vector
Rex Xub7072052016-09-26 15:53:40 +08004276spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004277{
Rex Xub7072052016-09-26 15:53:40 +08004278#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004279 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4280 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004281 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004282 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4283 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4284 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004285#else
4286 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4287 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
4288 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast);
4289#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004290
4291 // Handle group invocation operations scalar by scalar.
4292 // The result type is the same type as the original type.
4293 // The algorithm is to:
4294 // - break the vector into scalars
4295 // - apply the operation to each scalar
4296 // - make a vector out the scalar results
4297
4298 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004299 int numComponents = builder.getNumComponents(operands[0]);
4300 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004301 std::vector<spv::Id> results;
4302
4303 // do each scalar op
4304 for (int comp = 0; comp < numComponents; ++comp) {
4305 std::vector<unsigned int> indexes;
4306 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004307 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xu2bbbe062016-08-23 15:41:05 +08004308
Rex Xub7072052016-09-26 15:53:40 +08004309 std::vector<spv::Id> spvGroupOperands;
4310 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
4311 if (op == spv::OpGroupBroadcast) {
4312 spvGroupOperands.push_back(scalar);
4313 spvGroupOperands.push_back(operands[1]);
4314 } else {
4315 spvGroupOperands.push_back(spv::GroupOperationReduce);
4316 spvGroupOperands.push_back(scalar);
4317 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004318
Rex Xub7072052016-09-26 15:53:40 +08004319 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004320 }
4321
4322 // put the pieces together
4323 return builder.createCompositeConstruct(typeId, results);
4324}
Rex Xu2bbbe062016-08-23 15:41:05 +08004325
John Kessenich5e4b1242015-08-06 22:53:06 -06004326spv::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 -06004327{
Rex Xu8ff43de2016-04-22 16:51:45 +08004328 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004329#ifdef AMD_EXTENSIONS
4330 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4331#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004332 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004333#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004334
John Kessenich140f3df2015-06-26 16:58:36 -06004335 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004336 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004337 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004338 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004339 spv::Id typeId0 = 0;
4340 if (consumedOperands > 0)
4341 typeId0 = builder.getTypeId(operands[0]);
4342 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004343
4344 switch (op) {
4345 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004346 if (isFloat)
4347 libCall = spv::GLSLstd450FMin;
4348 else if (isUnsigned)
4349 libCall = spv::GLSLstd450UMin;
4350 else
4351 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004352 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004353 break;
4354 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004355 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004356 break;
4357 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004358 if (isFloat)
4359 libCall = spv::GLSLstd450FMax;
4360 else if (isUnsigned)
4361 libCall = spv::GLSLstd450UMax;
4362 else
4363 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004364 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004365 break;
4366 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004367 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004368 break;
4369 case glslang::EOpDot:
4370 opCode = spv::OpDot;
4371 break;
4372 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004373 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004374 break;
4375
4376 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004377 if (isFloat)
4378 libCall = spv::GLSLstd450FClamp;
4379 else if (isUnsigned)
4380 libCall = spv::GLSLstd450UClamp;
4381 else
4382 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004383 builder.promoteScalar(precision, operands.front(), operands[1]);
4384 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004385 break;
4386 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004387 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4388 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004389 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004390 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004391 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004392 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004393 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004394 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004395 break;
4396 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004397 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004398 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004399 break;
4400 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004401 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004402 builder.promoteScalar(precision, operands[0], operands[2]);
4403 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004404 break;
4405
4406 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004407 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004408 break;
4409 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004410 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004411 break;
4412 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004413 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004414 break;
4415 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004416 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004417 break;
4418 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004419 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004420 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004421 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004422 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004423 libCall = spv::GLSLstd450InterpolateAtSample;
4424 break;
4425 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004426 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004427 libCall = spv::GLSLstd450InterpolateAtOffset;
4428 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004429 case glslang::EOpAddCarry:
4430 opCode = spv::OpIAddCarry;
4431 typeId = builder.makeStructResultType(typeId0, typeId0);
4432 consumedOperands = 2;
4433 break;
4434 case glslang::EOpSubBorrow:
4435 opCode = spv::OpISubBorrow;
4436 typeId = builder.makeStructResultType(typeId0, typeId0);
4437 consumedOperands = 2;
4438 break;
4439 case glslang::EOpUMulExtended:
4440 opCode = spv::OpUMulExtended;
4441 typeId = builder.makeStructResultType(typeId0, typeId0);
4442 consumedOperands = 2;
4443 break;
4444 case glslang::EOpIMulExtended:
4445 opCode = spv::OpSMulExtended;
4446 typeId = builder.makeStructResultType(typeId0, typeId0);
4447 consumedOperands = 2;
4448 break;
4449 case glslang::EOpBitfieldExtract:
4450 if (isUnsigned)
4451 opCode = spv::OpBitFieldUExtract;
4452 else
4453 opCode = spv::OpBitFieldSExtract;
4454 break;
4455 case glslang::EOpBitfieldInsert:
4456 opCode = spv::OpBitFieldInsert;
4457 break;
4458
4459 case glslang::EOpFma:
4460 libCall = spv::GLSLstd450Fma;
4461 break;
4462 case glslang::EOpFrexp:
4463 libCall = spv::GLSLstd450FrexpStruct;
4464 if (builder.getNumComponents(operands[0]) == 1)
4465 frexpIntType = builder.makeIntegerType(32, true);
4466 else
4467 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4468 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4469 consumedOperands = 1;
4470 break;
4471 case glslang::EOpLdexp:
4472 libCall = spv::GLSLstd450Ldexp;
4473 break;
4474
Rex Xu574ab042016-04-14 16:53:07 +08004475 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004476 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004477
Rex Xu9d93a232016-05-05 12:30:44 +08004478#ifdef AMD_EXTENSIONS
4479 case glslang::EOpSwizzleInvocations:
4480 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4481 libCall = spv::SwizzleInvocationsAMD;
4482 break;
4483 case glslang::EOpSwizzleInvocationsMasked:
4484 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4485 libCall = spv::SwizzleInvocationsMaskedAMD;
4486 break;
4487 case glslang::EOpWriteInvocation:
4488 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4489 libCall = spv::WriteInvocationAMD;
4490 break;
4491
4492 case glslang::EOpMin3:
4493 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4494 if (isFloat)
4495 libCall = spv::FMin3AMD;
4496 else {
4497 if (isUnsigned)
4498 libCall = spv::UMin3AMD;
4499 else
4500 libCall = spv::SMin3AMD;
4501 }
4502 break;
4503 case glslang::EOpMax3:
4504 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4505 if (isFloat)
4506 libCall = spv::FMax3AMD;
4507 else {
4508 if (isUnsigned)
4509 libCall = spv::UMax3AMD;
4510 else
4511 libCall = spv::SMax3AMD;
4512 }
4513 break;
4514 case glslang::EOpMid3:
4515 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4516 if (isFloat)
4517 libCall = spv::FMid3AMD;
4518 else {
4519 if (isUnsigned)
4520 libCall = spv::UMid3AMD;
4521 else
4522 libCall = spv::SMid3AMD;
4523 }
4524 break;
4525
4526 case glslang::EOpInterpolateAtVertex:
4527 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4528 libCall = spv::InterpolateAtVertexAMD;
4529 break;
4530#endif
4531
John Kessenich140f3df2015-06-26 16:58:36 -06004532 default:
4533 return 0;
4534 }
4535
4536 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004537 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004538 // Use an extended instruction from the standard library.
4539 // Construct the call arguments, without modifying the original operands vector.
4540 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4541 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004542 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004543 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004544 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004545 case 0:
4546 // should all be handled by visitAggregate and createNoArgOperation
4547 assert(0);
4548 return 0;
4549 case 1:
4550 // should all be handled by createUnaryOperation
4551 assert(0);
4552 return 0;
4553 case 2:
4554 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4555 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004556 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004557 // anything 3 or over doesn't have l-value operands, so all should be consumed
4558 assert(consumedOperands == operands.size());
4559 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004560 break;
4561 }
4562 }
4563
John Kessenich55e7d112015-11-15 21:33:39 -07004564 // Decode the return types that were structures
4565 switch (op) {
4566 case glslang::EOpAddCarry:
4567 case glslang::EOpSubBorrow:
4568 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4569 id = builder.createCompositeExtract(id, typeId0, 0);
4570 break;
4571 case glslang::EOpUMulExtended:
4572 case glslang::EOpIMulExtended:
4573 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4574 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4575 break;
4576 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004577 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004578 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4579 id = builder.createCompositeExtract(id, typeId0, 0);
4580 break;
4581 default:
4582 break;
4583 }
4584
John Kessenich32cfd492016-02-02 12:37:46 -07004585 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004586}
4587
Rex Xu9d93a232016-05-05 12:30:44 +08004588// Intrinsics with no arguments (or no return value, and no precision).
4589spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004590{
4591 // TODO: get the barrier operands correct
4592
4593 switch (op) {
4594 case glslang::EOpEmitVertex:
4595 builder.createNoResultOp(spv::OpEmitVertex);
4596 return 0;
4597 case glslang::EOpEndPrimitive:
4598 builder.createNoResultOp(spv::OpEndPrimitive);
4599 return 0;
4600 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004601 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004602 return 0;
4603 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004604 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004605 return 0;
4606 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004607 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004608 return 0;
4609 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004610 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004611 return 0;
4612 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004613 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004614 return 0;
4615 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004616 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004617 return 0;
4618 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004619 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004620 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004621 case glslang::EOpAllMemoryBarrierWithGroupSync:
4622 // Control barrier with non-"None" semantic is also a memory barrier.
4623 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4624 return 0;
4625 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4626 // Control barrier with non-"None" semantic is also a memory barrier.
4627 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4628 return 0;
4629 case glslang::EOpWorkgroupMemoryBarrier:
4630 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4631 return 0;
4632 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4633 // Control barrier with non-"None" semantic is also a memory barrier.
4634 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4635 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004636#ifdef AMD_EXTENSIONS
4637 case glslang::EOpTime:
4638 {
4639 std::vector<spv::Id> args; // Dummy arguments
4640 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4641 return builder.setPrecision(id, precision);
4642 }
4643#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004644 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004645 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004646 return 0;
4647 }
4648}
4649
4650spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4651{
John Kessenich2f273362015-07-18 22:34:27 -06004652 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004653 spv::Id id;
4654 if (symbolValues.end() != iter) {
4655 id = iter->second;
4656 return id;
4657 }
4658
4659 // it was not found, create it
4660 id = createSpvVariable(symbol);
4661 symbolValues[symbol->getId()] = id;
4662
Rex Xuc884b4a2016-06-29 15:03:44 +08004663 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004664 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004665 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004666 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004667 if (symbol->getType().getQualifier().hasSpecConstantId())
4668 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004669 if (symbol->getQualifier().hasIndex())
4670 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4671 if (symbol->getQualifier().hasComponent())
4672 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4673 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004674 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004675 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004676 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004677 if (symbol->getQualifier().hasXfbBuffer())
4678 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4679 if (symbol->getQualifier().hasXfbOffset())
4680 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4681 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004682 // atomic counters use this:
4683 if (symbol->getQualifier().hasOffset())
4684 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004685 }
4686
scygan2c864272016-05-18 18:09:17 +02004687 if (symbol->getQualifier().hasLocation())
4688 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004689 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004690 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004691 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004692 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004693 }
John Kessenich140f3df2015-06-26 16:58:36 -06004694 if (symbol->getQualifier().hasSet())
4695 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004696 else if (IsDescriptorResource(symbol->getType())) {
4697 // default to 0
4698 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4699 }
John Kessenich140f3df2015-06-26 16:58:36 -06004700 if (symbol->getQualifier().hasBinding())
4701 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004702 if (symbol->getQualifier().hasAttachment())
4703 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004704 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004705 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004706 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004707 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004708 if (symbol->getQualifier().hasXfbBuffer())
4709 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4710 }
4711
Rex Xu1da878f2016-02-21 20:59:01 +08004712 if (symbol->getType().isImage()) {
4713 std::vector<spv::Decoration> memory;
4714 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4715 for (unsigned int i = 0; i < memory.size(); ++i)
4716 addDecoration(id, memory[i]);
4717 }
4718
John Kessenich140f3df2015-06-26 16:58:36 -06004719 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004720 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004721 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004722 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004723
John Kessenich140f3df2015-06-26 16:58:36 -06004724 return id;
4725}
4726
John Kessenich55e7d112015-11-15 21:33:39 -07004727// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004728void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4729{
John Kessenich4016e382016-07-15 11:53:56 -06004730 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004731 builder.addDecoration(id, dec);
4732}
4733
John Kessenich55e7d112015-11-15 21:33:39 -07004734// If 'dec' is valid, add a one-operand decoration to an object
4735void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4736{
John Kessenich4016e382016-07-15 11:53:56 -06004737 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004738 builder.addDecoration(id, dec, value);
4739}
4740
4741// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004742void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4743{
John Kessenich4016e382016-07-15 11:53:56 -06004744 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004745 builder.addMemberDecoration(id, (unsigned)member, dec);
4746}
4747
John Kessenich92187592016-02-01 13:45:25 -07004748// If 'dec' is valid, add a one-operand decoration to a struct member
4749void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
4750{
John Kessenich4016e382016-07-15 11:53:56 -06004751 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07004752 builder.addMemberDecoration(id, (unsigned)member, dec, value);
4753}
4754
John Kessenich55e7d112015-11-15 21:33:39 -07004755// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07004756// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07004757//
4758// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
4759//
4760// Recursively walk the nodes. The nodes form a tree whose leaves are
4761// regular constants, which themselves are trees that createSpvConstant()
4762// recursively walks. So, this function walks the "top" of the tree:
4763// - emit specialization constant-building instructions for specConstant
4764// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04004765spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07004766{
John Kessenich7cc0e282016-03-20 00:46:02 -06004767 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07004768
qining4f4bb812016-04-03 23:55:17 -04004769 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07004770 if (! node.getQualifier().specConstant) {
4771 // hand off to the non-spec-constant path
4772 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
4773 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04004774 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07004775 nextConst, false);
4776 }
4777
4778 // We now know we have a specialization constant to build
4779
John Kessenichd94c0032016-05-30 19:29:40 -06004780 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04004781 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
4782 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
4783 std::vector<spv::Id> dimConstId;
4784 for (int dim = 0; dim < 3; ++dim) {
4785 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
4786 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
4787 if (specConst)
4788 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
4789 }
4790 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
4791 }
4792
4793 // An AST node labelled as specialization constant should be a symbol node.
4794 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
4795 if (auto* sn = node.getAsSymbolNode()) {
4796 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04004797 // Traverse the constant constructor sub tree like generating normal run-time instructions.
4798 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
4799 // will set the builder into spec constant op instruction generating mode.
4800 sub_tree->traverse(this);
4801 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04004802 } else if (auto* const_union_array = &sn->getConstArray()){
4803 int nextConst = 0;
4804 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07004805 }
4806 }
qining4f4bb812016-04-03 23:55:17 -04004807
4808 // Neither a front-end constant node, nor a specialization constant node with constant union array or
4809 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04004810 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04004811 exit(1);
4812 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07004813}
4814
John Kessenich140f3df2015-06-26 16:58:36 -06004815// Use 'consts' as the flattened glslang source of scalar constants to recursively
4816// build the aggregate SPIR-V constant.
4817//
4818// If there are not enough elements present in 'consts', 0 will be substituted;
4819// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
4820//
qining08408382016-03-21 09:51:37 -04004821spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06004822{
4823 // vector of constants for SPIR-V
4824 std::vector<spv::Id> spvConsts;
4825
4826 // Type is used for struct and array constants
4827 spv::Id typeId = convertGlslangToSpvType(glslangType);
4828
4829 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004830 glslang::TType elementType(glslangType, 0);
4831 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04004832 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004833 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06004834 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06004835 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04004836 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06004837 } else if (glslangType.getStruct()) {
4838 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
4839 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04004840 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06004841 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06004842 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
4843 bool zero = nextConst >= consts.size();
4844 switch (glslangType.getBasicType()) {
4845 case glslang::EbtInt:
4846 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
4847 break;
4848 case glslang::EbtUint:
4849 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
4850 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004851 case glslang::EbtInt64:
4852 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
4853 break;
4854 case glslang::EbtUint64:
4855 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
4856 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004857 case glslang::EbtFloat:
4858 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4859 break;
4860 case glslang::EbtDouble:
4861 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
4862 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004863#ifdef AMD_EXTENSIONS
4864 case glslang::EbtFloat16:
4865 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
4866 break;
4867#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004868 case glslang::EbtBool:
4869 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
4870 break;
4871 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004872 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004873 break;
4874 }
4875 ++nextConst;
4876 }
4877 } else {
4878 // we have a non-aggregate (scalar) constant
4879 bool zero = nextConst >= consts.size();
4880 spv::Id scalar = 0;
4881 switch (glslangType.getBasicType()) {
4882 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004883 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004884 break;
4885 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004886 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004887 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004888 case glslang::EbtInt64:
4889 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4890 break;
4891 case glslang::EbtUint64:
4892 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4893 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004894 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004895 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004896 break;
4897 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004898 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004899 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004900#ifdef AMD_EXTENSIONS
4901 case glslang::EbtFloat16:
4902 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
4903 break;
4904#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004905 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004906 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004907 break;
4908 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004909 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004910 break;
4911 }
4912 ++nextConst;
4913 return scalar;
4914 }
4915
4916 return builder.makeCompositeConstant(typeId, spvConsts);
4917}
4918
John Kessenich7c1aa102015-10-15 13:29:11 -06004919// Return true if the node is a constant or symbol whose reading has no
4920// non-trivial observable cost or effect.
4921bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4922{
4923 // don't know what this is
4924 if (node == nullptr)
4925 return false;
4926
4927 // a constant is safe
4928 if (node->getAsConstantUnion() != nullptr)
4929 return true;
4930
4931 // not a symbol means non-trivial
4932 if (node->getAsSymbolNode() == nullptr)
4933 return false;
4934
4935 // a symbol, depends on what's being read
4936 switch (node->getType().getQualifier().storage) {
4937 case glslang::EvqTemporary:
4938 case glslang::EvqGlobal:
4939 case glslang::EvqIn:
4940 case glslang::EvqInOut:
4941 case glslang::EvqConst:
4942 case glslang::EvqConstReadOnly:
4943 case glslang::EvqUniform:
4944 return true;
4945 default:
4946 return false;
4947 }
qining25262b32016-05-06 17:25:16 -04004948}
John Kessenich7c1aa102015-10-15 13:29:11 -06004949
4950// A node is trivial if it is a single operation with no side effects.
4951// Error on the side of saying non-trivial.
4952// Return true if trivial.
4953bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4954{
4955 if (node == nullptr)
4956 return false;
4957
4958 // symbols and constants are trivial
4959 if (isTrivialLeaf(node))
4960 return true;
4961
4962 // otherwise, it needs to be a simple operation or one or two leaf nodes
4963
4964 // not a simple operation
4965 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4966 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4967 if (binaryNode == nullptr && unaryNode == nullptr)
4968 return false;
4969
4970 // not on leaf nodes
4971 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4972 return false;
4973
4974 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4975 return false;
4976 }
4977
4978 switch (node->getAsOperator()->getOp()) {
4979 case glslang::EOpLogicalNot:
4980 case glslang::EOpConvIntToBool:
4981 case glslang::EOpConvUintToBool:
4982 case glslang::EOpConvFloatToBool:
4983 case glslang::EOpConvDoubleToBool:
4984 case glslang::EOpEqual:
4985 case glslang::EOpNotEqual:
4986 case glslang::EOpLessThan:
4987 case glslang::EOpGreaterThan:
4988 case glslang::EOpLessThanEqual:
4989 case glslang::EOpGreaterThanEqual:
4990 case glslang::EOpIndexDirect:
4991 case glslang::EOpIndexDirectStruct:
4992 case glslang::EOpLogicalXor:
4993 case glslang::EOpAny:
4994 case glslang::EOpAll:
4995 return true;
4996 default:
4997 return false;
4998 }
4999}
5000
5001// Emit short-circuiting code, where 'right' is never evaluated unless
5002// the left side is true (for &&) or false (for ||).
5003spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5004{
5005 spv::Id boolTypeId = builder.makeBoolType();
5006
5007 // emit left operand
5008 builder.clearAccessChain();
5009 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005010 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005011
5012 // Operands to accumulate OpPhi operands
5013 std::vector<spv::Id> phiOperands;
5014 // accumulate left operand's phi information
5015 phiOperands.push_back(leftId);
5016 phiOperands.push_back(builder.getBuildPoint()->getId());
5017
5018 // Make the two kinds of operation symmetric with a "!"
5019 // || => emit "if (! left) result = right"
5020 // && => emit "if ( left) result = right"
5021 //
5022 // TODO: this runtime "not" for || could be avoided by adding functionality
5023 // to 'builder' to have an "else" without an "then"
5024 if (op == glslang::EOpLogicalOr)
5025 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5026
5027 // make an "if" based on the left value
5028 spv::Builder::If ifBuilder(leftId, builder);
5029
5030 // emit right operand as the "then" part of the "if"
5031 builder.clearAccessChain();
5032 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005033 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005034
5035 // accumulate left operand's phi information
5036 phiOperands.push_back(rightId);
5037 phiOperands.push_back(builder.getBuildPoint()->getId());
5038
5039 // finish the "if"
5040 ifBuilder.makeEndIf();
5041
5042 // phi together the two results
5043 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5044}
5045
Rex Xu9d93a232016-05-05 12:30:44 +08005046// Return type Id of the imported set of extended instructions corresponds to the name.
5047// Import this set if it has not been imported yet.
5048spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5049{
5050 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5051 return extBuiltinMap[name];
5052 else {
Rex Xu51596642016-09-21 18:56:12 +08005053 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005054 spv::Id extBuiltins = builder.import(name);
5055 extBuiltinMap[name] = extBuiltins;
5056 return extBuiltins;
5057 }
5058}
5059
John Kessenich140f3df2015-06-26 16:58:36 -06005060}; // end anonymous namespace
5061
5062namespace glslang {
5063
John Kessenich68d78fd2015-07-12 19:28:10 -06005064void GetSpirvVersion(std::string& version)
5065{
John Kessenich9e55f632015-07-15 10:03:39 -06005066 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005067 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005068 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005069 version = buf;
5070}
5071
John Kessenich140f3df2015-06-26 16:58:36 -06005072// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005073void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005074{
5075 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005076 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06005077 for (int i = 0; i < (int)spirv.size(); ++i) {
5078 unsigned int word = spirv[i];
5079 out.write((const char*)&word, 4);
5080 }
5081 out.close();
5082}
5083
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005084// Write SPIR-V out to a text file with 32-bit hexadecimal words
5085void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName)
5086{
5087 std::ofstream out;
5088 out.open(baseName, std::ios::binary | std::ios::out);
5089 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
5090 const int WORDS_PER_LINE = 8;
5091 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5092 out << "\t";
5093 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5094 const unsigned int word = spirv[i + j];
5095 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5096 if (i + j + 1 < (int)spirv.size()) {
5097 out << ",";
5098 }
5099 }
5100 out << std::endl;
5101 }
5102 out.close();
5103}
5104
John Kessenich140f3df2015-06-26 16:58:36 -06005105//
5106// Set up the glslang traversal
5107//
5108void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5109{
Lei Zhang17535f72016-05-04 15:55:59 -04005110 spv::SpvBuildLogger logger;
5111 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005112}
5113
Lei Zhang17535f72016-05-04 15:55:59 -04005114void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005115{
John Kessenich140f3df2015-06-26 16:58:36 -06005116 TIntermNode* root = intermediate.getTreeRoot();
5117
5118 if (root == 0)
5119 return;
5120
5121 glslang::GetThreadPoolAllocator().push();
5122
Lei Zhang17535f72016-05-04 15:55:59 -04005123 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005124 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005125 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005126 it.dumpSpv(spirv);
5127
5128 glslang::GetThreadPoolAllocator().pop();
5129}
5130
5131}; // end namespace glslang