blob: 276899c4de8bdff97d78aa68aad3168e0e875b32 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
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//
John Kessenich927608b2017-01-06 12:34:14 -070023// 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.
John Kessenich140f3df2015-06-26 16:58:36 -060035
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
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600132 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
133 glslang::TLayoutPacking, const glslang::TQualifier&);
134 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
135 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700136 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700137 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800138 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600139 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700140 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700141 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
142 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 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 +0100144 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600145
John Kessenich6fccb3c2016-09-19 16:01:41 -0600146 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 void makeFunctions(const glslang::TIntermSequence&);
148 void makeGlobalInitializers(const glslang::TIntermSequence&);
149 void visitFunctions(const glslang::TIntermSequence&);
150 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800151 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600152 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
153 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
155
qining25262b32016-05-06 17:25:16 -0400156 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);
157 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
158 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 +0800159 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 +0800160 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 -0600161 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800162 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 +0800163 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800164 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600165 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 +0800166 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
168 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700169 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400172 spv::Id createSpvConstant(const glslang::TIntermTyped&);
173 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600174 bool isTrivialLeaf(const glslang::TIntermTyped* node);
175 bool isTrivial(const glslang::TIntermTyped* node);
176 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800177 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600178
179 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600180 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700181 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600182 int sequenceDepth;
183
Lei Zhang17535f72016-05-04 15:55:59 -0400184 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400185
John Kessenich140f3df2015-06-26 16:58:36 -0600186 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
187 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700188 bool inEntryPoint;
189 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700190 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 -0700191 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600192 const glslang::TIntermediate* glslangIntermediate;
193 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800194 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600195
John Kessenich2f273362015-07-18 22:34:27 -0600196 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600197 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600198 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700199 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600200 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 -0600201 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600202};
203
204//
205// Helper functions for translating glslang representations to SPIR-V enumerants.
206//
207
208// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700209spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600210{
John Kessenich66e2faf2016-03-12 18:34:36 -0700211 switch (source) {
212 case glslang::EShSourceGlsl:
213 switch (profile) {
214 case ENoProfile:
215 case ECoreProfile:
216 case ECompatibilityProfile:
217 return spv::SourceLanguageGLSL;
218 case EEsProfile:
219 return spv::SourceLanguageESSL;
220 default:
221 return spv::SourceLanguageUnknown;
222 }
223 case glslang::EShSourceHlsl:
John Kessenich927608b2017-01-06 12:34:14 -0700224 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400225 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
248spv::StorageClass TranslateStorageClass(const glslang::TType& type)
249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtAtomicUint)
255 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700256 else if (type.containsOpaque())
257 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700259 if (type.getQualifier().layoutPushConstant)
260 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 if (type.getBasicType() == glslang::EbtBlock)
262 return spv::StorageClassUniform;
263 else
264 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 } else {
266 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
268 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
270 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400271 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600273 return spv::StorageClassFunction;
274 }
275 }
276}
277
278// Translate glslang sampler type to SPIR-V dimensionality.
279spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
280{
281 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700282 case glslang::Esd1D: return spv::Dim1D;
283 case glslang::Esd2D: return spv::Dim2D;
284 case glslang::Esd3D: return spv::Dim3D;
285 case glslang::EsdCube: return spv::DimCube;
286 case glslang::EsdRect: return spv::DimRect;
287 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700288 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::Dim2D;
292 }
293}
294
John Kessenichf6640762016-08-01 19:44:00 -0600295// Translate glslang precision to SPIR-V precision decorations.
296spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
John Kessenichf6640762016-08-01 19:44:00 -0600298 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700299 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600300 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600301 default:
302 return spv::NoPrecision;
303 }
304}
305
John Kessenichf6640762016-08-01 19:44:00 -0600306// Translate glslang type to SPIR-V precision decorations.
307spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
308{
309 return TranslatePrecisionDecoration(type.getQualifier().precision);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V block decorations.
313spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
314{
315 if (type.getBasicType() == glslang::EbtBlock) {
316 switch (type.getQualifier().storage) {
317 case glslang::EvqUniform: return spv::DecorationBlock;
318 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
319 case glslang::EvqVaryingIn: return spv::DecorationBlock;
320 case glslang::EvqVaryingOut: return spv::DecorationBlock;
321 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700322 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600323 break;
324 }
325 }
326
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328}
329
Rex Xu1da878f2016-02-21 20:59:01 +0800330// Translate glslang type to SPIR-V memory decorations.
331void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
332{
333 if (qualifier.coherent)
334 memory.push_back(spv::DecorationCoherent);
335 if (qualifier.volatil)
336 memory.push_back(spv::DecorationVolatile);
337 if (qualifier.restrict)
338 memory.push_back(spv::DecorationRestrict);
339 if (qualifier.readonly)
340 memory.push_back(spv::DecorationNonWritable);
341 if (qualifier.writeonly)
342 memory.push_back(spv::DecorationNonReadable);
343}
344
John Kessenich140f3df2015-06-26 16:58:36 -0600345// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700346spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600347{
348 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElmRowMajor:
351 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 default:
355 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 } else {
359 switch (type.getBasicType()) {
360 default:
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 break;
363 case glslang::EbtBlock:
364 switch (type.getQualifier().storage) {
365 case glslang::EvqUniform:
366 case glslang::EvqBuffer:
367 switch (type.getQualifier().layoutPacking) {
368 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 }
373 case glslang::EvqVaryingIn:
374 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700378 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 }
381 }
382 }
383}
384
385// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600386// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700387// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800388spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600389{
Rex Xubbceed72016-05-21 09:40:44 +0800390 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800393 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700394 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800397#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800398 else if (qualifier.explicitInterp) {
399 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800400 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800401 }
Rex Xu9d93a232016-05-05 12:30:44 +0800402#endif
Rex Xubbceed72016-05-21 09:40:44 +0800403 else
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800405}
406
407// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600408// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800409// should be applied.
410spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
411{
412 if (qualifier.patch)
413 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700414 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700416 else if (qualifier.sample) {
417 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700419 } else
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421}
422
John Kessenich92187592016-02-01 13:45:25 -0700423// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600425{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700426 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationInvariant;
428 else
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430}
431
qining9220dbb2016-05-04 17:34:38 -0400432// If glslang type is noContraction, return SPIR-V NoContraction decoration.
433spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
434{
435 if (qualifier.noContraction)
436 return spv::DecorationNoContraction;
437 else
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400439}
440
David Netoa901ffe2016-06-08 14:11:40 +0100441// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
442// associated capabilities when required. For some built-in variables, a capability
443// is generated only when using the variable in an executable instruction, but not when
444// just declaring a struct member variable with it. This is true for PointSize,
445// ClipDistance, and CullDistance.
446spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600447{
448 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700449 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600450 // Defer adding the capability until the built-in is actually used.
451 if (! memberDeclaration) {
452 switch (glslangIntermediate->getStage()) {
453 case EShLangGeometry:
454 builder.addCapability(spv::CapabilityGeometryPointSize);
455 break;
456 case EShLangTessControl:
457 case EShLangTessEvaluation:
458 builder.addCapability(spv::CapabilityTessellationPointSize);
459 break;
460 default:
461 break;
462 }
John Kessenich92187592016-02-01 13:45:25 -0700463 }
464 return spv::BuiltInPointSize;
465
John Kessenichebb50532016-05-16 19:22:05 -0600466 // These *Distance capabilities logically belong here, but if the member is declared and
467 // then never used, consumers of SPIR-V prefer the capability not be declared.
468 // They are now generated when used, rather than here when declared.
469 // Potentially, the specification should be more clear what the minimum
470 // use needed is to trigger the capability.
471 //
John Kessenich92187592016-02-01 13:45:25 -0700472 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800474 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInClipDistance;
476
477 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100478 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800479 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700480 return spv::BuiltInCullDistance;
481
482 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500483 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800484#ifdef NV_EXTENSIONS
485 if (glslangIntermediate->getStage() == EShLangVertex ||
486 glslangIntermediate->getStage() == EShLangTessControl ||
487 glslangIntermediate->getStage() == EShLangTessEvaluation)
488 {
489 builder.addExtension(spv::E_SPV_NV_viewport_array2);
490 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
491 }
492#endif
John Kessenich92187592016-02-01 13:45:25 -0700493 return spv::BuiltInViewportIndex;
494
John Kessenich5e801132016-02-15 11:09:46 -0700495 case glslang::EbvSampleId:
496 builder.addCapability(spv::CapabilitySampleRateShading);
497 return spv::BuiltInSampleId;
498
499 case glslang::EbvSamplePosition:
500 builder.addCapability(spv::CapabilitySampleRateShading);
501 return spv::BuiltInSamplePosition;
502
503 case glslang::EbvSampleMask:
504 builder.addCapability(spv::CapabilitySampleRateShading);
505 return spv::BuiltInSampleMask;
506
John Kessenich78a45572016-07-08 14:05:15 -0600507 case glslang::EbvLayer:
508 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800509#ifdef NV_EXTENSIONS
510 if (!memberDeclaration)
511 {
512 if (glslangIntermediate->getStage() == EShLangVertex ||
513 glslangIntermediate->getStage() == EShLangTessControl ||
514 glslangIntermediate->getStage() == EShLangTessEvaluation)
515 {
516 builder.addExtension(spv::E_SPV_NV_viewport_array2);
517 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
518 }
519 }
520#endif
John Kessenich78a45572016-07-08 14:05:15 -0600521 return spv::BuiltInLayer;
522
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvVertexId: return spv::BuiltInVertexId;
525 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700526 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
527 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800528
John Kessenichda581a22015-10-14 14:10:30 -0600529 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800530 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
531 builder.addCapability(spv::CapabilityDrawParameters);
532 return spv::BuiltInBaseVertex;
533
John Kessenichda581a22015-10-14 14:10:30 -0600534 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800535 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
536 builder.addCapability(spv::CapabilityDrawParameters);
537 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200538
John Kessenichda581a22015-10-14 14:10:30 -0600539 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
541 builder.addCapability(spv::CapabilityDrawParameters);
542 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200543
544 case glslang::EbvPrimitiveId:
545 if (glslangIntermediate->getStage() == EShLangFragment)
546 builder.addCapability(spv::CapabilityGeometry);
547 return spv::BuiltInPrimitiveId;
548
John Kessenich140f3df2015-06-26 16:58:36 -0600549 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600550 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
551 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
552 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
553 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
554 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
555 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
556 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600557 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
558 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
559 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
560 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
561 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
562 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
563 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
564 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupSize;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLocalInvocationId;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupEqMaskKHR;
580
Rex Xu574ab042016-04-14 16:53:07 +0800581 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800582 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
583 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
584 return spv::BuiltInSubgroupGeMaskKHR;
585
Rex Xu574ab042016-04-14 16:53:07 +0800586 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800587 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
588 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
589 return spv::BuiltInSubgroupGtMaskKHR;
590
Rex Xu574ab042016-04-14 16:53:07 +0800591 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800592 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
593 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
594 return spv::BuiltInSubgroupLeMaskKHR;
595
Rex Xu574ab042016-04-14 16:53:07 +0800596 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800597 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
598 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
599 return spv::BuiltInSubgroupLtMaskKHR;
600
Rex Xu9d93a232016-05-05 12:30:44 +0800601#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800602 case glslang::EbvBaryCoordNoPersp:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordNoPerspAMD;
605
606 case glslang::EbvBaryCoordNoPerspCentroid:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
609
610 case glslang::EbvBaryCoordNoPerspSample:
611 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
612 return spv::BuiltInBaryCoordNoPerspSampleAMD;
613
614 case glslang::EbvBaryCoordSmooth:
615 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
616 return spv::BuiltInBaryCoordSmoothAMD;
617
618 case glslang::EbvBaryCoordSmoothCentroid:
619 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
620 return spv::BuiltInBaryCoordSmoothCentroidAMD;
621
622 case glslang::EbvBaryCoordSmoothSample:
623 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
624 return spv::BuiltInBaryCoordSmoothSampleAMD;
625
626 case glslang::EbvBaryCoordPullModel:
627 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
628 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800629#endif
chaoc771d89f2017-01-13 01:10:53 -0800630
John Kessenich6c8aaac2017-02-27 01:20:51 -0700631 case glslang::EbvDeviceIndex:
632 builder.addExtension(spv::E_SPV_KHR_device_group);
633 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700634 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700635
636 case glslang::EbvViewIndex:
637 builder.addExtension(spv::E_SPV_KHR_multiview);
638 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700639 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700640
chaoc771d89f2017-01-13 01:10:53 -0800641#ifdef NV_EXTENSIONS
642 case glslang::EbvViewportMaskNV:
643 builder.addExtension(spv::E_SPV_NV_viewport_array2);
644 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
645 return spv::BuiltInViewportMaskNV;
646 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800647 if (!memberDeclaration) {
648 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
649 builder.addCapability(spv::CapabilityShaderStereoViewNV);
650 }
chaoc771d89f2017-01-13 01:10:53 -0800651 return spv::BuiltInSecondaryPositionNV;
652 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800653 if (!memberDeclaration) {
654 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
655 builder.addCapability(spv::CapabilityShaderStereoViewNV);
656 }
chaoc771d89f2017-01-13 01:10:53 -0800657 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800658 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800659 if (!memberDeclaration) {
660 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
661 builder.addCapability(spv::CapabilityPerViewAttributesNV);
662 }
chaocdf3956c2017-02-14 14:52:34 -0800663 return spv::BuiltInPositionPerViewNV;
664 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800665 if (!memberDeclaration) {
666 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
667 builder.addCapability(spv::CapabilityPerViewAttributesNV);
668 }
chaocdf3956c2017-02-14 14:52:34 -0800669 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800670#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800671 default:
672 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600673 }
674}
675
Rex Xufc618912015-09-09 16:42:49 +0800676// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700677spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800678{
679 assert(type.getBasicType() == glslang::EbtSampler);
680
John Kessenich5d0fa972016-02-15 11:57:00 -0700681 // Check for capabilities
682 switch (type.getQualifier().layoutFormat) {
683 case glslang::ElfRg32f:
684 case glslang::ElfRg16f:
685 case glslang::ElfR11fG11fB10f:
686 case glslang::ElfR16f:
687 case glslang::ElfRgba16:
688 case glslang::ElfRgb10A2:
689 case glslang::ElfRg16:
690 case glslang::ElfRg8:
691 case glslang::ElfR16:
692 case glslang::ElfR8:
693 case glslang::ElfRgba16Snorm:
694 case glslang::ElfRg16Snorm:
695 case glslang::ElfRg8Snorm:
696 case glslang::ElfR16Snorm:
697 case glslang::ElfR8Snorm:
698
699 case glslang::ElfRg32i:
700 case glslang::ElfRg16i:
701 case glslang::ElfRg8i:
702 case glslang::ElfR16i:
703 case glslang::ElfR8i:
704
705 case glslang::ElfRgb10a2ui:
706 case glslang::ElfRg32ui:
707 case glslang::ElfRg16ui:
708 case glslang::ElfRg8ui:
709 case glslang::ElfR16ui:
710 case glslang::ElfR8ui:
711 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
712 break;
713
714 default:
715 break;
716 }
717
718 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800719 switch (type.getQualifier().layoutFormat) {
720 case glslang::ElfNone: return spv::ImageFormatUnknown;
721 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
722 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
723 case glslang::ElfR32f: return spv::ImageFormatR32f;
724 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
725 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
726 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
727 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
728 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
729 case glslang::ElfR16f: return spv::ImageFormatR16f;
730 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
731 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
732 case glslang::ElfRg16: return spv::ImageFormatRg16;
733 case glslang::ElfRg8: return spv::ImageFormatRg8;
734 case glslang::ElfR16: return spv::ImageFormatR16;
735 case glslang::ElfR8: return spv::ImageFormatR8;
736 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
737 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
738 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
739 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
740 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
741 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
742 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
743 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
744 case glslang::ElfR32i: return spv::ImageFormatR32i;
745 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
746 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
747 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
748 case glslang::ElfR16i: return spv::ImageFormatR16i;
749 case glslang::ElfR8i: return spv::ImageFormatR8i;
750 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
751 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
752 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
753 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
754 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
755 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
756 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
757 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
758 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
759 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600760 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800761 }
762}
763
qining25262b32016-05-06 17:25:16 -0400764// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700765// descriptor set.
766bool IsDescriptorResource(const glslang::TType& type)
767{
John Kessenichf7497e22016-03-08 21:36:22 -0700768 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700769 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700770 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700771
772 // non block...
773 // basically samplerXXX/subpass/sampler/texture are all included
774 // if they are the global-scope-class, not the function parameter
775 // (or local, if they ever exist) class.
776 if (type.getBasicType() == glslang::EbtSampler)
777 return type.getQualifier().isUniformOrBuffer();
778
779 // None of the above.
780 return false;
781}
782
John Kesseniche0b6cad2015-12-24 10:30:13 -0700783void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
784{
785 if (child.layoutMatrix == glslang::ElmNone)
786 child.layoutMatrix = parent.layoutMatrix;
787
788 if (parent.invariant)
789 child.invariant = true;
790 if (parent.nopersp)
791 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800792#ifdef AMD_EXTENSIONS
793 if (parent.explicitInterp)
794 child.explicitInterp = true;
795#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700796 if (parent.flat)
797 child.flat = true;
798 if (parent.centroid)
799 child.centroid = true;
800 if (parent.patch)
801 child.patch = true;
802 if (parent.sample)
803 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800804 if (parent.coherent)
805 child.coherent = true;
806 if (parent.volatil)
807 child.volatil = true;
808 if (parent.restrict)
809 child.restrict = true;
810 if (parent.readonly)
811 child.readonly = true;
812 if (parent.writeonly)
813 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700814}
815
John Kessenichf2b7f332016-09-01 17:05:23 -0600816bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817{
John Kessenich7b9fa252016-01-21 18:56:57 -0700818 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600819 // - struct members might inherit from a struct declaration
820 // (note that non-block structs don't explicitly inherit,
821 // only implicitly, meaning no decoration involved)
822 // - affect decorations on the struct members
823 // (note smooth does not, and expecting something like volatile
824 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700825 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600826 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700827}
828
John Kessenich140f3df2015-06-26 16:58:36 -0600829//
830// Implement the TGlslangToSpvTraverser class.
831//
832
Lei Zhang17535f72016-05-04 15:55:59 -0400833TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600834 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
835 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400836 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700837 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600838 glslangIntermediate(glslangIntermediate)
839{
840 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
841
842 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700843 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600844 stdBuiltins = builder.import("GLSL.std.450");
845 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600846 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
847 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600848
849 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600850 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
851 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600852 builder.addSourceExtension(it->c_str());
853
854 // Add the top-level modes for this shader.
855
John Kessenich92187592016-02-01 13:45:25 -0700856 if (glslangIntermediate->getXfbMode()) {
857 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600858 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700859 }
John Kessenich140f3df2015-06-26 16:58:36 -0600860
861 unsigned int mode;
862 switch (glslangIntermediate->getStage()) {
863 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600864 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600865 break;
866
867 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600868 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
870 break;
871
872 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700875 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
876 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
877 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600878 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600879 }
John Kessenich4016e382016-07-15 11:53:56 -0600880 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600881 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
882
John Kesseniche6903322015-10-13 16:29:02 -0600883 switch (glslangIntermediate->getVertexSpacing()) {
884 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
885 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
886 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600887 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600888 }
John Kessenich4016e382016-07-15 11:53:56 -0600889 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600890 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
891
892 switch (glslangIntermediate->getVertexOrder()) {
893 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
894 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600895 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600896 }
John Kessenich4016e382016-07-15 11:53:56 -0600897 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600898 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
899
900 if (glslangIntermediate->getPointMode())
901 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600902 break;
903
904 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600905 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600906 switch (glslangIntermediate->getInputPrimitive()) {
907 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
908 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
909 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700910 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600911 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600912 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600913 }
John Kessenich4016e382016-07-15 11:53:56 -0600914 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600915 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600916
John Kessenich140f3df2015-06-26 16:58:36 -0600917 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
918
919 switch (glslangIntermediate->getOutputPrimitive()) {
920 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
921 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
922 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600923 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600924 }
John Kessenich4016e382016-07-15 11:53:56 -0600925 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600926 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
927 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
928 break;
929
930 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600931 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600932 if (glslangIntermediate->getPixelCenterInteger())
933 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600934
John Kessenich140f3df2015-06-26 16:58:36 -0600935 if (glslangIntermediate->getOriginUpperLeft())
936 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600937 else
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600939
940 if (glslangIntermediate->getEarlyFragmentTests())
941 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
942
943 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600944 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
945 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600946 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600947 }
John Kessenich4016e382016-07-15 11:53:56 -0600948 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600949 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
950
951 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 break;
954
955 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600956 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600957 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
958 glslangIntermediate->getLocalSize(1),
959 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600960 break;
961
962 default:
963 break;
964 }
John Kessenich140f3df2015-06-26 16:58:36 -0600965}
966
John Kessenichfca82622016-11-26 13:23:20 -0700967// Finish creating SPV, after the traversal is complete.
968void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700969{
John Kessenich517fe7a2016-11-26 13:31:47 -0700970 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700971 builder.setBuildPoint(shaderEntry->getLastBlock());
972 builder.leaveFunction();
973 }
974
John Kessenich7ba63412015-12-20 17:37:07 -0700975 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100976 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
977 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700978
qiningda397332016-03-09 19:54:03 -0500979 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700980}
981
John Kessenichfca82622016-11-26 13:23:20 -0700982// Write the SPV into 'out'.
983void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600984{
John Kessenichfca82622016-11-26 13:23:20 -0700985 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600986}
987
988//
989// Implement the traversal functions.
990//
991// Return true from interior nodes to have the external traversal
992// continue on to children. Return false if children were
993// already processed.
994//
995
996//
qining25262b32016-05-06 17:25:16 -0400997// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600998// - uniform/input reads
999// - output writes
1000// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1001// - something simple that degenerates into the last bullet
1002//
1003void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1004{
qining75d1d802016-04-06 14:42:01 -04001005 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1006 if (symbol->getType().getQualifier().isSpecConstant())
1007 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1008
John Kessenich140f3df2015-06-26 16:58:36 -06001009 // getSymbolId() will set up all the IO decorations on the first call.
1010 // Formal function parameters were mapped during makeFunctions().
1011 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001012
1013 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1014 if (builder.isPointer(id)) {
1015 spv::StorageClass sc = builder.getStorageClass(id);
1016 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1017 iOSet.insert(id);
1018 }
1019
1020 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001021 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001022 // Prepare to generate code for the access
1023
1024 // L-value chains will be computed left to right. We're on the symbol now,
1025 // which is the left-most part of the access chain, so now is "clear" time,
1026 // followed by setting the base.
1027 builder.clearAccessChain();
1028
1029 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001030 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001031 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001032 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001033 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001034 // These are also pure R-values.
1035 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001036 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001037 builder.setAccessChainRValue(id);
1038 else
1039 builder.setAccessChainLValue(id);
1040 }
1041}
1042
1043bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1044{
qining40887662016-04-03 22:20:42 -04001045 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1046 if (node->getType().getQualifier().isSpecConstant())
1047 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1048
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // First, handle special cases
1050 switch (node->getOp()) {
1051 case glslang::EOpAssign:
1052 case glslang::EOpAddAssign:
1053 case glslang::EOpSubAssign:
1054 case glslang::EOpMulAssign:
1055 case glslang::EOpVectorTimesMatrixAssign:
1056 case glslang::EOpVectorTimesScalarAssign:
1057 case glslang::EOpMatrixTimesScalarAssign:
1058 case glslang::EOpMatrixTimesMatrixAssign:
1059 case glslang::EOpDivAssign:
1060 case glslang::EOpModAssign:
1061 case glslang::EOpAndAssign:
1062 case glslang::EOpInclusiveOrAssign:
1063 case glslang::EOpExclusiveOrAssign:
1064 case glslang::EOpLeftShiftAssign:
1065 case glslang::EOpRightShiftAssign:
1066 // A bin-op assign "a += b" means the same thing as "a = a + b"
1067 // where a is evaluated before b. For a simple assignment, GLSL
1068 // says to evaluate the left before the right. So, always, left
1069 // node then right node.
1070 {
1071 // get the left l-value, save it away
1072 builder.clearAccessChain();
1073 node->getLeft()->traverse(this);
1074 spv::Builder::AccessChain lValue = builder.getAccessChain();
1075
1076 // evaluate the right
1077 builder.clearAccessChain();
1078 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001079 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001080
1081 if (node->getOp() != glslang::EOpAssign) {
1082 // the left is also an r-value
1083 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001084 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001085
1086 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001087 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001088 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001089 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1090 node->getType().getBasicType());
1091
1092 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001093 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001094 }
1095
1096 // store the result
1097 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001098 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001099
1100 // assignments are expressions having an rValue after they are evaluated...
1101 builder.clearAccessChain();
1102 builder.setAccessChainRValue(rValue);
1103 }
1104 return false;
1105 case glslang::EOpIndexDirect:
1106 case glslang::EOpIndexDirectStruct:
1107 {
1108 // Get the left part of the access chain.
1109 node->getLeft()->traverse(this);
1110
1111 // Add the next element in the chain
1112
David Netoa901ffe2016-06-08 14:11:40 +01001113 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001114 if (! node->getLeft()->getType().isArray() &&
1115 node->getLeft()->getType().isVector() &&
1116 node->getOp() == glslang::EOpIndexDirect) {
1117 // This is essentially a hard-coded vector swizzle of size 1,
1118 // so short circuit the access-chain stuff with a swizzle.
1119 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001120 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001121 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001122 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001123 int spvIndex = glslangIndex;
1124 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1125 node->getOp() == glslang::EOpIndexDirectStruct)
1126 {
1127 // This may be, e.g., an anonymous block-member selection, which generally need
1128 // index remapping due to hidden members in anonymous blocks.
1129 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1130 assert(remapper.size() > 0);
1131 spvIndex = remapper[glslangIndex];
1132 }
John Kessenichebb50532016-05-16 19:22:05 -06001133
David Netoa901ffe2016-06-08 14:11:40 +01001134 // normal case for indexing array or structure or block
1135 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1136
1137 // Add capabilities here for accessing PointSize and clip/cull distance.
1138 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001139 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001140 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001141 }
1142 }
1143 return false;
1144 case glslang::EOpIndexIndirect:
1145 {
1146 // Structure or array or vector indirection.
1147 // Will use native SPIR-V access-chain for struct and array indirection;
1148 // matrices are arrays of vectors, so will also work for a matrix.
1149 // Will use the access chain's 'component' for variable index into a vector.
1150
1151 // This adapter is building access chains left to right.
1152 // Set up the access chain to the left.
1153 node->getLeft()->traverse(this);
1154
1155 // save it so that computing the right side doesn't trash it
1156 spv::Builder::AccessChain partial = builder.getAccessChain();
1157
1158 // compute the next index in the chain
1159 builder.clearAccessChain();
1160 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001161 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001162
1163 // restore the saved access chain
1164 builder.setAccessChain(partial);
1165
1166 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001167 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001168 else
John Kessenichfa668da2015-09-13 14:46:30 -06001169 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001170 }
1171 return false;
1172 case glslang::EOpVectorSwizzle:
1173 {
1174 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001175 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001176 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001177 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001178 }
1179 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001180 case glslang::EOpMatrixSwizzle:
1181 logger->missingFunctionality("matrix swizzle");
1182 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001183 case glslang::EOpLogicalOr:
1184 case glslang::EOpLogicalAnd:
1185 {
1186
1187 // These may require short circuiting, but can sometimes be done as straight
1188 // binary operations. The right operand must be short circuited if it has
1189 // side effects, and should probably be if it is complex.
1190 if (isTrivial(node->getRight()->getAsTyped()))
1191 break; // handle below as a normal binary operation
1192 // otherwise, we need to do dynamic short circuiting on the right operand
1193 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1194 builder.clearAccessChain();
1195 builder.setAccessChainRValue(result);
1196 }
1197 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001198 default:
1199 break;
1200 }
1201
1202 // Assume generic binary op...
1203
John Kessenich32cfd492016-02-02 12:37:46 -07001204 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001205 builder.clearAccessChain();
1206 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001207 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001208
John Kessenich32cfd492016-02-02 12:37:46 -07001209 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.clearAccessChain();
1211 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001212 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001215 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001216 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001217 convertGlslangToSpvType(node->getType()), left, right,
1218 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001219
John Kessenich50e57562015-12-21 21:21:11 -07001220 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001221 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001222 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001223 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001224 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001225 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001226 return false;
1227 }
John Kessenich140f3df2015-06-26 16:58:36 -06001228}
1229
1230bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1231{
qining40887662016-04-03 22:20:42 -04001232 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1233 if (node->getType().getQualifier().isSpecConstant())
1234 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1235
John Kessenichfc51d282015-08-19 13:34:18 -06001236 spv::Id result = spv::NoResult;
1237
1238 // try texturing first
1239 result = createImageTextureFunctionCall(node);
1240 if (result != spv::NoResult) {
1241 builder.clearAccessChain();
1242 builder.setAccessChainRValue(result);
1243
1244 return false; // done with this node
1245 }
1246
1247 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001248
1249 if (node->getOp() == glslang::EOpArrayLength) {
1250 // Quite special; won't want to evaluate the operand.
1251
1252 // Normal .length() would have been constant folded by the front-end.
1253 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001254 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001255 assert(node->getOperand()->getType().isRuntimeSizedArray());
1256 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1257 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001258 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1259 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001260
1261 builder.clearAccessChain();
1262 builder.setAccessChainRValue(length);
1263
1264 return false;
1265 }
1266
John Kessenichfc51d282015-08-19 13:34:18 -06001267 // Start by evaluating the operand
1268
John Kessenich8c8505c2016-07-26 12:50:38 -06001269 // Does it need a swizzle inversion? If so, evaluation is inverted;
1270 // operate first on the swizzle base, then apply the swizzle.
1271 spv::Id invertedType = spv::NoType;
1272 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1273 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1274 invertedType = getInvertedSwizzleType(*node->getOperand());
1275
John Kessenich140f3df2015-06-26 16:58:36 -06001276 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001277 if (invertedType != spv::NoType)
1278 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1279 else
1280 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001281
Rex Xufc618912015-09-09 16:42:49 +08001282 spv::Id operand = spv::NoResult;
1283
1284 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1285 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001286 node->getOp() == glslang::EOpAtomicCounter ||
1287 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001288 operand = builder.accessChainGetLValue(); // Special case l-value operands
1289 else
John Kessenich32cfd492016-02-02 12:37:46 -07001290 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001291
John Kessenichf6640762016-08-01 19:44:00 -06001292 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001293 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001294
1295 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001296 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001297 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 // if not, then possibly an operation
1300 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001301 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 if (invertedType)
1305 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1306
John Kessenich140f3df2015-06-26 16:58:36 -06001307 builder.clearAccessChain();
1308 builder.setAccessChainRValue(result);
1309
1310 return false; // done with this node
1311 }
1312
1313 // it must be a special case, check...
1314 switch (node->getOp()) {
1315 case glslang::EOpPostIncrement:
1316 case glslang::EOpPostDecrement:
1317 case glslang::EOpPreIncrement:
1318 case glslang::EOpPreDecrement:
1319 {
1320 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001321 spv::Id one = 0;
1322 if (node->getBasicType() == glslang::EbtFloat)
1323 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001324 else if (node->getBasicType() == glslang::EbtDouble)
1325 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001326#ifdef AMD_EXTENSIONS
1327 else if (node->getBasicType() == glslang::EbtFloat16)
1328 one = builder.makeFloat16Constant(1.0F);
1329#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001330 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1331 one = builder.makeInt64Constant(1);
1332 else
1333 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001334 glslang::TOperator op;
1335 if (node->getOp() == glslang::EOpPreIncrement ||
1336 node->getOp() == glslang::EOpPostIncrement)
1337 op = glslang::EOpAdd;
1338 else
1339 op = glslang::EOpSub;
1340
John Kessenichf6640762016-08-01 19:44:00 -06001341 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001342 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001343 convertGlslangToSpvType(node->getType()), operand, one,
1344 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001345 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001346
1347 // The result of operation is always stored, but conditionally the
1348 // consumed result. The consumed result is always an r-value.
1349 builder.accessChainStore(result);
1350 builder.clearAccessChain();
1351 if (node->getOp() == glslang::EOpPreIncrement ||
1352 node->getOp() == glslang::EOpPreDecrement)
1353 builder.setAccessChainRValue(result);
1354 else
1355 builder.setAccessChainRValue(operand);
1356 }
1357
1358 return false;
1359
1360 case glslang::EOpEmitStreamVertex:
1361 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1362 return false;
1363 case glslang::EOpEndStreamPrimitive:
1364 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1365 return false;
1366
1367 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001368 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001369 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001370 }
John Kessenich140f3df2015-06-26 16:58:36 -06001371}
1372
1373bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1374{
qining27e04a02016-04-14 16:40:20 -04001375 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1376 if (node->getType().getQualifier().isSpecConstant())
1377 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1378
John Kessenichfc51d282015-08-19 13:34:18 -06001379 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001380 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1381 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001382
1383 // try texturing
1384 result = createImageTextureFunctionCall(node);
1385 if (result != spv::NoResult) {
1386 builder.clearAccessChain();
1387 builder.setAccessChainRValue(result);
1388
1389 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001390 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001391 // "imageStore" is a special case, which has no result
1392 return false;
1393 }
John Kessenichfc51d282015-08-19 13:34:18 -06001394
John Kessenich140f3df2015-06-26 16:58:36 -06001395 glslang::TOperator binOp = glslang::EOpNull;
1396 bool reduceComparison = true;
1397 bool isMatrix = false;
1398 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001399 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001400
1401 assert(node->getOp());
1402
John Kessenichf6640762016-08-01 19:44:00 -06001403 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
1405 switch (node->getOp()) {
1406 case glslang::EOpSequence:
1407 {
1408 if (preVisit)
1409 ++sequenceDepth;
1410 else
1411 --sequenceDepth;
1412
1413 if (sequenceDepth == 1) {
1414 // If this is the parent node of all the functions, we want to see them
1415 // early, so all call points have actual SPIR-V functions to reference.
1416 // In all cases, still let the traverser visit the children for us.
1417 makeFunctions(node->getAsAggregate()->getSequence());
1418
John Kessenich6fccb3c2016-09-19 16:01:41 -06001419 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001420 // anything else gets there, so visit out of order, doing them all now.
1421 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1422
John Kessenich6a60c2f2016-12-08 21:01:59 -07001423 // 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 -06001424 // so do them manually.
1425 visitFunctions(node->getAsAggregate()->getSequence());
1426
1427 return false;
1428 }
1429
1430 return true;
1431 }
1432 case glslang::EOpLinkerObjects:
1433 {
1434 if (visit == glslang::EvPreVisit)
1435 linkageOnly = true;
1436 else
1437 linkageOnly = false;
1438
1439 return true;
1440 }
1441 case glslang::EOpComma:
1442 {
1443 // processing from left to right naturally leaves the right-most
1444 // lying around in the access chain
1445 glslang::TIntermSequence& glslangOperands = node->getSequence();
1446 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1447 glslangOperands[i]->traverse(this);
1448
1449 return false;
1450 }
1451 case glslang::EOpFunction:
1452 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001453 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001454 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001456 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001457 } else {
1458 handleFunctionEntry(node);
1459 }
1460 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001461 if (inEntryPoint)
1462 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001463 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001464 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 }
1466
1467 return true;
1468 case glslang::EOpParameters:
1469 // Parameters will have been consumed by EOpFunction processing, but not
1470 // the body, so we still visited the function node's children, making this
1471 // child redundant.
1472 return false;
1473 case glslang::EOpFunctionCall:
1474 {
1475 if (node->isUserDefined())
1476 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001477 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001478 if (result) {
1479 builder.clearAccessChain();
1480 builder.setAccessChainRValue(result);
1481 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001482 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001483
1484 return false;
1485 }
1486 case glslang::EOpConstructMat2x2:
1487 case glslang::EOpConstructMat2x3:
1488 case glslang::EOpConstructMat2x4:
1489 case glslang::EOpConstructMat3x2:
1490 case glslang::EOpConstructMat3x3:
1491 case glslang::EOpConstructMat3x4:
1492 case glslang::EOpConstructMat4x2:
1493 case glslang::EOpConstructMat4x3:
1494 case glslang::EOpConstructMat4x4:
1495 case glslang::EOpConstructDMat2x2:
1496 case glslang::EOpConstructDMat2x3:
1497 case glslang::EOpConstructDMat2x4:
1498 case glslang::EOpConstructDMat3x2:
1499 case glslang::EOpConstructDMat3x3:
1500 case glslang::EOpConstructDMat3x4:
1501 case glslang::EOpConstructDMat4x2:
1502 case glslang::EOpConstructDMat4x3:
1503 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001504#ifdef AMD_EXTENSIONS
1505 case glslang::EOpConstructF16Mat2x2:
1506 case glslang::EOpConstructF16Mat2x3:
1507 case glslang::EOpConstructF16Mat2x4:
1508 case glslang::EOpConstructF16Mat3x2:
1509 case glslang::EOpConstructF16Mat3x3:
1510 case glslang::EOpConstructF16Mat3x4:
1511 case glslang::EOpConstructF16Mat4x2:
1512 case glslang::EOpConstructF16Mat4x3:
1513 case glslang::EOpConstructF16Mat4x4:
1514#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001515 isMatrix = true;
1516 // fall through
1517 case glslang::EOpConstructFloat:
1518 case glslang::EOpConstructVec2:
1519 case glslang::EOpConstructVec3:
1520 case glslang::EOpConstructVec4:
1521 case glslang::EOpConstructDouble:
1522 case glslang::EOpConstructDVec2:
1523 case glslang::EOpConstructDVec3:
1524 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001525#ifdef AMD_EXTENSIONS
1526 case glslang::EOpConstructFloat16:
1527 case glslang::EOpConstructF16Vec2:
1528 case glslang::EOpConstructF16Vec3:
1529 case glslang::EOpConstructF16Vec4:
1530#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001531 case glslang::EOpConstructBool:
1532 case glslang::EOpConstructBVec2:
1533 case glslang::EOpConstructBVec3:
1534 case glslang::EOpConstructBVec4:
1535 case glslang::EOpConstructInt:
1536 case glslang::EOpConstructIVec2:
1537 case glslang::EOpConstructIVec3:
1538 case glslang::EOpConstructIVec4:
1539 case glslang::EOpConstructUint:
1540 case glslang::EOpConstructUVec2:
1541 case glslang::EOpConstructUVec3:
1542 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001543 case glslang::EOpConstructInt64:
1544 case glslang::EOpConstructI64Vec2:
1545 case glslang::EOpConstructI64Vec3:
1546 case glslang::EOpConstructI64Vec4:
1547 case glslang::EOpConstructUint64:
1548 case glslang::EOpConstructU64Vec2:
1549 case glslang::EOpConstructU64Vec3:
1550 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001551 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001552 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001553 {
1554 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001555 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001556 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001557 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001558 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001559 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001560 std::vector<spv::Id> constituents;
1561 for (int c = 0; c < (int)arguments.size(); ++c)
1562 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001563 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001564 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001565 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001566 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001567 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001568
1569 builder.clearAccessChain();
1570 builder.setAccessChainRValue(constructed);
1571
1572 return false;
1573 }
1574
1575 // These six are component-wise compares with component-wise results.
1576 // Forward on to createBinaryOperation(), requesting a vector result.
1577 case glslang::EOpLessThan:
1578 case glslang::EOpGreaterThan:
1579 case glslang::EOpLessThanEqual:
1580 case glslang::EOpGreaterThanEqual:
1581 case glslang::EOpVectorEqual:
1582 case glslang::EOpVectorNotEqual:
1583 {
1584 // Map the operation to a binary
1585 binOp = node->getOp();
1586 reduceComparison = false;
1587 switch (node->getOp()) {
1588 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1589 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1590 default: binOp = node->getOp(); break;
1591 }
1592
1593 break;
1594 }
1595 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001596 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001597 binOp = glslang::EOpMul;
1598 break;
1599 case glslang::EOpOuterProduct:
1600 // two vectors multiplied to make a matrix
1601 binOp = glslang::EOpOuterProduct;
1602 break;
1603 case glslang::EOpDot:
1604 {
qining25262b32016-05-06 17:25:16 -04001605 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001606 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001607 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001608 binOp = glslang::EOpMul;
1609 break;
1610 }
1611 case glslang::EOpMod:
1612 // when an aggregate, this is the floating-point mod built-in function,
1613 // which can be emitted by the one in createBinaryOperation()
1614 binOp = glslang::EOpMod;
1615 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001616 case glslang::EOpEmitVertex:
1617 case glslang::EOpEndPrimitive:
1618 case glslang::EOpBarrier:
1619 case glslang::EOpMemoryBarrier:
1620 case glslang::EOpMemoryBarrierAtomicCounter:
1621 case glslang::EOpMemoryBarrierBuffer:
1622 case glslang::EOpMemoryBarrierImage:
1623 case glslang::EOpMemoryBarrierShared:
1624 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001625 case glslang::EOpAllMemoryBarrierWithGroupSync:
1626 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1627 case glslang::EOpWorkgroupMemoryBarrier:
1628 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001629 noReturnValue = true;
1630 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1631 break;
1632
John Kessenich426394d2015-07-23 10:22:48 -06001633 case glslang::EOpAtomicAdd:
1634 case glslang::EOpAtomicMin:
1635 case glslang::EOpAtomicMax:
1636 case glslang::EOpAtomicAnd:
1637 case glslang::EOpAtomicOr:
1638 case glslang::EOpAtomicXor:
1639 case glslang::EOpAtomicExchange:
1640 case glslang::EOpAtomicCompSwap:
1641 atomic = true;
1642 break;
1643
John Kessenich140f3df2015-06-26 16:58:36 -06001644 default:
1645 break;
1646 }
1647
1648 //
1649 // See if it maps to a regular operation.
1650 //
John Kessenich140f3df2015-06-26 16:58:36 -06001651 if (binOp != glslang::EOpNull) {
1652 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1653 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1654 assert(left && right);
1655
1656 builder.clearAccessChain();
1657 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001658 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001659
1660 builder.clearAccessChain();
1661 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001662 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001663
qining25262b32016-05-06 17:25:16 -04001664 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001665 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001666 left->getType().getBasicType(), reduceComparison);
1667
1668 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001669 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001670 builder.clearAccessChain();
1671 builder.setAccessChainRValue(result);
1672
1673 return false;
1674 }
1675
John Kessenich426394d2015-07-23 10:22:48 -06001676 //
1677 // Create the list of operands.
1678 //
John Kessenich140f3df2015-06-26 16:58:36 -06001679 glslang::TIntermSequence& glslangOperands = node->getSequence();
1680 std::vector<spv::Id> operands;
1681 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001682 // special case l-value operands; there are just a few
1683 bool lvalue = false;
1684 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001685 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001686 case glslang::EOpModf:
1687 if (arg == 1)
1688 lvalue = true;
1689 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001690 case glslang::EOpInterpolateAtSample:
1691 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001692#ifdef AMD_EXTENSIONS
1693 case glslang::EOpInterpolateAtVertex:
1694#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001695 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001696 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001697
1698 // Does it need a swizzle inversion? If so, evaluation is inverted;
1699 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001700 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001701 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1702 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1703 }
Rex Xu7a26c172015-12-08 17:12:09 +08001704 break;
Rex Xud4782c12015-09-06 16:30:11 +08001705 case glslang::EOpAtomicAdd:
1706 case glslang::EOpAtomicMin:
1707 case glslang::EOpAtomicMax:
1708 case glslang::EOpAtomicAnd:
1709 case glslang::EOpAtomicOr:
1710 case glslang::EOpAtomicXor:
1711 case glslang::EOpAtomicExchange:
1712 case glslang::EOpAtomicCompSwap:
1713 if (arg == 0)
1714 lvalue = true;
1715 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001716 case glslang::EOpAddCarry:
1717 case glslang::EOpSubBorrow:
1718 if (arg == 2)
1719 lvalue = true;
1720 break;
1721 case glslang::EOpUMulExtended:
1722 case glslang::EOpIMulExtended:
1723 if (arg >= 2)
1724 lvalue = true;
1725 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001726 default:
1727 break;
1728 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001729 builder.clearAccessChain();
1730 if (invertedType != spv::NoType && arg == 0)
1731 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1732 else
1733 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001734 if (lvalue)
1735 operands.push_back(builder.accessChainGetLValue());
1736 else
John Kessenich32cfd492016-02-02 12:37:46 -07001737 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001738 }
John Kessenich426394d2015-07-23 10:22:48 -06001739
1740 if (atomic) {
1741 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001742 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001743 } else {
1744 // Pass through to generic operations.
1745 switch (glslangOperands.size()) {
1746 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001747 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001748 break;
1749 case 1:
qining25262b32016-05-06 17:25:16 -04001750 result = createUnaryOperation(
1751 node->getOp(), precision,
1752 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001753 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001754 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001755 break;
1756 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001758 break;
1759 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001760 if (invertedType)
1761 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001762 }
1763
1764 if (noReturnValue)
1765 return false;
1766
1767 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001768 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001769 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001770 } else {
1771 builder.clearAccessChain();
1772 builder.setAccessChainRValue(result);
1773 return false;
1774 }
1775}
1776
John Kessenich433e9ff2017-01-26 20:31:11 -07001777// This path handles both if-then-else and ?:
1778// The if-then-else has a node type of void, while
1779// ?: has either a void or a non-void node type
1780//
1781// Leaving the result, when not void:
1782// GLSL only has r-values as the result of a :?, but
1783// if we have an l-value, that can be more efficient if it will
1784// become the base of a complex r-value expression, because the
1785// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001786bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1787{
John Kessenich433e9ff2017-01-26 20:31:11 -07001788 // See if it simple and safe to generate OpSelect instead of using control flow.
1789 // Crucially, side effects must be avoided, and there are performance trade-offs.
1790 // Return true if good idea (and safe) for OpSelect, false otherwise.
1791 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001792 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1793 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001794 return false;
1795
1796 if (node->getTrueBlock() == nullptr ||
1797 node->getFalseBlock() == nullptr)
1798 return false;
1799
1800 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1801 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1802
1803 // return true if a single operand to ? : is okay for OpSelect
1804 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001805 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001806 };
1807
1808 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1809 operandOkay(node->getFalseBlock()->getAsTyped());
1810 };
1811
1812 // Emit OpSelect for this selection.
1813 const auto handleAsOpSelect = [&]() {
1814 node->getCondition()->traverse(this);
1815 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1816 node->getTrueBlock()->traverse(this);
1817 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1818 node->getFalseBlock()->traverse(this);
1819 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1820
1821 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1822 builder.clearAccessChain();
1823 builder.setAccessChainRValue(select);
1824 };
1825
1826 // Try for OpSelect
1827
1828 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001829 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1830 if (node->getType().getQualifier().isSpecConstant())
1831 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1832
John Kessenich433e9ff2017-01-26 20:31:11 -07001833 handleAsOpSelect();
1834 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001835 }
1836
John Kessenich433e9ff2017-01-26 20:31:11 -07001837 // Instead, emit control flow...
1838
1839 // Don't handle results as temporaries, because there will be two names
1840 // and better to leave SSA to later passes.
1841 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1842 ? spv::NoResult
1843 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1844
John Kessenich140f3df2015-06-26 16:58:36 -06001845 // emit the condition before doing anything with selection
1846 node->getCondition()->traverse(this);
1847
1848 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001849 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001850
John Kessenich433e9ff2017-01-26 20:31:11 -07001851 // emit the "then" statement
1852 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001853 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001854 if (result != spv::NoResult)
1855 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001856 }
1857
John Kessenich433e9ff2017-01-26 20:31:11 -07001858 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001859 ifBuilder.makeBeginElse();
1860 // emit the "else" statement
1861 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001862 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001863 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001864 }
1865
John Kessenich433e9ff2017-01-26 20:31:11 -07001866 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001867 ifBuilder.makeEndIf();
1868
John Kessenich433e9ff2017-01-26 20:31:11 -07001869 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001870 // GLSL only has r-values as the result of a :?, but
1871 // if we have an l-value, that can be more efficient if it will
1872 // become the base of a complex r-value expression, because the
1873 // next layer copies r-values into memory to use the access-chain mechanism
1874 builder.clearAccessChain();
1875 builder.setAccessChainLValue(result);
1876 }
1877
1878 return false;
1879}
1880
1881bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1882{
1883 // emit and get the condition before doing anything with switch
1884 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001885 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001886
1887 // browse the children to sort out code segments
1888 int defaultSegment = -1;
1889 std::vector<TIntermNode*> codeSegments;
1890 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1891 std::vector<int> caseValues;
1892 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1893 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1894 TIntermNode* child = *c;
1895 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001896 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001897 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001898 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001899 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1900 } else
1901 codeSegments.push_back(child);
1902 }
1903
qining25262b32016-05-06 17:25:16 -04001904 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001905 // statements between the last case and the end of the switch statement
1906 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1907 (int)codeSegments.size() == defaultSegment)
1908 codeSegments.push_back(nullptr);
1909
1910 // make the switch statement
1911 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001912 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001913
1914 // emit all the code in the segments
1915 breakForLoop.push(false);
1916 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1917 builder.nextSwitchSegment(segmentBlocks, s);
1918 if (codeSegments[s])
1919 codeSegments[s]->traverse(this);
1920 else
1921 builder.addSwitchBreak();
1922 }
1923 breakForLoop.pop();
1924
1925 builder.endSwitch(segmentBlocks);
1926
1927 return false;
1928}
1929
1930void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1931{
1932 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001933 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001934
1935 builder.clearAccessChain();
1936 builder.setAccessChainRValue(constant);
1937}
1938
1939bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1940{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001941 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001942 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001943 // Spec requires back edges to target header blocks, and every header block
1944 // must dominate its merge block. Make a header block first to ensure these
1945 // conditions are met. By definition, it will contain OpLoopMerge, followed
1946 // by a block-ending branch. But we don't want to put any other body/test
1947 // instructions in it, since the body/test may have arbitrary instructions,
1948 // including merges of its own.
1949 builder.setBuildPoint(&blocks.head);
1950 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001951 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001952 spv::Block& test = builder.makeNewBlock();
1953 builder.createBranch(&test);
1954
1955 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001956 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001957 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001958 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001959 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1960
1961 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001962 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001963 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001964 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001965 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001966 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001967
1968 builder.setBuildPoint(&blocks.continue_target);
1969 if (node->getTerminal())
1970 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001971 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001972 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001973 builder.createBranch(&blocks.body);
1974
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001975 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 builder.setBuildPoint(&blocks.body);
1977 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001978 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001979 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001980 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001981
1982 builder.setBuildPoint(&blocks.continue_target);
1983 if (node->getTerminal())
1984 node->getTerminal()->traverse(this);
1985 if (node->getTest()) {
1986 node->getTest()->traverse(this);
1987 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001988 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001989 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001990 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001991 // TODO: unless there was a break/return/discard instruction
1992 // somewhere in the body, this is an infinite loop, so we should
1993 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001994 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001995 }
John Kessenich140f3df2015-06-26 16:58:36 -06001996 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001997 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001998 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001999 return false;
2000}
2001
2002bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2003{
2004 if (node->getExpression())
2005 node->getExpression()->traverse(this);
2006
2007 switch (node->getFlowOp()) {
2008 case glslang::EOpKill:
2009 builder.makeDiscard();
2010 break;
2011 case glslang::EOpBreak:
2012 if (breakForLoop.top())
2013 builder.createLoopExit();
2014 else
2015 builder.addSwitchBreak();
2016 break;
2017 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002018 builder.createLoopContinue();
2019 break;
2020 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002021 if (node->getExpression()) {
2022 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2023 spv::Id returnId = accessChainLoad(glslangReturnType);
2024 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2025 builder.clearAccessChain();
2026 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2027 builder.setAccessChainLValue(copyId);
2028 multiTypeStore(glslangReturnType, returnId);
2029 returnId = builder.createLoad(copyId);
2030 }
2031 builder.makeReturn(false, returnId);
2032 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002033 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002034
2035 builder.clearAccessChain();
2036 break;
2037
2038 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002039 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002040 break;
2041 }
2042
2043 return false;
2044}
2045
2046spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2047{
qining25262b32016-05-06 17:25:16 -04002048 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002049 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002050 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002051 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002052 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002053 }
2054
2055 // Now, handle actual variables
2056 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2057 spv::Id spvType = convertGlslangToSpvType(node->getType());
2058
2059 const char* name = node->getName().c_str();
2060 if (glslang::IsAnonymous(name))
2061 name = "";
2062
2063 return builder.createVariable(storageClass, spvType, name);
2064}
2065
2066// Return type Id of the sampled type.
2067spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2068{
2069 switch (sampler.type) {
2070 case glslang::EbtFloat: return builder.makeFloatType(32);
2071 case glslang::EbtInt: return builder.makeIntType(32);
2072 case glslang::EbtUint: return builder.makeUintType(32);
2073 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002074 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002075 return builder.makeFloatType(32);
2076 }
2077}
2078
John Kessenich8c8505c2016-07-26 12:50:38 -06002079// If node is a swizzle operation, return the type that should be used if
2080// the swizzle base is first consumed by another operation, before the swizzle
2081// is applied.
2082spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2083{
John Kessenichecba76f2017-01-06 00:34:48 -07002084 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002085 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2086 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2087 else
2088 return spv::NoType;
2089}
2090
2091// When inverting a swizzle with a parent op, this function
2092// will apply the swizzle operation to a completed parent operation.
2093spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2094{
2095 std::vector<unsigned> swizzle;
2096 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2097 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2098}
2099
John Kessenich8c8505c2016-07-26 12:50:38 -06002100// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2101void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2102{
2103 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2104 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2105 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2106}
2107
John Kessenich3ac051e2015-12-20 11:29:16 -07002108// Convert from a glslang type to an SPV type, by calling into a
2109// recursive version of this function. This establishes the inherited
2110// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002111spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2112{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002113 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002114}
2115
2116// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002117// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002118// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002119spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002120{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002121 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002122
2123 switch (type.getBasicType()) {
2124 case glslang::EbtVoid:
2125 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002126 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002127 break;
2128 case glslang::EbtFloat:
2129 spvType = builder.makeFloatType(32);
2130 break;
2131 case glslang::EbtDouble:
2132 spvType = builder.makeFloatType(64);
2133 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002134#ifdef AMD_EXTENSIONS
2135 case glslang::EbtFloat16:
2136 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002137 spvType = builder.makeFloatType(16);
2138 break;
2139#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002140 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002141 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2142 // a 32-bit int where non-0 means true.
2143 if (explicitLayout != glslang::ElpNone)
2144 spvType = builder.makeUintType(32);
2145 else
2146 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002147 break;
2148 case glslang::EbtInt:
2149 spvType = builder.makeIntType(32);
2150 break;
2151 case glslang::EbtUint:
2152 spvType = builder.makeUintType(32);
2153 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002154 case glslang::EbtInt64:
2155 builder.addCapability(spv::CapabilityInt64);
2156 spvType = builder.makeIntType(64);
2157 break;
2158 case glslang::EbtUint64:
2159 builder.addCapability(spv::CapabilityInt64);
2160 spvType = builder.makeUintType(64);
2161 break;
John Kessenich426394d2015-07-23 10:22:48 -06002162 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002163 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002164 spvType = builder.makeUintType(32);
2165 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002166 case glslang::EbtSampler:
2167 {
2168 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002169 if (sampler.sampler) {
2170 // pure sampler
2171 spvType = builder.makeSamplerType();
2172 } else {
2173 // an image is present, make its type
2174 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2175 sampler.image ? 2 : 1, TranslateImageFormat(type));
2176 if (sampler.combined) {
2177 // already has both image and sampler, make the combined type
2178 spvType = builder.makeSampledImageType(spvType);
2179 }
John Kessenich55e7d112015-11-15 21:33:39 -07002180 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002181 }
John Kessenich140f3df2015-06-26 16:58:36 -06002182 break;
2183 case glslang::EbtStruct:
2184 case glslang::EbtBlock:
2185 {
2186 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002187 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002188
2189 // Try to share structs for different layouts, but not yet for other
2190 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002191 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002192 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002193 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002194 break;
2195
2196 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002197 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002198 memberRemapper[glslangMembers].resize(glslangMembers->size());
2199 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002200 }
2201 break;
2202 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002203 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002204 break;
2205 }
2206
2207 if (type.isMatrix())
2208 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2209 else {
2210 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2211 if (type.getVectorSize() > 1)
2212 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2213 }
2214
2215 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002216 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2217
John Kessenichc9a80832015-09-12 12:17:44 -06002218 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002219 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002220 // We need to decorate array strides for types needing explicit layout, except blocks.
2221 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002222 // Use a dummy glslang type for querying internal strides of
2223 // arrays of arrays, but using just a one-dimensional array.
2224 glslang::TType simpleArrayType(type, 0); // deference type of the array
2225 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2226 simpleArrayType.getArraySizes().dereference();
2227
2228 // Will compute the higher-order strides here, rather than making a whole
2229 // pile of types and doing repetitive recursion on their contents.
2230 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2231 }
John Kessenichf8842e52016-01-04 19:22:56 -07002232
2233 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002234 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002235 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002236 if (stride > 0)
2237 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002238 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002239 }
2240 } else {
2241 // single-dimensional array, and don't yet have stride
2242
John Kessenichf8842e52016-01-04 19:22:56 -07002243 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002244 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2245 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002246 }
John Kessenich31ed4832015-09-09 17:51:38 -06002247
John Kessenichc9a80832015-09-12 12:17:44 -06002248 // Do the outer dimension, which might not be known for a runtime-sized array
2249 if (type.isRuntimeSizedArray()) {
2250 spvType = builder.makeRuntimeArray(spvType);
2251 } else {
2252 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002253 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002254 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002255 if (stride > 0)
2256 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002257 }
2258
2259 return spvType;
2260}
2261
John Kessenich6090df02016-06-30 21:18:02 -06002262// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2263// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2264// Mutually recursive with convertGlslangToSpvType().
2265spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2266 const glslang::TTypeList* glslangMembers,
2267 glslang::TLayoutPacking explicitLayout,
2268 const glslang::TQualifier& qualifier)
2269{
2270 // Create a vector of struct types for SPIR-V to consume
2271 std::vector<spv::Id> spvMembers;
2272 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2273 int locationOffset = 0; // for use across struct members, when they are called recursively
2274 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2275 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2276 if (glslangMember.hiddenMember()) {
2277 ++memberDelta;
2278 if (type.getBasicType() == glslang::EbtBlock)
2279 memberRemapper[glslangMembers][i] = -1;
2280 } else {
2281 if (type.getBasicType() == glslang::EbtBlock)
2282 memberRemapper[glslangMembers][i] = i - memberDelta;
2283 // modify just this child's view of the qualifier
2284 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2285 InheritQualifiers(memberQualifier, qualifier);
2286
2287 // manually inherit location; it's more complex
2288 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2289 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2290 if (qualifier.hasLocation())
2291 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2292
2293 // recurse
2294 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2295 }
2296 }
2297
2298 // Make the SPIR-V type
2299 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002300 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002301 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2302
2303 // Decorate it
2304 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2305
2306 return spvType;
2307}
2308
2309void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2310 const glslang::TTypeList* glslangMembers,
2311 glslang::TLayoutPacking explicitLayout,
2312 const glslang::TQualifier& qualifier,
2313 spv::Id spvType)
2314{
2315 // Name and decorate the non-hidden members
2316 int offset = -1;
2317 int locationOffset = 0; // for use within the members of this struct
2318 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2319 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2320 int member = i;
2321 if (type.getBasicType() == glslang::EbtBlock)
2322 member = memberRemapper[glslangMembers][i];
2323
2324 // modify just this child's view of the qualifier
2325 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2326 InheritQualifiers(memberQualifier, qualifier);
2327
2328 // using -1 above to indicate a hidden member
2329 if (member >= 0) {
2330 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2331 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2332 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2333 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002334 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2335 type.getQualifier().storage == glslang::EvqVaryingOut) {
2336 if (type.getBasicType() == glslang::EbtBlock ||
2337 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002338 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2339 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2340 }
2341 }
2342 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2343
2344 if (qualifier.storage == glslang::EvqBuffer) {
2345 std::vector<spv::Decoration> memory;
2346 TranslateMemoryDecoration(memberQualifier, memory);
2347 for (unsigned int i = 0; i < memory.size(); ++i)
2348 addMemberDecoration(spvType, member, memory[i]);
2349 }
2350
John Kessenich2f47bc92016-06-30 21:47:35 -06002351 // Compute location decoration; tricky based on whether inheritance is at play and
2352 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002353 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2354 // probably move to the linker stage of the front end proper, and just have the
2355 // answer sitting already distributed throughout the individual member locations.
2356 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002357 // Ignore member locations if the container is an array, as that's
2358 // ill-specified and decisions have been made to not allow this anyway.
2359 // The object itself must have a location, and that comes out from decorating the object,
2360 // not the type (this code decorates types).
2361 if (! type.isArray()) {
2362 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2363 // struct members should not have explicit locations
2364 assert(type.getBasicType() != glslang::EbtStruct);
2365 location = memberQualifier.layoutLocation;
2366 } else if (type.getBasicType() != glslang::EbtBlock) {
2367 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2368 // The members, and their nested types, must not themselves have Location decorations.
2369 } else if (qualifier.hasLocation()) // inheritance
2370 location = qualifier.layoutLocation + locationOffset;
2371 }
John Kessenich6090df02016-06-30 21:18:02 -06002372 if (location >= 0)
2373 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2374
John Kessenich2f47bc92016-06-30 21:47:35 -06002375 if (qualifier.hasLocation()) // track for upcoming inheritance
2376 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2377
John Kessenich6090df02016-06-30 21:18:02 -06002378 // component, XFB, others
2379 if (glslangMember.getQualifier().hasComponent())
2380 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2381 if (glslangMember.getQualifier().hasXfbOffset())
2382 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2383 else if (explicitLayout != glslang::ElpNone) {
2384 // figure out what to do with offset, which is accumulating
2385 int nextOffset;
2386 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2387 if (offset >= 0)
2388 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2389 offset = nextOffset;
2390 }
2391
2392 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2393 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2394
2395 // built-in variable decorations
2396 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002397 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002398 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002399
2400#ifdef NV_EXTENSIONS
2401 if (builtIn == spv::BuiltInLayer) {
2402 // SPV_NV_viewport_array2 extension
2403 if (glslangMember.getQualifier().layoutViewportRelative){
2404 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2405 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2406 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2407 }
2408 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2409 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2410 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2411 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2412 }
2413 }
chaocdf3956c2017-02-14 14:52:34 -08002414 if (glslangMember.getQualifier().layoutPassthrough) {
2415 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2416 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2417 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2418 }
chaoc771d89f2017-01-13 01:10:53 -08002419#endif
John Kessenich6090df02016-06-30 21:18:02 -06002420 }
2421 }
2422
2423 // Decorate the structure
2424 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2425 addDecoration(spvType, TranslateBlockDecoration(type));
2426 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2427 builder.addCapability(spv::CapabilityGeometryStreams);
2428 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2429 }
2430 if (glslangIntermediate->getXfbMode()) {
2431 builder.addCapability(spv::CapabilityTransformFeedback);
2432 if (type.getQualifier().hasXfbStride())
2433 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2434 if (type.getQualifier().hasXfbBuffer())
2435 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2436 }
2437}
2438
John Kessenich6c292d32016-02-15 20:58:50 -07002439// Turn the expression forming the array size into an id.
2440// This is not quite trivial, because of specialization constants.
2441// Sometimes, a raw constant is turned into an Id, and sometimes
2442// a specialization constant expression is.
2443spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2444{
2445 // First, see if this is sized with a node, meaning a specialization constant:
2446 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2447 if (specNode != nullptr) {
2448 builder.clearAccessChain();
2449 specNode->traverse(this);
2450 return accessChainLoad(specNode->getAsTyped()->getType());
2451 }
qining25262b32016-05-06 17:25:16 -04002452
John Kessenich6c292d32016-02-15 20:58:50 -07002453 // Otherwise, need a compile-time (front end) size, get it:
2454 int size = arraySizes.getDimSize(dim);
2455 assert(size > 0);
2456 return builder.makeUintConstant(size);
2457}
2458
John Kessenich103bef92016-02-08 21:38:15 -07002459// Wrap the builder's accessChainLoad to:
2460// - localize handling of RelaxedPrecision
2461// - use the SPIR-V inferred type instead of another conversion of the glslang type
2462// (avoids unnecessary work and possible type punning for structures)
2463// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002464spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2465{
John Kessenich103bef92016-02-08 21:38:15 -07002466 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2467 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2468
2469 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002470 if (type.getBasicType() == glslang::EbtBool) {
2471 if (builder.isScalarType(nominalTypeId)) {
2472 // Conversion for bool
2473 spv::Id boolType = builder.makeBoolType();
2474 if (nominalTypeId != boolType)
2475 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2476 } else if (builder.isVectorType(nominalTypeId)) {
2477 // Conversion for bvec
2478 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2479 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2480 if (nominalTypeId != bvecType)
2481 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2482 }
2483 }
John Kessenich103bef92016-02-08 21:38:15 -07002484
2485 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002486}
2487
Rex Xu27253232016-02-23 17:51:09 +08002488// Wrap the builder's accessChainStore to:
2489// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002490//
2491// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002492void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2493{
2494 // Need to convert to abstract types when necessary
2495 if (type.getBasicType() == glslang::EbtBool) {
2496 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2497
2498 if (builder.isScalarType(nominalTypeId)) {
2499 // Conversion for bool
2500 spv::Id boolType = builder.makeBoolType();
2501 if (nominalTypeId != boolType) {
2502 spv::Id zero = builder.makeUintConstant(0);
2503 spv::Id one = builder.makeUintConstant(1);
2504 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2505 }
2506 } else if (builder.isVectorType(nominalTypeId)) {
2507 // Conversion for bvec
2508 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2509 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2510 if (nominalTypeId != bvecType) {
2511 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2512 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2513 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2514 }
2515 }
2516 }
2517
2518 builder.accessChainStore(rvalue);
2519}
2520
John Kessenich4bf71552016-09-02 11:20:21 -06002521// For storing when types match at the glslang level, but not might match at the
2522// SPIR-V level.
2523//
2524// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002525// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002526// as in a member-decorated way.
2527//
2528// NOTE: This function can handle any store request; if it's not special it
2529// simplifies to a simple OpStore.
2530//
2531// Implicitly uses the existing builder.accessChain as the storage target.
2532void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2533{
John Kessenichb3e24e42016-09-11 12:33:43 -06002534 // we only do the complex path here if it's an aggregate
2535 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002536 accessChainStore(type, rValue);
2537 return;
2538 }
2539
John Kessenichb3e24e42016-09-11 12:33:43 -06002540 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002541 spv::Id rType = builder.getTypeId(rValue);
2542 spv::Id lValue = builder.accessChainGetLValue();
2543 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2544 if (lType == rType) {
2545 accessChainStore(type, rValue);
2546 return;
2547 }
2548
John Kessenichb3e24e42016-09-11 12:33:43 -06002549 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002550 // where the two types were the same type in GLSL. This requires member
2551 // by member copy, recursively.
2552
John Kessenichb3e24e42016-09-11 12:33:43 -06002553 // If an array, copy element by element.
2554 if (type.isArray()) {
2555 glslang::TType glslangElementType(type, 0);
2556 spv::Id elementRType = builder.getContainedTypeId(rType);
2557 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2558 // get the source member
2559 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002560
John Kessenichb3e24e42016-09-11 12:33:43 -06002561 // set up the target storage
2562 builder.clearAccessChain();
2563 builder.setAccessChainLValue(lValue);
2564 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002565
John Kessenichb3e24e42016-09-11 12:33:43 -06002566 // store the member
2567 multiTypeStore(glslangElementType, elementRValue);
2568 }
2569 } else {
2570 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002571
John Kessenichb3e24e42016-09-11 12:33:43 -06002572 // loop over structure members
2573 const glslang::TTypeList& members = *type.getStruct();
2574 for (int m = 0; m < (int)members.size(); ++m) {
2575 const glslang::TType& glslangMemberType = *members[m].type;
2576
2577 // get the source member
2578 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2579 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2580
2581 // set up the target storage
2582 builder.clearAccessChain();
2583 builder.setAccessChainLValue(lValue);
2584 builder.accessChainPush(builder.makeIntConstant(m));
2585
2586 // store the member
2587 multiTypeStore(glslangMemberType, memberRValue);
2588 }
John Kessenich4bf71552016-09-02 11:20:21 -06002589 }
2590}
2591
John Kessenichf85e8062015-12-19 13:57:10 -07002592// Decide whether or not this type should be
2593// decorated with offsets and strides, and if so
2594// whether std140 or std430 rules should be applied.
2595glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002596{
John Kessenichf85e8062015-12-19 13:57:10 -07002597 // has to be a block
2598 if (type.getBasicType() != glslang::EbtBlock)
2599 return glslang::ElpNone;
2600
2601 // has to be a uniform or buffer block
2602 if (type.getQualifier().storage != glslang::EvqUniform &&
2603 type.getQualifier().storage != glslang::EvqBuffer)
2604 return glslang::ElpNone;
2605
2606 // return the layout to use
2607 switch (type.getQualifier().layoutPacking) {
2608 case glslang::ElpStd140:
2609 case glslang::ElpStd430:
2610 return type.getQualifier().layoutPacking;
2611 default:
2612 return glslang::ElpNone;
2613 }
John Kessenich31ed4832015-09-09 17:51:38 -06002614}
2615
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002616// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002617int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002618{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002619 int size;
John Kessenich49987892015-12-29 17:11:44 -07002620 int stride;
2621 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002622
2623 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002624}
2625
John Kessenich49987892015-12-29 17:11:44 -07002626// 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 -07002627// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002628int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002629{
John Kessenich49987892015-12-29 17:11:44 -07002630 glslang::TType elementType;
2631 elementType.shallowCopy(matrixType);
2632 elementType.clearArraySizes();
2633
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002634 int size;
John Kessenich49987892015-12-29 17:11:44 -07002635 int stride;
2636 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2637
2638 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002639}
2640
John Kessenich5e4b1242015-08-06 22:53:06 -06002641// Given a member type of a struct, realign the current offset for it, and compute
2642// the next (not yet aligned) offset for the next member, which will get aligned
2643// on the next call.
2644// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2645// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2646// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002647void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002648 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002649{
2650 // this will get a positive value when deemed necessary
2651 nextOffset = -1;
2652
John Kessenich5e4b1242015-08-06 22:53:06 -06002653 // override anything in currentOffset with user-set offset
2654 if (memberType.getQualifier().hasOffset())
2655 currentOffset = memberType.getQualifier().layoutOffset;
2656
2657 // It could be that current linker usage in glslang updated all the layoutOffset,
2658 // in which case the following code does not matter. But, that's not quite right
2659 // once cross-compilation unit GLSL validation is done, as the original user
2660 // settings are needed in layoutOffset, and then the following will come into play.
2661
John Kessenichf85e8062015-12-19 13:57:10 -07002662 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002663 if (! memberType.getQualifier().hasOffset())
2664 currentOffset = -1;
2665
2666 return;
2667 }
2668
John Kessenichf85e8062015-12-19 13:57:10 -07002669 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002670 if (currentOffset < 0)
2671 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002672
John Kessenich5e4b1242015-08-06 22:53:06 -06002673 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2674 // but possibly not yet correctly aligned.
2675
2676 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002677 int dummyStride;
2678 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002679 glslang::RoundToPow2(currentOffset, memberAlignment);
2680 nextOffset = currentOffset + memberSize;
2681}
2682
David Netoa901ffe2016-06-08 14:11:40 +01002683void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002684{
David Netoa901ffe2016-06-08 14:11:40 +01002685 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2686 switch (glslangBuiltIn)
2687 {
2688 case glslang::EbvClipDistance:
2689 case glslang::EbvCullDistance:
2690 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002691#ifdef NV_EXTENSIONS
2692 case glslang::EbvLayer:
2693 case glslang::EbvViewportMaskNV:
2694 case glslang::EbvSecondaryPositionNV:
2695 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002696 case glslang::EbvPositionPerViewNV:
2697 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002698#endif
David Netoa901ffe2016-06-08 14:11:40 +01002699 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2700 // Alternately, we could just call this for any glslang built-in, since the
2701 // capability already guards against duplicates.
2702 TranslateBuiltInDecoration(glslangBuiltIn, false);
2703 break;
2704 default:
2705 // Capabilities were already generated when the struct was declared.
2706 break;
2707 }
John Kessenichebb50532016-05-16 19:22:05 -06002708}
2709
John Kessenich6fccb3c2016-09-19 16:01:41 -06002710bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002711{
John Kessenicheee9d532016-09-19 18:09:30 -06002712 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002713}
2714
2715// Make all the functions, skeletally, without actually visiting their bodies.
2716void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2717{
2718 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2719 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002720 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002721 continue;
2722
2723 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002724 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002725 //
qining25262b32016-05-06 17:25:16 -04002726 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002727 // function. What it is an address of varies:
2728 //
John Kessenich4bf71552016-09-02 11:20:21 -06002729 // - "in" parameters not marked as "const" can be written to without modifying the calling
2730 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002731 //
2732 // - "const in" parameters can just be the r-value, as no writes need occur.
2733 //
John Kessenich4bf71552016-09-02 11:20:21 -06002734 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2735 // 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 -06002736
2737 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002738 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2740
2741 for (int p = 0; p < (int)parameters.size(); ++p) {
2742 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2743 spv::Id typeId = convertGlslangToSpvType(paramType);
steve-lunargdd8287a2017-02-23 18:04:12 -07002744 if (paramType.containsOpaque() ||
2745 (paramType.getBasicType() == glslang::EbtBlock && paramType.getQualifier().storage == glslang::EvqBuffer))
Jason Ekstranded15ef12016-06-08 13:54:48 -07002746 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2747 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002748 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2749 else
John Kessenich4bf71552016-09-02 11:20:21 -06002750 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002751 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002752 paramTypes.push_back(typeId);
2753 }
2754
2755 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002756 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2757 convertGlslangToSpvType(glslFunction->getType()),
2758 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002759
2760 // Track function to emit/call later
2761 functionMap[glslFunction->getName().c_str()] = function;
2762
2763 // Set the parameter id's
2764 for (int p = 0; p < (int)parameters.size(); ++p) {
2765 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2766 // give a name too
2767 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2768 }
2769 }
2770}
2771
2772// Process all the initializers, while skipping the functions and link objects
2773void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2774{
2775 builder.setBuildPoint(shaderEntry->getLastBlock());
2776 for (int i = 0; i < (int)initializers.size(); ++i) {
2777 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2778 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2779
2780 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002781 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002782 initializer->traverse(this);
2783 }
2784 }
2785}
2786
2787// Process all the functions, while skipping initializers.
2788void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2789{
2790 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2791 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002792 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002793 node->traverse(this);
2794 }
2795}
2796
2797void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2798{
qining25262b32016-05-06 17:25:16 -04002799 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002800 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002801 currentFunction = functionMap[node->getName().c_str()];
2802 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002803 builder.setBuildPoint(functionBlock);
2804}
2805
Rex Xu04db3f52015-09-16 11:44:02 +08002806void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002807{
Rex Xufc618912015-09-09 16:42:49 +08002808 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002809
2810 glslang::TSampler sampler = {};
2811 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002812 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002813 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2814 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2815 }
2816
John Kessenich140f3df2015-06-26 16:58:36 -06002817 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2818 builder.clearAccessChain();
2819 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002820
2821 // Special case l-value operands
2822 bool lvalue = false;
2823 switch (node.getOp()) {
2824 case glslang::EOpImageAtomicAdd:
2825 case glslang::EOpImageAtomicMin:
2826 case glslang::EOpImageAtomicMax:
2827 case glslang::EOpImageAtomicAnd:
2828 case glslang::EOpImageAtomicOr:
2829 case glslang::EOpImageAtomicXor:
2830 case glslang::EOpImageAtomicExchange:
2831 case glslang::EOpImageAtomicCompSwap:
2832 if (i == 0)
2833 lvalue = true;
2834 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002835 case glslang::EOpSparseImageLoad:
2836 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2837 lvalue = true;
2838 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002839 case glslang::EOpSparseTexture:
2840 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2841 lvalue = true;
2842 break;
2843 case glslang::EOpSparseTextureClamp:
2844 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2845 lvalue = true;
2846 break;
2847 case glslang::EOpSparseTextureLod:
2848 case glslang::EOpSparseTextureOffset:
2849 if (i == 3)
2850 lvalue = true;
2851 break;
2852 case glslang::EOpSparseTextureFetch:
2853 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2854 lvalue = true;
2855 break;
2856 case glslang::EOpSparseTextureFetchOffset:
2857 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2858 lvalue = true;
2859 break;
2860 case glslang::EOpSparseTextureLodOffset:
2861 case glslang::EOpSparseTextureGrad:
2862 case glslang::EOpSparseTextureOffsetClamp:
2863 if (i == 4)
2864 lvalue = true;
2865 break;
2866 case glslang::EOpSparseTextureGradOffset:
2867 case glslang::EOpSparseTextureGradClamp:
2868 if (i == 5)
2869 lvalue = true;
2870 break;
2871 case glslang::EOpSparseTextureGradOffsetClamp:
2872 if (i == 6)
2873 lvalue = true;
2874 break;
2875 case glslang::EOpSparseTextureGather:
2876 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2877 lvalue = true;
2878 break;
2879 case glslang::EOpSparseTextureGatherOffset:
2880 case glslang::EOpSparseTextureGatherOffsets:
2881 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2882 lvalue = true;
2883 break;
Rex Xufc618912015-09-09 16:42:49 +08002884 default:
2885 break;
2886 }
2887
Rex Xu6b86d492015-09-16 17:48:22 +08002888 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002889 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002890 else
John Kessenich32cfd492016-02-02 12:37:46 -07002891 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002892 }
2893}
2894
John Kessenichfc51d282015-08-19 13:34:18 -06002895void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002896{
John Kessenichfc51d282015-08-19 13:34:18 -06002897 builder.clearAccessChain();
2898 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002899 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002900}
John Kessenich140f3df2015-06-26 16:58:36 -06002901
John Kessenichfc51d282015-08-19 13:34:18 -06002902spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2903{
Rex Xufc618912015-09-09 16:42:49 +08002904 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002905 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002906 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002907 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002908
John Kessenichfc51d282015-08-19 13:34:18 -06002909 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002910 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2911 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2912 std::vector<spv::Id> arguments;
2913 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002914 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002915 else
2916 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002917 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002918
2919 spv::Builder::TextureParameters params = { };
2920 params.sampler = arguments[0];
2921
Rex Xu04db3f52015-09-16 11:44:02 +08002922 glslang::TCrackedTextureOp cracked;
2923 node->crackTexture(sampler, cracked);
2924
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002925 const bool isUnsignedResult =
2926 node->getType().getBasicType() == glslang::EbtUint64 ||
2927 node->getType().getBasicType() == glslang::EbtUint;
2928
John Kessenichfc51d282015-08-19 13:34:18 -06002929 // Check for queries
2930 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002931 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2932 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002933 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002934
John Kessenichfc51d282015-08-19 13:34:18 -06002935 switch (node->getOp()) {
2936 case glslang::EOpImageQuerySize:
2937 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002938 if (arguments.size() > 1) {
2939 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002940 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002941 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002942 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002943 case glslang::EOpImageQuerySamples:
2944 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002945 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002946 case glslang::EOpTextureQueryLod:
2947 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002948 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002949 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002950 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08002951 case glslang::EOpSparseTexelsResident:
2952 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002953 default:
2954 assert(0);
2955 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002956 }
John Kessenich140f3df2015-06-26 16:58:36 -06002957 }
2958
Rex Xufc618912015-09-09 16:42:49 +08002959 // Check for image functions other than queries
2960 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002961 std::vector<spv::Id> operands;
2962 auto opIt = arguments.begin();
2963 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002964
2965 // Handle subpass operations
2966 // TODO: GLSL should change to have the "MS" only on the type rather than the
2967 // built-in function.
2968 if (cracked.subpass) {
2969 // add on the (0,0) coordinate
2970 spv::Id zero = builder.makeIntConstant(0);
2971 std::vector<spv::Id> comps;
2972 comps.push_back(zero);
2973 comps.push_back(zero);
2974 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2975 if (sampler.ms) {
2976 operands.push_back(spv::ImageOperandsSampleMask);
2977 operands.push_back(*(opIt++));
2978 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002979 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002980 }
2981
John Kessenich56bab042015-09-16 10:54:31 -06002982 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002983 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002984 if (sampler.ms) {
2985 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002986 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002987 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002988 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2989 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002990 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002991 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002992 if (sampler.ms) {
2993 operands.push_back(*(opIt + 1));
2994 operands.push_back(spv::ImageOperandsSampleMask);
2995 operands.push_back(*opIt);
2996 } else
2997 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002998 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002999 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3000 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003001 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003002 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3003 builder.addCapability(spv::CapabilitySparseResidency);
3004 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3005 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3006
3007 if (sampler.ms) {
3008 operands.push_back(spv::ImageOperandsSampleMask);
3009 operands.push_back(*opIt++);
3010 }
3011
3012 // Create the return type that was a special structure
3013 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003014 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003015 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3016 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3017
3018 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3019
3020 // Decode the return type
3021 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3022 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003023 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003024 // Process image atomic operations
3025
3026 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3027 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003028 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003029
John Kessenich8c8505c2016-07-26 12:50:38 -06003030 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003031 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003032
3033 std::vector<spv::Id> operands;
3034 operands.push_back(pointer);
3035 for (; opIt != arguments.end(); ++opIt)
3036 operands.push_back(*opIt);
3037
John Kessenich8c8505c2016-07-26 12:50:38 -06003038 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003039 }
3040 }
3041
3042 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003043 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003044 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3045
John Kessenichfc51d282015-08-19 13:34:18 -06003046 // check for bias argument
3047 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003048 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003049 int nonBiasArgCount = 2;
3050 if (cracked.offset)
3051 ++nonBiasArgCount;
3052 if (cracked.grad)
3053 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003054 if (cracked.lodClamp)
3055 ++nonBiasArgCount;
3056 if (sparse)
3057 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003058
3059 if ((int)arguments.size() > nonBiasArgCount)
3060 bias = true;
3061 }
3062
John Kessenicha5c33d62016-06-02 23:45:21 -06003063 // See if the sampler param should really be just the SPV image part
3064 if (cracked.fetch) {
3065 // a fetch needs to have the image extracted first
3066 if (builder.isSampledImage(params.sampler))
3067 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3068 }
3069
John Kessenichfc51d282015-08-19 13:34:18 -06003070 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003071
John Kessenichfc51d282015-08-19 13:34:18 -06003072 params.coords = arguments[1];
3073 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003074 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003075
3076 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003077 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003078 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003079 ++extraArgs;
3080 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003081 params.Dref = arguments[2];
3082 ++extraArgs;
3083 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003084 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003085 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003086 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003087 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003088 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003089 dRefComp = builder.getNumComponents(params.coords) - 1;
3090 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003091 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3092 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003093
3094 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003095 if (cracked.lod) {
3096 params.lod = arguments[2];
3097 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003098 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3099 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3100 noImplicitLod = true;
3101 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003102
3103 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003104 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003105 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003106 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003107 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003108
3109 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003110 if (cracked.grad) {
3111 params.gradX = arguments[2 + extraArgs];
3112 params.gradY = arguments[3 + extraArgs];
3113 extraArgs += 2;
3114 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003115
3116 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003117 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003118 params.offset = arguments[2 + extraArgs];
3119 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003120 } else if (cracked.offsets) {
3121 params.offsets = arguments[2 + extraArgs];
3122 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003123 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003124
3125 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003126 if (cracked.lodClamp) {
3127 params.lodClamp = arguments[2 + extraArgs];
3128 ++extraArgs;
3129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003130
3131 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003132 if (sparse) {
3133 params.texelOut = arguments[2 + extraArgs];
3134 ++extraArgs;
3135 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003136
3137 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003138 if (bias) {
3139 params.bias = arguments[2 + extraArgs];
3140 ++extraArgs;
3141 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003142
3143 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003144 if (cracked.gather && ! sampler.shadow) {
3145 // default component is 0, if missing, otherwise an argument
3146 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003147 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003148 ++extraArgs;
3149 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003150 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003151 }
3152 }
John Kessenichfc51d282015-08-19 13:34:18 -06003153
John Kessenich65336482016-06-16 14:06:26 -06003154 // projective component (might not to move)
3155 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3156 // are divided by the last component of P."
3157 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3158 // unused components will appear after all used components."
3159 if (cracked.proj) {
3160 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3161 int projTargetComp;
3162 switch (sampler.dim) {
3163 case glslang::Esd1D: projTargetComp = 1; break;
3164 case glslang::Esd2D: projTargetComp = 2; break;
3165 case glslang::EsdRect: projTargetComp = 2; break;
3166 default: projTargetComp = projSourceComp; break;
3167 }
3168 // copy the projective coordinate if we have to
3169 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003170 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003171 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3172 projSourceComp);
3173 params.coords = builder.createCompositeInsert(projComp, params.coords,
3174 builder.getTypeId(params.coords), projTargetComp);
3175 }
3176 }
3177
John Kessenich8c8505c2016-07-26 12:50:38 -06003178 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003179}
3180
3181spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3182{
3183 // Grab the function's pointer from the previously created function
3184 spv::Function* function = functionMap[node->getName().c_str()];
3185 if (! function)
3186 return 0;
3187
3188 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3189 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3190
3191 // See comments in makeFunctions() for details about the semantics for parameter passing.
3192 //
3193 // These imply we need a four step process:
3194 // 1. Evaluate the arguments
3195 // 2. Allocate and make copies of in, out, and inout arguments
3196 // 3. Make the call
3197 // 4. Copy back the results
3198
3199 // 1. Evaluate the arguments
3200 std::vector<spv::Builder::AccessChain> lValues;
3201 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003202 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003204 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003205 // build l-value
3206 builder.clearAccessChain();
3207 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003208 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003209 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003210 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003211 // save l-value
3212 lValues.push_back(builder.getAccessChain());
3213 } else {
3214 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003215 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003216 }
3217 }
3218
3219 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3220 // copy the original into that space.
3221 //
3222 // Also, build up the list of actual arguments to pass in for the call
3223 int lValueCount = 0;
3224 int rValueCount = 0;
3225 std::vector<spv::Id> spvArgs;
3226 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003227 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003228 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003229 if (paramType.containsOpaque() ||
3230 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003231 builder.setAccessChain(lValues[lValueCount]);
3232 arg = builder.accessChainGetLValue();
3233 ++lValueCount;
3234 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003235 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003236 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3237 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3238 // need to copy the input into output space
3239 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003240 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003241 builder.clearAccessChain();
3242 builder.setAccessChainLValue(arg);
3243 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003244 }
3245 ++lValueCount;
3246 } else {
3247 arg = rValues[rValueCount];
3248 ++rValueCount;
3249 }
3250 spvArgs.push_back(arg);
3251 }
3252
3253 // 3. Make the call.
3254 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003255 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003256
3257 // 4. Copy back out an "out" arguments.
3258 lValueCount = 0;
3259 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003260 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003261 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3262 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3263 spv::Id copy = builder.createLoad(spvArgs[a]);
3264 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003265 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003266 }
3267 ++lValueCount;
3268 }
3269 }
3270
3271 return result;
3272}
3273
3274// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003275spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3276 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003277 spv::Id typeId, spv::Id left, spv::Id right,
3278 glslang::TBasicType typeProxy, bool reduceComparison)
3279{
Rex Xu8ff43de2016-04-22 16:51:45 +08003280 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003281#ifdef AMD_EXTENSIONS
3282 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3283#else
John Kessenich140f3df2015-06-26 16:58:36 -06003284 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003285#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003286 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003287
3288 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003289 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003290 bool comparison = false;
3291
3292 switch (op) {
3293 case glslang::EOpAdd:
3294 case glslang::EOpAddAssign:
3295 if (isFloat)
3296 binOp = spv::OpFAdd;
3297 else
3298 binOp = spv::OpIAdd;
3299 break;
3300 case glslang::EOpSub:
3301 case glslang::EOpSubAssign:
3302 if (isFloat)
3303 binOp = spv::OpFSub;
3304 else
3305 binOp = spv::OpISub;
3306 break;
3307 case glslang::EOpMul:
3308 case glslang::EOpMulAssign:
3309 if (isFloat)
3310 binOp = spv::OpFMul;
3311 else
3312 binOp = spv::OpIMul;
3313 break;
3314 case glslang::EOpVectorTimesScalar:
3315 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003316 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003317 if (builder.isVector(right))
3318 std::swap(left, right);
3319 assert(builder.isScalar(right));
3320 needMatchingVectors = false;
3321 binOp = spv::OpVectorTimesScalar;
3322 } else
3323 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 break;
3325 case glslang::EOpVectorTimesMatrix:
3326 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003327 binOp = spv::OpVectorTimesMatrix;
3328 break;
3329 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003330 binOp = spv::OpMatrixTimesVector;
3331 break;
3332 case glslang::EOpMatrixTimesScalar:
3333 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003334 binOp = spv::OpMatrixTimesScalar;
3335 break;
3336 case glslang::EOpMatrixTimesMatrix:
3337 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003338 binOp = spv::OpMatrixTimesMatrix;
3339 break;
3340 case glslang::EOpOuterProduct:
3341 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003342 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003343 break;
3344
3345 case glslang::EOpDiv:
3346 case glslang::EOpDivAssign:
3347 if (isFloat)
3348 binOp = spv::OpFDiv;
3349 else if (isUnsigned)
3350 binOp = spv::OpUDiv;
3351 else
3352 binOp = spv::OpSDiv;
3353 break;
3354 case glslang::EOpMod:
3355 case glslang::EOpModAssign:
3356 if (isFloat)
3357 binOp = spv::OpFMod;
3358 else if (isUnsigned)
3359 binOp = spv::OpUMod;
3360 else
3361 binOp = spv::OpSMod;
3362 break;
3363 case glslang::EOpRightShift:
3364 case glslang::EOpRightShiftAssign:
3365 if (isUnsigned)
3366 binOp = spv::OpShiftRightLogical;
3367 else
3368 binOp = spv::OpShiftRightArithmetic;
3369 break;
3370 case glslang::EOpLeftShift:
3371 case glslang::EOpLeftShiftAssign:
3372 binOp = spv::OpShiftLeftLogical;
3373 break;
3374 case glslang::EOpAnd:
3375 case glslang::EOpAndAssign:
3376 binOp = spv::OpBitwiseAnd;
3377 break;
3378 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003379 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003380 binOp = spv::OpLogicalAnd;
3381 break;
3382 case glslang::EOpInclusiveOr:
3383 case glslang::EOpInclusiveOrAssign:
3384 binOp = spv::OpBitwiseOr;
3385 break;
3386 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003387 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003388 binOp = spv::OpLogicalOr;
3389 break;
3390 case glslang::EOpExclusiveOr:
3391 case glslang::EOpExclusiveOrAssign:
3392 binOp = spv::OpBitwiseXor;
3393 break;
3394 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003395 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003396 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398
3399 case glslang::EOpLessThan:
3400 case glslang::EOpGreaterThan:
3401 case glslang::EOpLessThanEqual:
3402 case glslang::EOpGreaterThanEqual:
3403 case glslang::EOpEqual:
3404 case glslang::EOpNotEqual:
3405 case glslang::EOpVectorEqual:
3406 case glslang::EOpVectorNotEqual:
3407 comparison = true;
3408 break;
3409 default:
3410 break;
3411 }
3412
John Kessenich7c1aa102015-10-15 13:29:11 -06003413 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003414 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003415 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003416 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003417 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003418
3419 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003420 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003421 builder.promoteScalar(precision, left, right);
3422
qining25262b32016-05-06 17:25:16 -04003423 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3424 addDecoration(result, noContraction);
3425 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003426 }
3427
3428 if (! comparison)
3429 return 0;
3430
John Kessenich7c1aa102015-10-15 13:29:11 -06003431 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003432
John Kessenich4583b612016-08-07 19:14:22 -06003433 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3434 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003435 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003436
3437 switch (op) {
3438 case glslang::EOpLessThan:
3439 if (isFloat)
3440 binOp = spv::OpFOrdLessThan;
3441 else if (isUnsigned)
3442 binOp = spv::OpULessThan;
3443 else
3444 binOp = spv::OpSLessThan;
3445 break;
3446 case glslang::EOpGreaterThan:
3447 if (isFloat)
3448 binOp = spv::OpFOrdGreaterThan;
3449 else if (isUnsigned)
3450 binOp = spv::OpUGreaterThan;
3451 else
3452 binOp = spv::OpSGreaterThan;
3453 break;
3454 case glslang::EOpLessThanEqual:
3455 if (isFloat)
3456 binOp = spv::OpFOrdLessThanEqual;
3457 else if (isUnsigned)
3458 binOp = spv::OpULessThanEqual;
3459 else
3460 binOp = spv::OpSLessThanEqual;
3461 break;
3462 case glslang::EOpGreaterThanEqual:
3463 if (isFloat)
3464 binOp = spv::OpFOrdGreaterThanEqual;
3465 else if (isUnsigned)
3466 binOp = spv::OpUGreaterThanEqual;
3467 else
3468 binOp = spv::OpSGreaterThanEqual;
3469 break;
3470 case glslang::EOpEqual:
3471 case glslang::EOpVectorEqual:
3472 if (isFloat)
3473 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003474 else if (isBool)
3475 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003476 else
3477 binOp = spv::OpIEqual;
3478 break;
3479 case glslang::EOpNotEqual:
3480 case glslang::EOpVectorNotEqual:
3481 if (isFloat)
3482 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003483 else if (isBool)
3484 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003485 else
3486 binOp = spv::OpINotEqual;
3487 break;
3488 default:
3489 break;
3490 }
3491
qining25262b32016-05-06 17:25:16 -04003492 if (binOp != spv::OpNop) {
3493 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3494 addDecoration(result, noContraction);
3495 return builder.setPrecision(result, precision);
3496 }
John Kessenich140f3df2015-06-26 16:58:36 -06003497
3498 return 0;
3499}
3500
John Kessenich04bb8a02015-12-12 12:28:14 -07003501//
3502// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3503// These can be any of:
3504//
3505// matrix * scalar
3506// scalar * matrix
3507// matrix * matrix linear algebraic
3508// matrix * vector
3509// vector * matrix
3510// matrix * matrix componentwise
3511// matrix op matrix op in {+, -, /}
3512// matrix op scalar op in {+, -, /}
3513// scalar op matrix op in {+, -, /}
3514//
qining25262b32016-05-06 17:25:16 -04003515spv::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 -07003516{
3517 bool firstClass = true;
3518
3519 // First, handle first-class matrix operations (* and matrix/scalar)
3520 switch (op) {
3521 case spv::OpFDiv:
3522 if (builder.isMatrix(left) && builder.isScalar(right)) {
3523 // turn matrix / scalar into a multiply...
3524 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3525 op = spv::OpMatrixTimesScalar;
3526 } else
3527 firstClass = false;
3528 break;
3529 case spv::OpMatrixTimesScalar:
3530 if (builder.isMatrix(right))
3531 std::swap(left, right);
3532 assert(builder.isScalar(right));
3533 break;
3534 case spv::OpVectorTimesMatrix:
3535 assert(builder.isVector(left));
3536 assert(builder.isMatrix(right));
3537 break;
3538 case spv::OpMatrixTimesVector:
3539 assert(builder.isMatrix(left));
3540 assert(builder.isVector(right));
3541 break;
3542 case spv::OpMatrixTimesMatrix:
3543 assert(builder.isMatrix(left));
3544 assert(builder.isMatrix(right));
3545 break;
3546 default:
3547 firstClass = false;
3548 break;
3549 }
3550
qining25262b32016-05-06 17:25:16 -04003551 if (firstClass) {
3552 spv::Id result = builder.createBinOp(op, typeId, left, right);
3553 addDecoration(result, noContraction);
3554 return builder.setPrecision(result, precision);
3555 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003556
LoopDawg592860c2016-06-09 08:57:35 -06003557 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003558 // The result type of all of them is the same type as the (a) matrix operand.
3559 // The algorithm is to:
3560 // - break the matrix(es) into vectors
3561 // - smear any scalar to a vector
3562 // - do vector operations
3563 // - make a matrix out the vector results
3564 switch (op) {
3565 case spv::OpFAdd:
3566 case spv::OpFSub:
3567 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003568 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003569 case spv::OpFMul:
3570 {
3571 // one time set up...
3572 bool leftMat = builder.isMatrix(left);
3573 bool rightMat = builder.isMatrix(right);
3574 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3575 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3576 spv::Id scalarType = builder.getScalarTypeId(typeId);
3577 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3578 std::vector<spv::Id> results;
3579 spv::Id smearVec = spv::NoResult;
3580 if (builder.isScalar(left))
3581 smearVec = builder.smearScalar(precision, left, vecType);
3582 else if (builder.isScalar(right))
3583 smearVec = builder.smearScalar(precision, right, vecType);
3584
3585 // do each vector op
3586 for (unsigned int c = 0; c < numCols; ++c) {
3587 std::vector<unsigned int> indexes;
3588 indexes.push_back(c);
3589 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3590 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003591 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3592 addDecoration(result, noContraction);
3593 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003594 }
3595
3596 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003597 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003598 }
3599 default:
3600 assert(0);
3601 return spv::NoResult;
3602 }
3603}
3604
qining25262b32016-05-06 17:25:16 -04003605spv::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 -06003606{
3607 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003608 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003609 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003610 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003611#ifdef AMD_EXTENSIONS
3612 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3613#else
Rex Xu04db3f52015-09-16 11:44:02 +08003614 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003615#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003616
3617 switch (op) {
3618 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003619 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003620 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003621 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003622 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003623 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003624 unaryOp = spv::OpSNegate;
3625 break;
3626
3627 case glslang::EOpLogicalNot:
3628 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 unaryOp = spv::OpLogicalNot;
3630 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003631 case glslang::EOpBitwiseNot:
3632 unaryOp = spv::OpNot;
3633 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003634
John Kessenich140f3df2015-06-26 16:58:36 -06003635 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003636 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003637 break;
3638 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003639 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003640 break;
3641 case glslang::EOpTranspose:
3642 unaryOp = spv::OpTranspose;
3643 break;
3644
3645 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003646 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003647 break;
3648 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003649 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003650 break;
3651 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003652 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003653 break;
3654 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003655 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003656 break;
3657 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003658 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003659 break;
3660 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003661 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003662 break;
3663 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003664 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003665 break;
3666 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003667 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003668 break;
3669
3670 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003671 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003672 break;
3673 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003674 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003675 break;
3676 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003677 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003678 break;
3679 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003680 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003681 break;
3682 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003683 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003684 break;
3685 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003686 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688
3689 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003691 break;
3692 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003693 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695
3696 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003697 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003698 break;
3699 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003700 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003703 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003704 break;
3705 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003706 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003707 break;
3708 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003709 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714
3715 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003716 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
3718 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003719 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003720 break;
3721 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003722 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003723 break;
3724 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003731 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003732 break;
3733
3734 case glslang::EOpIsNan:
3735 unaryOp = spv::OpIsNan;
3736 break;
3737 case glslang::EOpIsInf:
3738 unaryOp = spv::OpIsInf;
3739 break;
LoopDawg592860c2016-06-09 08:57:35 -06003740 case glslang::EOpIsFinite:
3741 unaryOp = spv::OpIsFinite;
3742 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003743
Rex Xucbc426e2015-12-15 16:03:10 +08003744 case glslang::EOpFloatBitsToInt:
3745 case glslang::EOpFloatBitsToUint:
3746 case glslang::EOpIntBitsToFloat:
3747 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003748 case glslang::EOpDoubleBitsToInt64:
3749 case glslang::EOpDoubleBitsToUint64:
3750 case glslang::EOpInt64BitsToDouble:
3751 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003752 unaryOp = spv::OpBitcast;
3753 break;
3754
John Kessenich140f3df2015-06-26 16:58:36 -06003755 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003756 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003757 break;
3758 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003759 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003760 break;
3761 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003762 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003763 break;
3764 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003765 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003766 break;
3767 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003768 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003769 break;
3770 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003773 case glslang::EOpPackSnorm4x8:
3774 libCall = spv::GLSLstd450PackSnorm4x8;
3775 break;
3776 case glslang::EOpUnpackSnorm4x8:
3777 libCall = spv::GLSLstd450UnpackSnorm4x8;
3778 break;
3779 case glslang::EOpPackUnorm4x8:
3780 libCall = spv::GLSLstd450PackUnorm4x8;
3781 break;
3782 case glslang::EOpUnpackUnorm4x8:
3783 libCall = spv::GLSLstd450UnpackUnorm4x8;
3784 break;
3785 case glslang::EOpPackDouble2x32:
3786 libCall = spv::GLSLstd450PackDouble2x32;
3787 break;
3788 case glslang::EOpUnpackDouble2x32:
3789 libCall = spv::GLSLstd450UnpackDouble2x32;
3790 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003791
Rex Xu8ff43de2016-04-22 16:51:45 +08003792 case glslang::EOpPackInt2x32:
3793 case glslang::EOpUnpackInt2x32:
3794 case glslang::EOpPackUint2x32:
3795 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003796 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003797 break;
3798
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003799#ifdef AMD_EXTENSIONS
3800 case glslang::EOpPackFloat2x16:
3801 case glslang::EOpUnpackFloat2x16:
3802 unaryOp = spv::OpBitcast;
3803 break;
3804#endif
3805
John Kessenich140f3df2015-06-26 16:58:36 -06003806 case glslang::EOpDPdx:
3807 unaryOp = spv::OpDPdx;
3808 break;
3809 case glslang::EOpDPdy:
3810 unaryOp = spv::OpDPdy;
3811 break;
3812 case glslang::EOpFwidth:
3813 unaryOp = spv::OpFwidth;
3814 break;
3815 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003816 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003817 unaryOp = spv::OpDPdxFine;
3818 break;
3819 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003820 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003821 unaryOp = spv::OpDPdyFine;
3822 break;
3823 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003824 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003825 unaryOp = spv::OpFwidthFine;
3826 break;
3827 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003828 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 unaryOp = spv::OpDPdxCoarse;
3830 break;
3831 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003832 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003833 unaryOp = spv::OpDPdyCoarse;
3834 break;
3835 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003836 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003837 unaryOp = spv::OpFwidthCoarse;
3838 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003839 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003840 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003841 libCall = spv::GLSLstd450InterpolateAtCentroid;
3842 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003843 case glslang::EOpAny:
3844 unaryOp = spv::OpAny;
3845 break;
3846 case glslang::EOpAll:
3847 unaryOp = spv::OpAll;
3848 break;
3849
3850 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003851 if (isFloat)
3852 libCall = spv::GLSLstd450FAbs;
3853 else
3854 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003855 break;
3856 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 if (isFloat)
3858 libCall = spv::GLSLstd450FSign;
3859 else
3860 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003861 break;
3862
John Kessenichfc51d282015-08-19 13:34:18 -06003863 case glslang::EOpAtomicCounterIncrement:
3864 case glslang::EOpAtomicCounterDecrement:
3865 case glslang::EOpAtomicCounter:
3866 {
3867 // Handle all of the atomics in one place, in createAtomicOperation()
3868 std::vector<spv::Id> operands;
3869 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003870 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003871 }
3872
John Kessenichfc51d282015-08-19 13:34:18 -06003873 case glslang::EOpBitFieldReverse:
3874 unaryOp = spv::OpBitReverse;
3875 break;
3876 case glslang::EOpBitCount:
3877 unaryOp = spv::OpBitCount;
3878 break;
3879 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003880 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003881 break;
3882 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003883 if (isUnsigned)
3884 libCall = spv::GLSLstd450FindUMsb;
3885 else
3886 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003887 break;
3888
Rex Xu574ab042016-04-14 16:53:07 +08003889 case glslang::EOpBallot:
3890 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003891 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003892 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003893 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003894#ifdef AMD_EXTENSIONS
3895 case glslang::EOpMinInvocations:
3896 case glslang::EOpMaxInvocations:
3897 case glslang::EOpAddInvocations:
3898 case glslang::EOpMinInvocationsNonUniform:
3899 case glslang::EOpMaxInvocationsNonUniform:
3900 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003901 case glslang::EOpMinInvocationsInclusiveScan:
3902 case glslang::EOpMaxInvocationsInclusiveScan:
3903 case glslang::EOpAddInvocationsInclusiveScan:
3904 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3905 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3906 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3907 case glslang::EOpMinInvocationsExclusiveScan:
3908 case glslang::EOpMaxInvocationsExclusiveScan:
3909 case glslang::EOpAddInvocationsExclusiveScan:
3910 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3911 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3912 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003913#endif
Rex Xu51596642016-09-21 18:56:12 +08003914 {
3915 std::vector<spv::Id> operands;
3916 operands.push_back(operand);
3917 return createInvocationsOperation(op, typeId, operands, typeProxy);
3918 }
Rex Xu9d93a232016-05-05 12:30:44 +08003919
3920#ifdef AMD_EXTENSIONS
3921 case glslang::EOpMbcnt:
3922 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3923 libCall = spv::MbcntAMD;
3924 break;
3925
3926 case glslang::EOpCubeFaceIndex:
3927 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3928 libCall = spv::CubeFaceIndexAMD;
3929 break;
3930
3931 case glslang::EOpCubeFaceCoord:
3932 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3933 libCall = spv::CubeFaceCoordAMD;
3934 break;
3935#endif
Rex Xu338b1852016-05-05 20:38:33 +08003936
John Kessenich140f3df2015-06-26 16:58:36 -06003937 default:
3938 return 0;
3939 }
3940
3941 spv::Id id;
3942 if (libCall >= 0) {
3943 std::vector<spv::Id> args;
3944 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003945 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003946 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003947 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003948 }
John Kessenich140f3df2015-06-26 16:58:36 -06003949
qining25262b32016-05-06 17:25:16 -04003950 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003951 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003952}
3953
John Kessenich7a53f762016-01-20 11:19:27 -07003954// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003955spv::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 -07003956{
3957 // Handle unary operations vector by vector.
3958 // The result type is the same type as the original type.
3959 // The algorithm is to:
3960 // - break the matrix into vectors
3961 // - apply the operation to each vector
3962 // - make a matrix out the vector results
3963
3964 // get the types sorted out
3965 int numCols = builder.getNumColumns(operand);
3966 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003967 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3968 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003969 std::vector<spv::Id> results;
3970
3971 // do each vector op
3972 for (int c = 0; c < numCols; ++c) {
3973 std::vector<unsigned int> indexes;
3974 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003975 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3976 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3977 addDecoration(destVec, noContraction);
3978 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003979 }
3980
3981 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003982 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003983}
3984
Rex Xu73e3ce72016-04-27 18:48:17 +08003985spv::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 -06003986{
3987 spv::Op convOp = spv::OpNop;
3988 spv::Id zero = 0;
3989 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003990 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003991
3992 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3993
3994 switch (op) {
3995 case glslang::EOpConvIntToBool:
3996 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003997 case glslang::EOpConvInt64ToBool:
3998 case glslang::EOpConvUint64ToBool:
3999 zero = (op == glslang::EOpConvInt64ToBool ||
4000 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004001 zero = makeSmearedConstant(zero, vectorSize);
4002 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4003
4004 case glslang::EOpConvFloatToBool:
4005 zero = builder.makeFloatConstant(0.0F);
4006 zero = makeSmearedConstant(zero, vectorSize);
4007 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4008
4009 case glslang::EOpConvDoubleToBool:
4010 zero = builder.makeDoubleConstant(0.0);
4011 zero = makeSmearedConstant(zero, vectorSize);
4012 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4013
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004014#ifdef AMD_EXTENSIONS
4015 case glslang::EOpConvFloat16ToBool:
4016 zero = builder.makeFloat16Constant(0.0F);
4017 zero = makeSmearedConstant(zero, vectorSize);
4018 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4019#endif
4020
John Kessenich140f3df2015-06-26 16:58:36 -06004021 case glslang::EOpConvBoolToFloat:
4022 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004023 zero = builder.makeFloatConstant(0.0F);
4024 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004025 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004026
John Kessenich140f3df2015-06-26 16:58:36 -06004027 case glslang::EOpConvBoolToDouble:
4028 convOp = spv::OpSelect;
4029 zero = builder.makeDoubleConstant(0.0);
4030 one = builder.makeDoubleConstant(1.0);
4031 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004032
4033#ifdef AMD_EXTENSIONS
4034 case glslang::EOpConvBoolToFloat16:
4035 convOp = spv::OpSelect;
4036 zero = builder.makeFloat16Constant(0.0F);
4037 one = builder.makeFloat16Constant(1.0F);
4038 break;
4039#endif
4040
John Kessenich140f3df2015-06-26 16:58:36 -06004041 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004042 case glslang::EOpConvBoolToInt64:
4043 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4044 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004045 convOp = spv::OpSelect;
4046 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004047
John Kessenich140f3df2015-06-26 16:58:36 -06004048 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004049 case glslang::EOpConvBoolToUint64:
4050 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4051 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004052 convOp = spv::OpSelect;
4053 break;
4054
4055 case glslang::EOpConvIntToFloat:
4056 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004057 case glslang::EOpConvInt64ToFloat:
4058 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004059#ifdef AMD_EXTENSIONS
4060 case glslang::EOpConvIntToFloat16:
4061 case glslang::EOpConvInt64ToFloat16:
4062#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004063 convOp = spv::OpConvertSToF;
4064 break;
4065
4066 case glslang::EOpConvUintToFloat:
4067 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004068 case glslang::EOpConvUint64ToFloat:
4069 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004070#ifdef AMD_EXTENSIONS
4071 case glslang::EOpConvUintToFloat16:
4072 case glslang::EOpConvUint64ToFloat16:
4073#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004074 convOp = spv::OpConvertUToF;
4075 break;
4076
4077 case glslang::EOpConvDoubleToFloat:
4078 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004079#ifdef AMD_EXTENSIONS
4080 case glslang::EOpConvDoubleToFloat16:
4081 case glslang::EOpConvFloat16ToDouble:
4082 case glslang::EOpConvFloatToFloat16:
4083 case glslang::EOpConvFloat16ToFloat:
4084#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004085 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004086 if (builder.isMatrixType(destType))
4087 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089
4090 case glslang::EOpConvFloatToInt:
4091 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004092 case glslang::EOpConvFloatToInt64:
4093 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004094#ifdef AMD_EXTENSIONS
4095 case glslang::EOpConvFloat16ToInt:
4096 case glslang::EOpConvFloat16ToInt64:
4097#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004098 convOp = spv::OpConvertFToS;
4099 break;
4100
4101 case glslang::EOpConvUintToInt:
4102 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004103 case glslang::EOpConvUint64ToInt64:
4104 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004105 if (builder.isInSpecConstCodeGenMode()) {
4106 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004107 zero = (op == glslang::EOpConvUint64ToInt64 ||
4108 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004109 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004110 // Use OpIAdd, instead of OpBitcast to do the conversion when
4111 // generating for OpSpecConstantOp instruction.
4112 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4113 }
4114 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004115 convOp = spv::OpBitcast;
4116 break;
4117
4118 case glslang::EOpConvFloatToUint:
4119 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004120 case glslang::EOpConvFloatToUint64:
4121 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004122#ifdef AMD_EXTENSIONS
4123 case glslang::EOpConvFloat16ToUint:
4124 case glslang::EOpConvFloat16ToUint64:
4125#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004126 convOp = spv::OpConvertFToU;
4127 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004128
4129 case glslang::EOpConvIntToInt64:
4130 case glslang::EOpConvInt64ToInt:
4131 convOp = spv::OpSConvert;
4132 break;
4133
4134 case glslang::EOpConvUintToUint64:
4135 case glslang::EOpConvUint64ToUint:
4136 convOp = spv::OpUConvert;
4137 break;
4138
4139 case glslang::EOpConvIntToUint64:
4140 case glslang::EOpConvInt64ToUint:
4141 case glslang::EOpConvUint64ToInt:
4142 case glslang::EOpConvUintToInt64:
4143 // OpSConvert/OpUConvert + OpBitCast
4144 switch (op) {
4145 case glslang::EOpConvIntToUint64:
4146 convOp = spv::OpSConvert;
4147 type = builder.makeIntType(64);
4148 break;
4149 case glslang::EOpConvInt64ToUint:
4150 convOp = spv::OpSConvert;
4151 type = builder.makeIntType(32);
4152 break;
4153 case glslang::EOpConvUint64ToInt:
4154 convOp = spv::OpUConvert;
4155 type = builder.makeUintType(32);
4156 break;
4157 case glslang::EOpConvUintToInt64:
4158 convOp = spv::OpUConvert;
4159 type = builder.makeUintType(64);
4160 break;
4161 default:
4162 assert(0);
4163 break;
4164 }
4165
4166 if (vectorSize > 0)
4167 type = builder.makeVectorType(type, vectorSize);
4168
4169 operand = builder.createUnaryOp(convOp, type, operand);
4170
4171 if (builder.isInSpecConstCodeGenMode()) {
4172 // Build zero scalar or vector for OpIAdd.
4173 zero = (op == glslang::EOpConvIntToUint64 ||
4174 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4175 zero = makeSmearedConstant(zero, vectorSize);
4176 // Use OpIAdd, instead of OpBitcast to do the conversion when
4177 // generating for OpSpecConstantOp instruction.
4178 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4179 }
4180 // For normal run-time conversion instruction, use OpBitcast.
4181 convOp = spv::OpBitcast;
4182 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004183 default:
4184 break;
4185 }
4186
4187 spv::Id result = 0;
4188 if (convOp == spv::OpNop)
4189 return result;
4190
4191 if (convOp == spv::OpSelect) {
4192 zero = makeSmearedConstant(zero, vectorSize);
4193 one = makeSmearedConstant(one, vectorSize);
4194 result = builder.createTriOp(convOp, destType, operand, one, zero);
4195 } else
4196 result = builder.createUnaryOp(convOp, destType, operand);
4197
John Kessenich32cfd492016-02-02 12:37:46 -07004198 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004199}
4200
4201spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4202{
4203 if (vectorSize == 0)
4204 return constant;
4205
4206 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4207 std::vector<spv::Id> components;
4208 for (int c = 0; c < vectorSize; ++c)
4209 components.push_back(constant);
4210 return builder.makeCompositeConstant(vectorTypeId, components);
4211}
4212
John Kessenich426394d2015-07-23 10:22:48 -06004213// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004214spv::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 -06004215{
4216 spv::Op opCode = spv::OpNop;
4217
4218 switch (op) {
4219 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004220 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004221 opCode = spv::OpAtomicIAdd;
4222 break;
4223 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004224 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004225 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004226 break;
4227 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004228 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004229 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004230 break;
4231 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004232 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004233 opCode = spv::OpAtomicAnd;
4234 break;
4235 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004236 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004237 opCode = spv::OpAtomicOr;
4238 break;
4239 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004240 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004241 opCode = spv::OpAtomicXor;
4242 break;
4243 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004244 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004245 opCode = spv::OpAtomicExchange;
4246 break;
4247 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004248 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004249 opCode = spv::OpAtomicCompareExchange;
4250 break;
4251 case glslang::EOpAtomicCounterIncrement:
4252 opCode = spv::OpAtomicIIncrement;
4253 break;
4254 case glslang::EOpAtomicCounterDecrement:
4255 opCode = spv::OpAtomicIDecrement;
4256 break;
4257 case glslang::EOpAtomicCounter:
4258 opCode = spv::OpAtomicLoad;
4259 break;
4260 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004261 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004262 break;
4263 }
4264
4265 // Sort out the operands
4266 // - mapping from glslang -> SPV
4267 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004268 // - compare-exchange swaps the value and comparator
4269 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004270 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4271 auto opIt = operands.begin(); // walk the glslang operands
4272 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004273 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4274 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4275 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004276 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4277 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004278 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004279 spvAtomicOperands.push_back(*(opIt + 1));
4280 spvAtomicOperands.push_back(*opIt);
4281 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004282 }
John Kessenich426394d2015-07-23 10:22:48 -06004283
John Kessenich3e60a6f2015-09-14 22:45:16 -06004284 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004285 for (; opIt != operands.end(); ++opIt)
4286 spvAtomicOperands.push_back(*opIt);
4287
4288 return builder.createOp(opCode, typeId, spvAtomicOperands);
4289}
4290
John Kessenich91cef522016-05-05 16:45:40 -06004291// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004292spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004293{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004294#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004295 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004296 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004297#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004298
Rex Xu51596642016-09-21 18:56:12 +08004299 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004300 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004301 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4302
chaocf200da82016-12-20 12:44:35 -08004303 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4304 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004305 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4306 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004307 } else if (op == glslang::EOpAnyInvocation ||
4308 op == glslang::EOpAllInvocations ||
4309 op == glslang::EOpAllInvocationsEqual) {
4310 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4311 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004312 } else {
4313 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004314#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004315 if (op == glslang::EOpMinInvocationsNonUniform ||
4316 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004317 op == glslang::EOpAddInvocationsNonUniform ||
4318 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4319 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4320 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4321 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4322 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4323 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004324 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004325#endif
Rex Xu51596642016-09-21 18:56:12 +08004326
4327 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004328#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004329 switch (op) {
4330 case glslang::EOpMinInvocations:
4331 case glslang::EOpMaxInvocations:
4332 case glslang::EOpAddInvocations:
4333 case glslang::EOpMinInvocationsNonUniform:
4334 case glslang::EOpMaxInvocationsNonUniform:
4335 case glslang::EOpAddInvocationsNonUniform:
4336 groupOperation = spv::GroupOperationReduce;
4337 spvGroupOperands.push_back(groupOperation);
4338 break;
4339 case glslang::EOpMinInvocationsInclusiveScan:
4340 case glslang::EOpMaxInvocationsInclusiveScan:
4341 case glslang::EOpAddInvocationsInclusiveScan:
4342 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4343 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4344 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4345 groupOperation = spv::GroupOperationInclusiveScan;
4346 spvGroupOperands.push_back(groupOperation);
4347 break;
4348 case glslang::EOpMinInvocationsExclusiveScan:
4349 case glslang::EOpMaxInvocationsExclusiveScan:
4350 case glslang::EOpAddInvocationsExclusiveScan:
4351 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4352 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4353 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4354 groupOperation = spv::GroupOperationExclusiveScan;
4355 spvGroupOperands.push_back(groupOperation);
4356 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004357 default:
4358 break;
Rex Xu430ef402016-10-14 17:22:23 +08004359 }
Rex Xu9d93a232016-05-05 12:30:44 +08004360#endif
Rex Xu51596642016-09-21 18:56:12 +08004361 }
4362
4363 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4364 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004365
4366 switch (op) {
4367 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004368 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004369 break;
John Kessenich91cef522016-05-05 16:45:40 -06004370 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004371 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004372 break;
John Kessenich91cef522016-05-05 16:45:40 -06004373 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004374 opCode = spv::OpSubgroupAllEqualKHR;
4375 break;
Rex Xu51596642016-09-21 18:56:12 +08004376 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004377 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004378 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004379 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004380 break;
4381 case glslang::EOpReadFirstInvocation:
4382 opCode = spv::OpSubgroupFirstInvocationKHR;
4383 break;
4384 case glslang::EOpBallot:
4385 {
4386 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4387 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4388 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4389 //
4390 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4391 //
4392 spv::Id uintType = builder.makeUintType(32);
4393 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4394 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4395
4396 std::vector<spv::Id> components;
4397 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4398 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4399
4400 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4401 return builder.createUnaryOp(spv::OpBitcast, typeId,
4402 builder.createCompositeConstruct(uvec2Type, components));
4403 }
4404
Rex Xu9d93a232016-05-05 12:30:44 +08004405#ifdef AMD_EXTENSIONS
4406 case glslang::EOpMinInvocations:
4407 case glslang::EOpMaxInvocations:
4408 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004409 case glslang::EOpMinInvocationsInclusiveScan:
4410 case glslang::EOpMaxInvocationsInclusiveScan:
4411 case glslang::EOpAddInvocationsInclusiveScan:
4412 case glslang::EOpMinInvocationsExclusiveScan:
4413 case glslang::EOpMaxInvocationsExclusiveScan:
4414 case glslang::EOpAddInvocationsExclusiveScan:
4415 if (op == glslang::EOpMinInvocations ||
4416 op == glslang::EOpMinInvocationsInclusiveScan ||
4417 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004418 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004419 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004420 else {
4421 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004422 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004423 else
Rex Xu51596642016-09-21 18:56:12 +08004424 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004425 }
Rex Xu430ef402016-10-14 17:22:23 +08004426 } else if (op == glslang::EOpMaxInvocations ||
4427 op == glslang::EOpMaxInvocationsInclusiveScan ||
4428 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004429 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004430 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004431 else {
4432 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004433 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004434 else
Rex Xu51596642016-09-21 18:56:12 +08004435 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004436 }
4437 } else {
4438 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004439 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004440 else
Rex Xu51596642016-09-21 18:56:12 +08004441 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004442 }
4443
Rex Xu2bbbe062016-08-23 15:41:05 +08004444 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004445 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004446
4447 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004448 case glslang::EOpMinInvocationsNonUniform:
4449 case glslang::EOpMaxInvocationsNonUniform:
4450 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004451 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4452 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4453 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4454 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4455 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4456 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4457 if (op == glslang::EOpMinInvocationsNonUniform ||
4458 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4459 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004460 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004461 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004462 else {
4463 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004464 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004465 else
Rex Xu51596642016-09-21 18:56:12 +08004466 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004467 }
4468 }
Rex Xu430ef402016-10-14 17:22:23 +08004469 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4470 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4471 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004472 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004473 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004474 else {
4475 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004476 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004477 else
Rex Xu51596642016-09-21 18:56:12 +08004478 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004479 }
4480 }
4481 else {
4482 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004483 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004484 else
Rex Xu51596642016-09-21 18:56:12 +08004485 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004486 }
4487
Rex Xu2bbbe062016-08-23 15:41:05 +08004488 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004489 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004490
4491 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004492#endif
John Kessenich91cef522016-05-05 16:45:40 -06004493 default:
4494 logger->missingFunctionality("invocation operation");
4495 return spv::NoResult;
4496 }
Rex Xu51596642016-09-21 18:56:12 +08004497
4498 assert(opCode != spv::OpNop);
4499 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004500}
4501
Rex Xu2bbbe062016-08-23 15:41:05 +08004502// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004503spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004504{
Rex Xub7072052016-09-26 15:53:40 +08004505#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004506 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4507 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004508 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004509 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004510 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4511 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4512 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004513#else
4514 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4515 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004516 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4517 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004518#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004519
4520 // Handle group invocation operations scalar by scalar.
4521 // The result type is the same type as the original type.
4522 // The algorithm is to:
4523 // - break the vector into scalars
4524 // - apply the operation to each scalar
4525 // - make a vector out the scalar results
4526
4527 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004528 int numComponents = builder.getNumComponents(operands[0]);
4529 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004530 std::vector<spv::Id> results;
4531
4532 // do each scalar op
4533 for (int comp = 0; comp < numComponents; ++comp) {
4534 std::vector<unsigned int> indexes;
4535 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004536 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004537 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004538 if (op == spv::OpSubgroupReadInvocationKHR) {
4539 spvGroupOperands.push_back(scalar);
4540 spvGroupOperands.push_back(operands[1]);
4541 } else if (op == spv::OpGroupBroadcast) {
4542 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004543 spvGroupOperands.push_back(scalar);
4544 spvGroupOperands.push_back(operands[1]);
4545 } else {
chaocf200da82016-12-20 12:44:35 -08004546 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004547 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004548 spvGroupOperands.push_back(scalar);
4549 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004550
Rex Xub7072052016-09-26 15:53:40 +08004551 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004552 }
4553
4554 // put the pieces together
4555 return builder.createCompositeConstruct(typeId, results);
4556}
Rex Xu2bbbe062016-08-23 15:41:05 +08004557
John Kessenich5e4b1242015-08-06 22:53:06 -06004558spv::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 -06004559{
Rex Xu8ff43de2016-04-22 16:51:45 +08004560 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004561#ifdef AMD_EXTENSIONS
4562 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4563#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004564 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004565#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004566
John Kessenich140f3df2015-06-26 16:58:36 -06004567 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004568 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004569 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004570 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004571 spv::Id typeId0 = 0;
4572 if (consumedOperands > 0)
4573 typeId0 = builder.getTypeId(operands[0]);
4574 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004575
4576 switch (op) {
4577 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004578 if (isFloat)
4579 libCall = spv::GLSLstd450FMin;
4580 else if (isUnsigned)
4581 libCall = spv::GLSLstd450UMin;
4582 else
4583 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004584 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004585 break;
4586 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004587 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004588 break;
4589 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004590 if (isFloat)
4591 libCall = spv::GLSLstd450FMax;
4592 else if (isUnsigned)
4593 libCall = spv::GLSLstd450UMax;
4594 else
4595 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004596 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004597 break;
4598 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004599 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004600 break;
4601 case glslang::EOpDot:
4602 opCode = spv::OpDot;
4603 break;
4604 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004605 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004606 break;
4607
4608 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004609 if (isFloat)
4610 libCall = spv::GLSLstd450FClamp;
4611 else if (isUnsigned)
4612 libCall = spv::GLSLstd450UClamp;
4613 else
4614 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004615 builder.promoteScalar(precision, operands.front(), operands[1]);
4616 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004617 break;
4618 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004619 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4620 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004621 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004622 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004623 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004624 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004625 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004626 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004627 break;
4628 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004629 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004630 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004631 break;
4632 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004633 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004634 builder.promoteScalar(precision, operands[0], operands[2]);
4635 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004636 break;
4637
4638 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004639 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004640 break;
4641 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004642 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004643 break;
4644 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004645 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004646 break;
4647 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004648 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004649 break;
4650 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004651 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004652 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004653 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004654 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004655 libCall = spv::GLSLstd450InterpolateAtSample;
4656 break;
4657 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004658 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004659 libCall = spv::GLSLstd450InterpolateAtOffset;
4660 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004661 case glslang::EOpAddCarry:
4662 opCode = spv::OpIAddCarry;
4663 typeId = builder.makeStructResultType(typeId0, typeId0);
4664 consumedOperands = 2;
4665 break;
4666 case glslang::EOpSubBorrow:
4667 opCode = spv::OpISubBorrow;
4668 typeId = builder.makeStructResultType(typeId0, typeId0);
4669 consumedOperands = 2;
4670 break;
4671 case glslang::EOpUMulExtended:
4672 opCode = spv::OpUMulExtended;
4673 typeId = builder.makeStructResultType(typeId0, typeId0);
4674 consumedOperands = 2;
4675 break;
4676 case glslang::EOpIMulExtended:
4677 opCode = spv::OpSMulExtended;
4678 typeId = builder.makeStructResultType(typeId0, typeId0);
4679 consumedOperands = 2;
4680 break;
4681 case glslang::EOpBitfieldExtract:
4682 if (isUnsigned)
4683 opCode = spv::OpBitFieldUExtract;
4684 else
4685 opCode = spv::OpBitFieldSExtract;
4686 break;
4687 case glslang::EOpBitfieldInsert:
4688 opCode = spv::OpBitFieldInsert;
4689 break;
4690
4691 case glslang::EOpFma:
4692 libCall = spv::GLSLstd450Fma;
4693 break;
4694 case glslang::EOpFrexp:
4695 libCall = spv::GLSLstd450FrexpStruct;
4696 if (builder.getNumComponents(operands[0]) == 1)
4697 frexpIntType = builder.makeIntegerType(32, true);
4698 else
4699 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4700 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4701 consumedOperands = 1;
4702 break;
4703 case glslang::EOpLdexp:
4704 libCall = spv::GLSLstd450Ldexp;
4705 break;
4706
Rex Xu574ab042016-04-14 16:53:07 +08004707 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004708 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004709
Rex Xu9d93a232016-05-05 12:30:44 +08004710#ifdef AMD_EXTENSIONS
4711 case glslang::EOpSwizzleInvocations:
4712 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4713 libCall = spv::SwizzleInvocationsAMD;
4714 break;
4715 case glslang::EOpSwizzleInvocationsMasked:
4716 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4717 libCall = spv::SwizzleInvocationsMaskedAMD;
4718 break;
4719 case glslang::EOpWriteInvocation:
4720 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4721 libCall = spv::WriteInvocationAMD;
4722 break;
4723
4724 case glslang::EOpMin3:
4725 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4726 if (isFloat)
4727 libCall = spv::FMin3AMD;
4728 else {
4729 if (isUnsigned)
4730 libCall = spv::UMin3AMD;
4731 else
4732 libCall = spv::SMin3AMD;
4733 }
4734 break;
4735 case glslang::EOpMax3:
4736 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4737 if (isFloat)
4738 libCall = spv::FMax3AMD;
4739 else {
4740 if (isUnsigned)
4741 libCall = spv::UMax3AMD;
4742 else
4743 libCall = spv::SMax3AMD;
4744 }
4745 break;
4746 case glslang::EOpMid3:
4747 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4748 if (isFloat)
4749 libCall = spv::FMid3AMD;
4750 else {
4751 if (isUnsigned)
4752 libCall = spv::UMid3AMD;
4753 else
4754 libCall = spv::SMid3AMD;
4755 }
4756 break;
4757
4758 case glslang::EOpInterpolateAtVertex:
4759 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4760 libCall = spv::InterpolateAtVertexAMD;
4761 break;
4762#endif
4763
John Kessenich140f3df2015-06-26 16:58:36 -06004764 default:
4765 return 0;
4766 }
4767
4768 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004769 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004770 // Use an extended instruction from the standard library.
4771 // Construct the call arguments, without modifying the original operands vector.
4772 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4773 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004774 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004775 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004776 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004777 case 0:
4778 // should all be handled by visitAggregate and createNoArgOperation
4779 assert(0);
4780 return 0;
4781 case 1:
4782 // should all be handled by createUnaryOperation
4783 assert(0);
4784 return 0;
4785 case 2:
4786 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4787 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004788 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004789 // anything 3 or over doesn't have l-value operands, so all should be consumed
4790 assert(consumedOperands == operands.size());
4791 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004792 break;
4793 }
4794 }
4795
John Kessenich55e7d112015-11-15 21:33:39 -07004796 // Decode the return types that were structures
4797 switch (op) {
4798 case glslang::EOpAddCarry:
4799 case glslang::EOpSubBorrow:
4800 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4801 id = builder.createCompositeExtract(id, typeId0, 0);
4802 break;
4803 case glslang::EOpUMulExtended:
4804 case glslang::EOpIMulExtended:
4805 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4806 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4807 break;
4808 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004809 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004810 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4811 id = builder.createCompositeExtract(id, typeId0, 0);
4812 break;
4813 default:
4814 break;
4815 }
4816
John Kessenich32cfd492016-02-02 12:37:46 -07004817 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004818}
4819
Rex Xu9d93a232016-05-05 12:30:44 +08004820// Intrinsics with no arguments (or no return value, and no precision).
4821spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004822{
4823 // TODO: get the barrier operands correct
4824
4825 switch (op) {
4826 case glslang::EOpEmitVertex:
4827 builder.createNoResultOp(spv::OpEmitVertex);
4828 return 0;
4829 case glslang::EOpEndPrimitive:
4830 builder.createNoResultOp(spv::OpEndPrimitive);
4831 return 0;
4832 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004833 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004834 return 0;
4835 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004836 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004837 return 0;
4838 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004839 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004840 return 0;
4841 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004842 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004843 return 0;
4844 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004845 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004846 return 0;
4847 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004848 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004849 return 0;
4850 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004851 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004852 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004853 case glslang::EOpAllMemoryBarrierWithGroupSync:
4854 // Control barrier with non-"None" semantic is also a memory barrier.
4855 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4856 return 0;
4857 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4858 // Control barrier with non-"None" semantic is also a memory barrier.
4859 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4860 return 0;
4861 case glslang::EOpWorkgroupMemoryBarrier:
4862 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4863 return 0;
4864 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4865 // Control barrier with non-"None" semantic is also a memory barrier.
4866 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4867 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004868#ifdef AMD_EXTENSIONS
4869 case glslang::EOpTime:
4870 {
4871 std::vector<spv::Id> args; // Dummy arguments
4872 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4873 return builder.setPrecision(id, precision);
4874 }
4875#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004876 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004877 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004878 return 0;
4879 }
4880}
4881
4882spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4883{
John Kessenich2f273362015-07-18 22:34:27 -06004884 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004885 spv::Id id;
4886 if (symbolValues.end() != iter) {
4887 id = iter->second;
4888 return id;
4889 }
4890
4891 // it was not found, create it
4892 id = createSpvVariable(symbol);
4893 symbolValues[symbol->getId()] = id;
4894
Rex Xuc884b4a2016-06-29 15:03:44 +08004895 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004896 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004897 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004898 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004899 if (symbol->getType().getQualifier().hasSpecConstantId())
4900 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004901 if (symbol->getQualifier().hasIndex())
4902 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4903 if (symbol->getQualifier().hasComponent())
4904 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4905 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004906 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004907 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004908 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004909 if (symbol->getQualifier().hasXfbBuffer())
4910 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4911 if (symbol->getQualifier().hasXfbOffset())
4912 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4913 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004914 // atomic counters use this:
4915 if (symbol->getQualifier().hasOffset())
4916 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004917 }
4918
scygan2c864272016-05-18 18:09:17 +02004919 if (symbol->getQualifier().hasLocation())
4920 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004921 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004922 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004923 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004924 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004925 }
John Kessenich140f3df2015-06-26 16:58:36 -06004926 if (symbol->getQualifier().hasSet())
4927 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004928 else if (IsDescriptorResource(symbol->getType())) {
4929 // default to 0
4930 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4931 }
John Kessenich140f3df2015-06-26 16:58:36 -06004932 if (symbol->getQualifier().hasBinding())
4933 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004934 if (symbol->getQualifier().hasAttachment())
4935 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004936 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004937 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004938 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004939 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004940 if (symbol->getQualifier().hasXfbBuffer())
4941 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4942 }
4943
Rex Xu1da878f2016-02-21 20:59:01 +08004944 if (symbol->getType().isImage()) {
4945 std::vector<spv::Decoration> memory;
4946 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4947 for (unsigned int i = 0; i < memory.size(); ++i)
4948 addDecoration(id, memory[i]);
4949 }
4950
John Kessenich140f3df2015-06-26 16:58:36 -06004951 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004952 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004953 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004954 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004955
John Kessenichecba76f2017-01-06 00:34:48 -07004956#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004957 if (builtIn == spv::BuiltInSampleMask) {
4958 spv::Decoration decoration;
4959 // GL_NV_sample_mask_override_coverage extension
4960 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004961 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004962 else
4963 decoration = (spv::Decoration)spv::DecorationMax;
4964 addDecoration(id, decoration);
4965 if (decoration != spv::DecorationMax) {
4966 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4967 }
4968 }
chaoc771d89f2017-01-13 01:10:53 -08004969 else if (builtIn == spv::BuiltInLayer) {
4970 // SPV_NV_viewport_array2 extension
4971 if (symbol->getQualifier().layoutViewportRelative)
4972 {
4973 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4974 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4975 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4976 }
4977 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4978 {
4979 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4980 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4981 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4982 }
4983 }
4984
chaoc6e5acae2016-12-20 13:28:52 -08004985 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004986 addDecoration(id, spv::DecorationPassthroughNV);
4987 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004988 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4989 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004990#endif
4991
John Kessenich140f3df2015-06-26 16:58:36 -06004992 return id;
4993}
4994
John Kessenich55e7d112015-11-15 21:33:39 -07004995// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004996void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4997{
John Kessenich4016e382016-07-15 11:53:56 -06004998 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004999 builder.addDecoration(id, dec);
5000}
5001
John Kessenich55e7d112015-11-15 21:33:39 -07005002// If 'dec' is valid, add a one-operand decoration to an object
5003void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5004{
John Kessenich4016e382016-07-15 11:53:56 -06005005 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005006 builder.addDecoration(id, dec, value);
5007}
5008
5009// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005010void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5011{
John Kessenich4016e382016-07-15 11:53:56 -06005012 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005013 builder.addMemberDecoration(id, (unsigned)member, dec);
5014}
5015
John Kessenich92187592016-02-01 13:45:25 -07005016// If 'dec' is valid, add a one-operand decoration to a struct member
5017void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5018{
John Kessenich4016e382016-07-15 11:53:56 -06005019 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005020 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5021}
5022
John Kessenich55e7d112015-11-15 21:33:39 -07005023// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005024// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005025//
5026// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5027//
5028// Recursively walk the nodes. The nodes form a tree whose leaves are
5029// regular constants, which themselves are trees that createSpvConstant()
5030// recursively walks. So, this function walks the "top" of the tree:
5031// - emit specialization constant-building instructions for specConstant
5032// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005033spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005034{
John Kessenich7cc0e282016-03-20 00:46:02 -06005035 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005036
qining4f4bb812016-04-03 23:55:17 -04005037 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005038 if (! node.getQualifier().specConstant) {
5039 // hand off to the non-spec-constant path
5040 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5041 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005042 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005043 nextConst, false);
5044 }
5045
5046 // We now know we have a specialization constant to build
5047
John Kessenichd94c0032016-05-30 19:29:40 -06005048 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005049 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5050 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5051 std::vector<spv::Id> dimConstId;
5052 for (int dim = 0; dim < 3; ++dim) {
5053 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5054 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5055 if (specConst)
5056 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5057 }
5058 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5059 }
5060
5061 // An AST node labelled as specialization constant should be a symbol node.
5062 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5063 if (auto* sn = node.getAsSymbolNode()) {
5064 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005065 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5066 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5067 // will set the builder into spec constant op instruction generating mode.
5068 sub_tree->traverse(this);
5069 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005070 } else if (auto* const_union_array = &sn->getConstArray()){
5071 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005072 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5073 builder.addName(id, sn->getName().c_str());
5074 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005075 }
5076 }
qining4f4bb812016-04-03 23:55:17 -04005077
5078 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5079 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005080 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005081 exit(1);
5082 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005083}
5084
John Kessenich140f3df2015-06-26 16:58:36 -06005085// Use 'consts' as the flattened glslang source of scalar constants to recursively
5086// build the aggregate SPIR-V constant.
5087//
5088// If there are not enough elements present in 'consts', 0 will be substituted;
5089// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5090//
qining08408382016-03-21 09:51:37 -04005091spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005092{
5093 // vector of constants for SPIR-V
5094 std::vector<spv::Id> spvConsts;
5095
5096 // Type is used for struct and array constants
5097 spv::Id typeId = convertGlslangToSpvType(glslangType);
5098
5099 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005100 glslang::TType elementType(glslangType, 0);
5101 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005102 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005103 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005104 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005105 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005106 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005107 } else if (glslangType.getStruct()) {
5108 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5109 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005110 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005111 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005112 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5113 bool zero = nextConst >= consts.size();
5114 switch (glslangType.getBasicType()) {
5115 case glslang::EbtInt:
5116 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5117 break;
5118 case glslang::EbtUint:
5119 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5120 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005121 case glslang::EbtInt64:
5122 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5123 break;
5124 case glslang::EbtUint64:
5125 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5126 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005127 case glslang::EbtFloat:
5128 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5129 break;
5130 case glslang::EbtDouble:
5131 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5132 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005133#ifdef AMD_EXTENSIONS
5134 case glslang::EbtFloat16:
5135 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5136 break;
5137#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005138 case glslang::EbtBool:
5139 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5140 break;
5141 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005142 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005143 break;
5144 }
5145 ++nextConst;
5146 }
5147 } else {
5148 // we have a non-aggregate (scalar) constant
5149 bool zero = nextConst >= consts.size();
5150 spv::Id scalar = 0;
5151 switch (glslangType.getBasicType()) {
5152 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005153 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005154 break;
5155 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005156 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005157 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005158 case glslang::EbtInt64:
5159 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5160 break;
5161 case glslang::EbtUint64:
5162 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5163 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005164 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005165 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005166 break;
5167 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005168 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005169 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005170#ifdef AMD_EXTENSIONS
5171 case glslang::EbtFloat16:
5172 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5173 break;
5174#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005175 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005176 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005177 break;
5178 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005179 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005180 break;
5181 }
5182 ++nextConst;
5183 return scalar;
5184 }
5185
5186 return builder.makeCompositeConstant(typeId, spvConsts);
5187}
5188
John Kessenich7c1aa102015-10-15 13:29:11 -06005189// Return true if the node is a constant or symbol whose reading has no
5190// non-trivial observable cost or effect.
5191bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5192{
5193 // don't know what this is
5194 if (node == nullptr)
5195 return false;
5196
5197 // a constant is safe
5198 if (node->getAsConstantUnion() != nullptr)
5199 return true;
5200
5201 // not a symbol means non-trivial
5202 if (node->getAsSymbolNode() == nullptr)
5203 return false;
5204
5205 // a symbol, depends on what's being read
5206 switch (node->getType().getQualifier().storage) {
5207 case glslang::EvqTemporary:
5208 case glslang::EvqGlobal:
5209 case glslang::EvqIn:
5210 case glslang::EvqInOut:
5211 case glslang::EvqConst:
5212 case glslang::EvqConstReadOnly:
5213 case glslang::EvqUniform:
5214 return true;
5215 default:
5216 return false;
5217 }
qining25262b32016-05-06 17:25:16 -04005218}
John Kessenich7c1aa102015-10-15 13:29:11 -06005219
5220// A node is trivial if it is a single operation with no side effects.
5221// Error on the side of saying non-trivial.
5222// Return true if trivial.
5223bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5224{
5225 if (node == nullptr)
5226 return false;
5227
5228 // symbols and constants are trivial
5229 if (isTrivialLeaf(node))
5230 return true;
5231
5232 // otherwise, it needs to be a simple operation or one or two leaf nodes
5233
5234 // not a simple operation
5235 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5236 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5237 if (binaryNode == nullptr && unaryNode == nullptr)
5238 return false;
5239
5240 // not on leaf nodes
5241 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5242 return false;
5243
5244 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5245 return false;
5246 }
5247
5248 switch (node->getAsOperator()->getOp()) {
5249 case glslang::EOpLogicalNot:
5250 case glslang::EOpConvIntToBool:
5251 case glslang::EOpConvUintToBool:
5252 case glslang::EOpConvFloatToBool:
5253 case glslang::EOpConvDoubleToBool:
5254 case glslang::EOpEqual:
5255 case glslang::EOpNotEqual:
5256 case glslang::EOpLessThan:
5257 case glslang::EOpGreaterThan:
5258 case glslang::EOpLessThanEqual:
5259 case glslang::EOpGreaterThanEqual:
5260 case glslang::EOpIndexDirect:
5261 case glslang::EOpIndexDirectStruct:
5262 case glslang::EOpLogicalXor:
5263 case glslang::EOpAny:
5264 case glslang::EOpAll:
5265 return true;
5266 default:
5267 return false;
5268 }
5269}
5270
5271// Emit short-circuiting code, where 'right' is never evaluated unless
5272// the left side is true (for &&) or false (for ||).
5273spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5274{
5275 spv::Id boolTypeId = builder.makeBoolType();
5276
5277 // emit left operand
5278 builder.clearAccessChain();
5279 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005280 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005281
5282 // Operands to accumulate OpPhi operands
5283 std::vector<spv::Id> phiOperands;
5284 // accumulate left operand's phi information
5285 phiOperands.push_back(leftId);
5286 phiOperands.push_back(builder.getBuildPoint()->getId());
5287
5288 // Make the two kinds of operation symmetric with a "!"
5289 // || => emit "if (! left) result = right"
5290 // && => emit "if ( left) result = right"
5291 //
5292 // TODO: this runtime "not" for || could be avoided by adding functionality
5293 // to 'builder' to have an "else" without an "then"
5294 if (op == glslang::EOpLogicalOr)
5295 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5296
5297 // make an "if" based on the left value
5298 spv::Builder::If ifBuilder(leftId, builder);
5299
5300 // emit right operand as the "then" part of the "if"
5301 builder.clearAccessChain();
5302 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005303 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005304
5305 // accumulate left operand's phi information
5306 phiOperands.push_back(rightId);
5307 phiOperands.push_back(builder.getBuildPoint()->getId());
5308
5309 // finish the "if"
5310 ifBuilder.makeEndIf();
5311
5312 // phi together the two results
5313 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5314}
5315
Rex Xu9d93a232016-05-05 12:30:44 +08005316// Return type Id of the imported set of extended instructions corresponds to the name.
5317// Import this set if it has not been imported yet.
5318spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5319{
5320 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5321 return extBuiltinMap[name];
5322 else {
Rex Xu51596642016-09-21 18:56:12 +08005323 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005324 spv::Id extBuiltins = builder.import(name);
5325 extBuiltinMap[name] = extBuiltins;
5326 return extBuiltins;
5327 }
5328}
5329
John Kessenich140f3df2015-06-26 16:58:36 -06005330}; // end anonymous namespace
5331
5332namespace glslang {
5333
John Kessenich68d78fd2015-07-12 19:28:10 -06005334void GetSpirvVersion(std::string& version)
5335{
John Kessenich9e55f632015-07-15 10:03:39 -06005336 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005337 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005338 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005339 version = buf;
5340}
5341
John Kessenich140f3df2015-06-26 16:58:36 -06005342// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005343void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005344{
5345 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005346 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005347 if (out.fail())
5348 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005349 for (int i = 0; i < (int)spirv.size(); ++i) {
5350 unsigned int word = spirv[i];
5351 out.write((const char*)&word, 4);
5352 }
5353 out.close();
5354}
5355
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005356// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005357void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005358{
5359 std::ofstream out;
5360 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005361 if (out.fail())
5362 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005363 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005364 if (varName != nullptr) {
5365 out << "\t #pragma once" << std::endl;
5366 out << "const uint32_t " << varName << "[] = {" << std::endl;
5367 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005368 const int WORDS_PER_LINE = 8;
5369 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5370 out << "\t";
5371 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5372 const unsigned int word = spirv[i + j];
5373 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5374 if (i + j + 1 < (int)spirv.size()) {
5375 out << ",";
5376 }
5377 }
5378 out << std::endl;
5379 }
Flavio15017db2017-02-15 14:29:33 -08005380 if (varName != nullptr) {
5381 out << "};";
5382 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005383 out.close();
5384}
5385
John Kessenich140f3df2015-06-26 16:58:36 -06005386//
5387// Set up the glslang traversal
5388//
5389void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5390{
Lei Zhang17535f72016-05-04 15:55:59 -04005391 spv::SpvBuildLogger logger;
5392 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005393}
5394
Lei Zhang17535f72016-05-04 15:55:59 -04005395void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005396{
John Kessenich140f3df2015-06-26 16:58:36 -06005397 TIntermNode* root = intermediate.getTreeRoot();
5398
5399 if (root == 0)
5400 return;
5401
5402 glslang::GetThreadPoolAllocator().push();
5403
Lei Zhang17535f72016-05-04 15:55:59 -04005404 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005405 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005406 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005407 it.dumpSpv(spirv);
5408
5409 glslang::GetThreadPoolAllocator().pop();
5410}
5411
5412}; // end namespace glslang