blob: 89f421777e5c491c32168ab9d4ae01278e1f8d7e [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:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
John Kessenich92187592016-02-01 13:45:25 -0700495 return spv::BuiltInViewportIndex;
496
John Kessenich5e801132016-02-15 11:09:46 -0700497 case glslang::EbvSampleId:
498 builder.addCapability(spv::CapabilitySampleRateShading);
499 return spv::BuiltInSampleId;
500
501 case glslang::EbvSamplePosition:
502 builder.addCapability(spv::CapabilitySampleRateShading);
503 return spv::BuiltInSamplePosition;
504
505 case glslang::EbvSampleMask:
506 builder.addCapability(spv::CapabilitySampleRateShading);
507 return spv::BuiltInSampleMask;
508
John Kessenich78a45572016-07-08 14:05:15 -0600509 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800510 if (!memberDeclaration) {
511 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800512#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800513 if (glslangIntermediate->getStage() == EShLangVertex ||
514 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800515 glslangIntermediate->getStage() == EShLangTessEvaluation) {
516
chaoc771d89f2017-01-13 01:10:53 -0800517 builder.addExtension(spv::E_SPV_NV_viewport_array2);
518 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
519 }
chaoc771d89f2017-01-13 01:10:53 -0800520#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800521 }
522
John Kessenich78a45572016-07-08 14:05:15 -0600523 return spv::BuiltInLayer;
524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvVertexId: return spv::BuiltInVertexId;
527 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700528 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
529 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800530
John Kessenichda581a22015-10-14 14:10:30 -0600531 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800532 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
533 builder.addCapability(spv::CapabilityDrawParameters);
534 return spv::BuiltInBaseVertex;
535
John Kessenichda581a22015-10-14 14:10:30 -0600536 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800537 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
538 builder.addCapability(spv::CapabilityDrawParameters);
539 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200540
John Kessenichda581a22015-10-14 14:10:30 -0600541 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800542 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
543 builder.addCapability(spv::CapabilityDrawParameters);
544 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200545
546 case glslang::EbvPrimitiveId:
547 if (glslangIntermediate->getStage() == EShLangFragment)
548 builder.addCapability(spv::CapabilityGeometry);
549 return spv::BuiltInPrimitiveId;
550
John Kessenich140f3df2015-06-26 16:58:36 -0600551 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
553 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
554 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
555 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
556 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
557 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
558 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600559 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
560 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
561 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
562 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
563 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
564 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
565 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
566 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupSize;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLocalInvocationId;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupEqMaskKHR;
582
Rex Xu574ab042016-04-14 16:53:07 +0800583 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800584 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
585 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
586 return spv::BuiltInSubgroupGeMaskKHR;
587
Rex Xu574ab042016-04-14 16:53:07 +0800588 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800589 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
590 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
591 return spv::BuiltInSubgroupGtMaskKHR;
592
Rex Xu574ab042016-04-14 16:53:07 +0800593 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800594 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
595 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
596 return spv::BuiltInSubgroupLeMaskKHR;
597
Rex Xu574ab042016-04-14 16:53:07 +0800598 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800599 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
600 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
601 return spv::BuiltInSubgroupLtMaskKHR;
602
Rex Xu9d93a232016-05-05 12:30:44 +0800603#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800604 case glslang::EbvBaryCoordNoPersp:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordNoPerspAMD;
607
608 case glslang::EbvBaryCoordNoPerspCentroid:
609 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
610 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
611
612 case glslang::EbvBaryCoordNoPerspSample:
613 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
614 return spv::BuiltInBaryCoordNoPerspSampleAMD;
615
616 case glslang::EbvBaryCoordSmooth:
617 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
618 return spv::BuiltInBaryCoordSmoothAMD;
619
620 case glslang::EbvBaryCoordSmoothCentroid:
621 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
622 return spv::BuiltInBaryCoordSmoothCentroidAMD;
623
624 case glslang::EbvBaryCoordSmoothSample:
625 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
626 return spv::BuiltInBaryCoordSmoothSampleAMD;
627
628 case glslang::EbvBaryCoordPullModel:
629 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
630 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800631#endif
chaoc771d89f2017-01-13 01:10:53 -0800632
John Kessenich6c8aaac2017-02-27 01:20:51 -0700633 case glslang::EbvDeviceIndex:
634 builder.addExtension(spv::E_SPV_KHR_device_group);
635 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700636 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700637
638 case glslang::EbvViewIndex:
639 builder.addExtension(spv::E_SPV_KHR_multiview);
640 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700641 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700642
chaoc771d89f2017-01-13 01:10:53 -0800643#ifdef NV_EXTENSIONS
644 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NV_viewport_array2);
647 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
648 }
chaoc771d89f2017-01-13 01:10:53 -0800649 return spv::BuiltInViewportMaskNV;
650 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800651 if (!memberDeclaration) {
652 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
653 builder.addCapability(spv::CapabilityShaderStereoViewNV);
654 }
chaoc771d89f2017-01-13 01:10:53 -0800655 return spv::BuiltInSecondaryPositionNV;
656 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800657 if (!memberDeclaration) {
658 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
659 builder.addCapability(spv::CapabilityShaderStereoViewNV);
660 }
chaoc771d89f2017-01-13 01:10:53 -0800661 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800662 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800663 if (!memberDeclaration) {
664 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
665 builder.addCapability(spv::CapabilityPerViewAttributesNV);
666 }
chaocdf3956c2017-02-14 14:52:34 -0800667 return spv::BuiltInPositionPerViewNV;
668 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800669 if (!memberDeclaration) {
670 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
671 builder.addCapability(spv::CapabilityPerViewAttributesNV);
672 }
chaocdf3956c2017-02-14 14:52:34 -0800673 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800674#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800675 default:
676 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600677 }
678}
679
Rex Xufc618912015-09-09 16:42:49 +0800680// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700681spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800682{
683 assert(type.getBasicType() == glslang::EbtSampler);
684
John Kessenich5d0fa972016-02-15 11:57:00 -0700685 // Check for capabilities
686 switch (type.getQualifier().layoutFormat) {
687 case glslang::ElfRg32f:
688 case glslang::ElfRg16f:
689 case glslang::ElfR11fG11fB10f:
690 case glslang::ElfR16f:
691 case glslang::ElfRgba16:
692 case glslang::ElfRgb10A2:
693 case glslang::ElfRg16:
694 case glslang::ElfRg8:
695 case glslang::ElfR16:
696 case glslang::ElfR8:
697 case glslang::ElfRgba16Snorm:
698 case glslang::ElfRg16Snorm:
699 case glslang::ElfRg8Snorm:
700 case glslang::ElfR16Snorm:
701 case glslang::ElfR8Snorm:
702
703 case glslang::ElfRg32i:
704 case glslang::ElfRg16i:
705 case glslang::ElfRg8i:
706 case glslang::ElfR16i:
707 case glslang::ElfR8i:
708
709 case glslang::ElfRgb10a2ui:
710 case glslang::ElfRg32ui:
711 case glslang::ElfRg16ui:
712 case glslang::ElfRg8ui:
713 case glslang::ElfR16ui:
714 case glslang::ElfR8ui:
715 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
716 break;
717
718 default:
719 break;
720 }
721
722 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800723 switch (type.getQualifier().layoutFormat) {
724 case glslang::ElfNone: return spv::ImageFormatUnknown;
725 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
726 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
727 case glslang::ElfR32f: return spv::ImageFormatR32f;
728 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
729 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
730 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
731 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
732 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
733 case glslang::ElfR16f: return spv::ImageFormatR16f;
734 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
735 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
736 case glslang::ElfRg16: return spv::ImageFormatRg16;
737 case glslang::ElfRg8: return spv::ImageFormatRg8;
738 case glslang::ElfR16: return spv::ImageFormatR16;
739 case glslang::ElfR8: return spv::ImageFormatR8;
740 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
741 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
742 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
743 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
744 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
745 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
746 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
747 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
748 case glslang::ElfR32i: return spv::ImageFormatR32i;
749 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
750 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
751 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
752 case glslang::ElfR16i: return spv::ImageFormatR16i;
753 case glslang::ElfR8i: return spv::ImageFormatR8i;
754 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
755 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
756 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
757 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
758 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
759 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
760 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
761 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
762 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
763 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600764 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800765 }
766}
767
qining25262b32016-05-06 17:25:16 -0400768// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700769// descriptor set.
770bool IsDescriptorResource(const glslang::TType& type)
771{
John Kessenichf7497e22016-03-08 21:36:22 -0700772 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700773 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700774 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700775
776 // non block...
777 // basically samplerXXX/subpass/sampler/texture are all included
778 // if they are the global-scope-class, not the function parameter
779 // (or local, if they ever exist) class.
780 if (type.getBasicType() == glslang::EbtSampler)
781 return type.getQualifier().isUniformOrBuffer();
782
783 // None of the above.
784 return false;
785}
786
John Kesseniche0b6cad2015-12-24 10:30:13 -0700787void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
788{
789 if (child.layoutMatrix == glslang::ElmNone)
790 child.layoutMatrix = parent.layoutMatrix;
791
792 if (parent.invariant)
793 child.invariant = true;
794 if (parent.nopersp)
795 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800796#ifdef AMD_EXTENSIONS
797 if (parent.explicitInterp)
798 child.explicitInterp = true;
799#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700800 if (parent.flat)
801 child.flat = true;
802 if (parent.centroid)
803 child.centroid = true;
804 if (parent.patch)
805 child.patch = true;
806 if (parent.sample)
807 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800808 if (parent.coherent)
809 child.coherent = true;
810 if (parent.volatil)
811 child.volatil = true;
812 if (parent.restrict)
813 child.restrict = true;
814 if (parent.readonly)
815 child.readonly = true;
816 if (parent.writeonly)
817 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700818}
819
John Kessenichf2b7f332016-09-01 17:05:23 -0600820bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700821{
John Kessenich7b9fa252016-01-21 18:56:57 -0700822 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600823 // - struct members might inherit from a struct declaration
824 // (note that non-block structs don't explicitly inherit,
825 // only implicitly, meaning no decoration involved)
826 // - affect decorations on the struct members
827 // (note smooth does not, and expecting something like volatile
828 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700829 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600830 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700831}
832
John Kessenich140f3df2015-06-26 16:58:36 -0600833//
834// Implement the TGlslangToSpvTraverser class.
835//
836
Lei Zhang17535f72016-05-04 15:55:59 -0400837TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600838 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
839 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400840 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700841 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600842 glslangIntermediate(glslangIntermediate)
843{
844 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
845
846 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700847 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600848 stdBuiltins = builder.import("GLSL.std.450");
849 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600850 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
851 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600852
853 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600854 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
855 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600856 builder.addSourceExtension(it->c_str());
857
858 // Add the top-level modes for this shader.
859
John Kessenich92187592016-02-01 13:45:25 -0700860 if (glslangIntermediate->getXfbMode()) {
861 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600862 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700863 }
John Kessenich140f3df2015-06-26 16:58:36 -0600864
865 unsigned int mode;
866 switch (glslangIntermediate->getStage()) {
867 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600868 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 break;
870
871 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600872 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600873 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
874 break;
875
876 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600877 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600878 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700879 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
880 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
881 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600882 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600883 }
John Kessenich4016e382016-07-15 11:53:56 -0600884 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600885 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
886
John Kesseniche6903322015-10-13 16:29:02 -0600887 switch (glslangIntermediate->getVertexSpacing()) {
888 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
889 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
890 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600891 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600892 }
John Kessenich4016e382016-07-15 11:53:56 -0600893 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600894 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
895
896 switch (glslangIntermediate->getVertexOrder()) {
897 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
898 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600899 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600900 }
John Kessenich4016e382016-07-15 11:53:56 -0600901 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600902 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
903
904 if (glslangIntermediate->getPointMode())
905 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600906 break;
907
908 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600909 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600910 switch (glslangIntermediate->getInputPrimitive()) {
911 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
912 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
913 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700914 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600915 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600916 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600917 }
John Kessenich4016e382016-07-15 11:53:56 -0600918 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600919 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600920
John Kessenich140f3df2015-06-26 16:58:36 -0600921 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
922
923 switch (glslangIntermediate->getOutputPrimitive()) {
924 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
925 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
926 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600927 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600928 }
John Kessenich4016e382016-07-15 11:53:56 -0600929 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600930 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
931 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
932 break;
933
934 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600935 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600936 if (glslangIntermediate->getPixelCenterInteger())
937 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600938
John Kessenich140f3df2015-06-26 16:58:36 -0600939 if (glslangIntermediate->getOriginUpperLeft())
940 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600941 else
942 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600943
944 if (glslangIntermediate->getEarlyFragmentTests())
945 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
946
947 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600948 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
949 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600950 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600951 }
John Kessenich4016e382016-07-15 11:53:56 -0600952 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600953 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
954
955 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
956 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600957 break;
958
959 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600960 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600961 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
962 glslangIntermediate->getLocalSize(1),
963 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600964 break;
965
966 default:
967 break;
968 }
John Kessenich140f3df2015-06-26 16:58:36 -0600969}
970
John Kessenichfca82622016-11-26 13:23:20 -0700971// Finish creating SPV, after the traversal is complete.
972void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700973{
John Kessenich517fe7a2016-11-26 13:31:47 -0700974 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700975 builder.setBuildPoint(shaderEntry->getLastBlock());
976 builder.leaveFunction();
977 }
978
John Kessenich7ba63412015-12-20 17:37:07 -0700979 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100980 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
981 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700982
qiningda397332016-03-09 19:54:03 -0500983 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700984}
985
John Kessenichfca82622016-11-26 13:23:20 -0700986// Write the SPV into 'out'.
987void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600988{
John Kessenichfca82622016-11-26 13:23:20 -0700989 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600990}
991
992//
993// Implement the traversal functions.
994//
995// Return true from interior nodes to have the external traversal
996// continue on to children. Return false if children were
997// already processed.
998//
999
1000//
qining25262b32016-05-06 17:25:16 -04001001// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001002// - uniform/input reads
1003// - output writes
1004// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1005// - something simple that degenerates into the last bullet
1006//
1007void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1008{
qining75d1d802016-04-06 14:42:01 -04001009 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1010 if (symbol->getType().getQualifier().isSpecConstant())
1011 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1012
John Kessenich140f3df2015-06-26 16:58:36 -06001013 // getSymbolId() will set up all the IO decorations on the first call.
1014 // Formal function parameters were mapped during makeFunctions().
1015 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001016
1017 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1018 if (builder.isPointer(id)) {
1019 spv::StorageClass sc = builder.getStorageClass(id);
1020 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1021 iOSet.insert(id);
1022 }
1023
1024 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001025 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001026 // Prepare to generate code for the access
1027
1028 // L-value chains will be computed left to right. We're on the symbol now,
1029 // which is the left-most part of the access chain, so now is "clear" time,
1030 // followed by setting the base.
1031 builder.clearAccessChain();
1032
1033 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001034 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001035 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001036 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001037 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001038 // These are also pure R-values.
1039 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001040 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001041 builder.setAccessChainRValue(id);
1042 else
1043 builder.setAccessChainLValue(id);
1044 }
1045}
1046
1047bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1048{
qining40887662016-04-03 22:20:42 -04001049 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1050 if (node->getType().getQualifier().isSpecConstant())
1051 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1052
John Kessenich140f3df2015-06-26 16:58:36 -06001053 // First, handle special cases
1054 switch (node->getOp()) {
1055 case glslang::EOpAssign:
1056 case glslang::EOpAddAssign:
1057 case glslang::EOpSubAssign:
1058 case glslang::EOpMulAssign:
1059 case glslang::EOpVectorTimesMatrixAssign:
1060 case glslang::EOpVectorTimesScalarAssign:
1061 case glslang::EOpMatrixTimesScalarAssign:
1062 case glslang::EOpMatrixTimesMatrixAssign:
1063 case glslang::EOpDivAssign:
1064 case glslang::EOpModAssign:
1065 case glslang::EOpAndAssign:
1066 case glslang::EOpInclusiveOrAssign:
1067 case glslang::EOpExclusiveOrAssign:
1068 case glslang::EOpLeftShiftAssign:
1069 case glslang::EOpRightShiftAssign:
1070 // A bin-op assign "a += b" means the same thing as "a = a + b"
1071 // where a is evaluated before b. For a simple assignment, GLSL
1072 // says to evaluate the left before the right. So, always, left
1073 // node then right node.
1074 {
1075 // get the left l-value, save it away
1076 builder.clearAccessChain();
1077 node->getLeft()->traverse(this);
1078 spv::Builder::AccessChain lValue = builder.getAccessChain();
1079
1080 // evaluate the right
1081 builder.clearAccessChain();
1082 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001083 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001084
1085 if (node->getOp() != glslang::EOpAssign) {
1086 // the left is also an r-value
1087 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001088 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001089
1090 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001091 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001092 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001093 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1094 node->getType().getBasicType());
1095
1096 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001097 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001098 }
1099
1100 // store the result
1101 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001102 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001103
1104 // assignments are expressions having an rValue after they are evaluated...
1105 builder.clearAccessChain();
1106 builder.setAccessChainRValue(rValue);
1107 }
1108 return false;
1109 case glslang::EOpIndexDirect:
1110 case glslang::EOpIndexDirectStruct:
1111 {
1112 // Get the left part of the access chain.
1113 node->getLeft()->traverse(this);
1114
1115 // Add the next element in the chain
1116
David Netoa901ffe2016-06-08 14:11:40 +01001117 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001118 if (! node->getLeft()->getType().isArray() &&
1119 node->getLeft()->getType().isVector() &&
1120 node->getOp() == glslang::EOpIndexDirect) {
1121 // This is essentially a hard-coded vector swizzle of size 1,
1122 // so short circuit the access-chain stuff with a swizzle.
1123 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001124 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001125 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001126 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001127 int spvIndex = glslangIndex;
1128 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1129 node->getOp() == glslang::EOpIndexDirectStruct)
1130 {
1131 // This may be, e.g., an anonymous block-member selection, which generally need
1132 // index remapping due to hidden members in anonymous blocks.
1133 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1134 assert(remapper.size() > 0);
1135 spvIndex = remapper[glslangIndex];
1136 }
John Kessenichebb50532016-05-16 19:22:05 -06001137
David Netoa901ffe2016-06-08 14:11:40 +01001138 // normal case for indexing array or structure or block
1139 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1140
1141 // Add capabilities here for accessing PointSize and clip/cull distance.
1142 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001143 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001144 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001145 }
1146 }
1147 return false;
1148 case glslang::EOpIndexIndirect:
1149 {
1150 // Structure or array or vector indirection.
1151 // Will use native SPIR-V access-chain for struct and array indirection;
1152 // matrices are arrays of vectors, so will also work for a matrix.
1153 // Will use the access chain's 'component' for variable index into a vector.
1154
1155 // This adapter is building access chains left to right.
1156 // Set up the access chain to the left.
1157 node->getLeft()->traverse(this);
1158
1159 // save it so that computing the right side doesn't trash it
1160 spv::Builder::AccessChain partial = builder.getAccessChain();
1161
1162 // compute the next index in the chain
1163 builder.clearAccessChain();
1164 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001165 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001166
1167 // restore the saved access chain
1168 builder.setAccessChain(partial);
1169
1170 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001171 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001172 else
John Kessenichfa668da2015-09-13 14:46:30 -06001173 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001174 }
1175 return false;
1176 case glslang::EOpVectorSwizzle:
1177 {
1178 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001179 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001180 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001181 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001182 }
1183 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001184 case glslang::EOpMatrixSwizzle:
1185 logger->missingFunctionality("matrix swizzle");
1186 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001187 case glslang::EOpLogicalOr:
1188 case glslang::EOpLogicalAnd:
1189 {
1190
1191 // These may require short circuiting, but can sometimes be done as straight
1192 // binary operations. The right operand must be short circuited if it has
1193 // side effects, and should probably be if it is complex.
1194 if (isTrivial(node->getRight()->getAsTyped()))
1195 break; // handle below as a normal binary operation
1196 // otherwise, we need to do dynamic short circuiting on the right operand
1197 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1198 builder.clearAccessChain();
1199 builder.setAccessChainRValue(result);
1200 }
1201 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001202 default:
1203 break;
1204 }
1205
1206 // Assume generic binary op...
1207
John Kessenich32cfd492016-02-02 12:37:46 -07001208 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001209 builder.clearAccessChain();
1210 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001211 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001212
John Kessenich32cfd492016-02-02 12:37:46 -07001213 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001214 builder.clearAccessChain();
1215 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001216 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001217
John Kessenich32cfd492016-02-02 12:37:46 -07001218 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001219 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001220 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001221 convertGlslangToSpvType(node->getType()), left, right,
1222 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
John Kessenich50e57562015-12-21 21:21:11 -07001224 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001225 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001226 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001227 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001228 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001229 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001230 return false;
1231 }
John Kessenich140f3df2015-06-26 16:58:36 -06001232}
1233
1234bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1235{
qining40887662016-04-03 22:20:42 -04001236 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1237 if (node->getType().getQualifier().isSpecConstant())
1238 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1239
John Kessenichfc51d282015-08-19 13:34:18 -06001240 spv::Id result = spv::NoResult;
1241
1242 // try texturing first
1243 result = createImageTextureFunctionCall(node);
1244 if (result != spv::NoResult) {
1245 builder.clearAccessChain();
1246 builder.setAccessChainRValue(result);
1247
1248 return false; // done with this node
1249 }
1250
1251 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001252
1253 if (node->getOp() == glslang::EOpArrayLength) {
1254 // Quite special; won't want to evaluate the operand.
1255
1256 // Normal .length() would have been constant folded by the front-end.
1257 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001258 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001259 assert(node->getOperand()->getType().isRuntimeSizedArray());
1260 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1261 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001262 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1263 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001264
1265 builder.clearAccessChain();
1266 builder.setAccessChainRValue(length);
1267
1268 return false;
1269 }
1270
John Kessenichfc51d282015-08-19 13:34:18 -06001271 // Start by evaluating the operand
1272
John Kessenich8c8505c2016-07-26 12:50:38 -06001273 // Does it need a swizzle inversion? If so, evaluation is inverted;
1274 // operate first on the swizzle base, then apply the swizzle.
1275 spv::Id invertedType = spv::NoType;
1276 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1277 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1278 invertedType = getInvertedSwizzleType(*node->getOperand());
1279
John Kessenich140f3df2015-06-26 16:58:36 -06001280 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001281 if (invertedType != spv::NoType)
1282 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1283 else
1284 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001285
Rex Xufc618912015-09-09 16:42:49 +08001286 spv::Id operand = spv::NoResult;
1287
1288 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1289 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001290 node->getOp() == glslang::EOpAtomicCounter ||
1291 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001292 operand = builder.accessChainGetLValue(); // Special case l-value operands
1293 else
John Kessenich32cfd492016-02-02 12:37:46 -07001294 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001295
John Kessenichf6640762016-08-01 19:44:00 -06001296 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001297 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001298
1299 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001300 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001301 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 // if not, then possibly an operation
1304 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001305 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001306
1307 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001308 if (invertedType)
1309 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1310
John Kessenich140f3df2015-06-26 16:58:36 -06001311 builder.clearAccessChain();
1312 builder.setAccessChainRValue(result);
1313
1314 return false; // done with this node
1315 }
1316
1317 // it must be a special case, check...
1318 switch (node->getOp()) {
1319 case glslang::EOpPostIncrement:
1320 case glslang::EOpPostDecrement:
1321 case glslang::EOpPreIncrement:
1322 case glslang::EOpPreDecrement:
1323 {
1324 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001325 spv::Id one = 0;
1326 if (node->getBasicType() == glslang::EbtFloat)
1327 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001328 else if (node->getBasicType() == glslang::EbtDouble)
1329 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001330#ifdef AMD_EXTENSIONS
1331 else if (node->getBasicType() == glslang::EbtFloat16)
1332 one = builder.makeFloat16Constant(1.0F);
1333#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001334 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1335 one = builder.makeInt64Constant(1);
1336 else
1337 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001338 glslang::TOperator op;
1339 if (node->getOp() == glslang::EOpPreIncrement ||
1340 node->getOp() == glslang::EOpPostIncrement)
1341 op = glslang::EOpAdd;
1342 else
1343 op = glslang::EOpSub;
1344
John Kessenichf6640762016-08-01 19:44:00 -06001345 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001346 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001347 convertGlslangToSpvType(node->getType()), operand, one,
1348 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001349 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001350
1351 // The result of operation is always stored, but conditionally the
1352 // consumed result. The consumed result is always an r-value.
1353 builder.accessChainStore(result);
1354 builder.clearAccessChain();
1355 if (node->getOp() == glslang::EOpPreIncrement ||
1356 node->getOp() == glslang::EOpPreDecrement)
1357 builder.setAccessChainRValue(result);
1358 else
1359 builder.setAccessChainRValue(operand);
1360 }
1361
1362 return false;
1363
1364 case glslang::EOpEmitStreamVertex:
1365 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1366 return false;
1367 case glslang::EOpEndStreamPrimitive:
1368 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1369 return false;
1370
1371 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001372 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001373 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001374 }
John Kessenich140f3df2015-06-26 16:58:36 -06001375}
1376
1377bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1378{
qining27e04a02016-04-14 16:40:20 -04001379 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1380 if (node->getType().getQualifier().isSpecConstant())
1381 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1382
John Kessenichfc51d282015-08-19 13:34:18 -06001383 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001384 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1385 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001386
1387 // try texturing
1388 result = createImageTextureFunctionCall(node);
1389 if (result != spv::NoResult) {
1390 builder.clearAccessChain();
1391 builder.setAccessChainRValue(result);
1392
1393 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001394 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001395 // "imageStore" is a special case, which has no result
1396 return false;
1397 }
John Kessenichfc51d282015-08-19 13:34:18 -06001398
John Kessenich140f3df2015-06-26 16:58:36 -06001399 glslang::TOperator binOp = glslang::EOpNull;
1400 bool reduceComparison = true;
1401 bool isMatrix = false;
1402 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001403 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001404
1405 assert(node->getOp());
1406
John Kessenichf6640762016-08-01 19:44:00 -06001407 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001408
1409 switch (node->getOp()) {
1410 case glslang::EOpSequence:
1411 {
1412 if (preVisit)
1413 ++sequenceDepth;
1414 else
1415 --sequenceDepth;
1416
1417 if (sequenceDepth == 1) {
1418 // If this is the parent node of all the functions, we want to see them
1419 // early, so all call points have actual SPIR-V functions to reference.
1420 // In all cases, still let the traverser visit the children for us.
1421 makeFunctions(node->getAsAggregate()->getSequence());
1422
John Kessenich6fccb3c2016-09-19 16:01:41 -06001423 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001424 // anything else gets there, so visit out of order, doing them all now.
1425 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1426
John Kessenich6a60c2f2016-12-08 21:01:59 -07001427 // 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 -06001428 // so do them manually.
1429 visitFunctions(node->getAsAggregate()->getSequence());
1430
1431 return false;
1432 }
1433
1434 return true;
1435 }
1436 case glslang::EOpLinkerObjects:
1437 {
1438 if (visit == glslang::EvPreVisit)
1439 linkageOnly = true;
1440 else
1441 linkageOnly = false;
1442
1443 return true;
1444 }
1445 case glslang::EOpComma:
1446 {
1447 // processing from left to right naturally leaves the right-most
1448 // lying around in the access chain
1449 glslang::TIntermSequence& glslangOperands = node->getSequence();
1450 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1451 glslangOperands[i]->traverse(this);
1452
1453 return false;
1454 }
1455 case glslang::EOpFunction:
1456 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001457 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001458 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001459 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001460 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001461 } else {
1462 handleFunctionEntry(node);
1463 }
1464 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001465 if (inEntryPoint)
1466 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001467 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001468 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001469 }
1470
1471 return true;
1472 case glslang::EOpParameters:
1473 // Parameters will have been consumed by EOpFunction processing, but not
1474 // the body, so we still visited the function node's children, making this
1475 // child redundant.
1476 return false;
1477 case glslang::EOpFunctionCall:
1478 {
1479 if (node->isUserDefined())
1480 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001481 // 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 -07001482 if (result) {
1483 builder.clearAccessChain();
1484 builder.setAccessChainRValue(result);
1485 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001486 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001487
1488 return false;
1489 }
1490 case glslang::EOpConstructMat2x2:
1491 case glslang::EOpConstructMat2x3:
1492 case glslang::EOpConstructMat2x4:
1493 case glslang::EOpConstructMat3x2:
1494 case glslang::EOpConstructMat3x3:
1495 case glslang::EOpConstructMat3x4:
1496 case glslang::EOpConstructMat4x2:
1497 case glslang::EOpConstructMat4x3:
1498 case glslang::EOpConstructMat4x4:
1499 case glslang::EOpConstructDMat2x2:
1500 case glslang::EOpConstructDMat2x3:
1501 case glslang::EOpConstructDMat2x4:
1502 case glslang::EOpConstructDMat3x2:
1503 case glslang::EOpConstructDMat3x3:
1504 case glslang::EOpConstructDMat3x4:
1505 case glslang::EOpConstructDMat4x2:
1506 case glslang::EOpConstructDMat4x3:
1507 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001508#ifdef AMD_EXTENSIONS
1509 case glslang::EOpConstructF16Mat2x2:
1510 case glslang::EOpConstructF16Mat2x3:
1511 case glslang::EOpConstructF16Mat2x4:
1512 case glslang::EOpConstructF16Mat3x2:
1513 case glslang::EOpConstructF16Mat3x3:
1514 case glslang::EOpConstructF16Mat3x4:
1515 case glslang::EOpConstructF16Mat4x2:
1516 case glslang::EOpConstructF16Mat4x3:
1517 case glslang::EOpConstructF16Mat4x4:
1518#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001519 isMatrix = true;
1520 // fall through
1521 case glslang::EOpConstructFloat:
1522 case glslang::EOpConstructVec2:
1523 case glslang::EOpConstructVec3:
1524 case glslang::EOpConstructVec4:
1525 case glslang::EOpConstructDouble:
1526 case glslang::EOpConstructDVec2:
1527 case glslang::EOpConstructDVec3:
1528 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001529#ifdef AMD_EXTENSIONS
1530 case glslang::EOpConstructFloat16:
1531 case glslang::EOpConstructF16Vec2:
1532 case glslang::EOpConstructF16Vec3:
1533 case glslang::EOpConstructF16Vec4:
1534#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001535 case glslang::EOpConstructBool:
1536 case glslang::EOpConstructBVec2:
1537 case glslang::EOpConstructBVec3:
1538 case glslang::EOpConstructBVec4:
1539 case glslang::EOpConstructInt:
1540 case glslang::EOpConstructIVec2:
1541 case glslang::EOpConstructIVec3:
1542 case glslang::EOpConstructIVec4:
1543 case glslang::EOpConstructUint:
1544 case glslang::EOpConstructUVec2:
1545 case glslang::EOpConstructUVec3:
1546 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001547 case glslang::EOpConstructInt64:
1548 case glslang::EOpConstructI64Vec2:
1549 case glslang::EOpConstructI64Vec3:
1550 case glslang::EOpConstructI64Vec4:
1551 case glslang::EOpConstructUint64:
1552 case glslang::EOpConstructU64Vec2:
1553 case glslang::EOpConstructU64Vec3:
1554 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001555 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001556 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001557 {
1558 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001559 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001560 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001561 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001562 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001563 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001564 std::vector<spv::Id> constituents;
1565 for (int c = 0; c < (int)arguments.size(); ++c)
1566 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001567 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001568 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001569 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001570 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001571 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001572
1573 builder.clearAccessChain();
1574 builder.setAccessChainRValue(constructed);
1575
1576 return false;
1577 }
1578
1579 // These six are component-wise compares with component-wise results.
1580 // Forward on to createBinaryOperation(), requesting a vector result.
1581 case glslang::EOpLessThan:
1582 case glslang::EOpGreaterThan:
1583 case glslang::EOpLessThanEqual:
1584 case glslang::EOpGreaterThanEqual:
1585 case glslang::EOpVectorEqual:
1586 case glslang::EOpVectorNotEqual:
1587 {
1588 // Map the operation to a binary
1589 binOp = node->getOp();
1590 reduceComparison = false;
1591 switch (node->getOp()) {
1592 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1593 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1594 default: binOp = node->getOp(); break;
1595 }
1596
1597 break;
1598 }
1599 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001600 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001601 binOp = glslang::EOpMul;
1602 break;
1603 case glslang::EOpOuterProduct:
1604 // two vectors multiplied to make a matrix
1605 binOp = glslang::EOpOuterProduct;
1606 break;
1607 case glslang::EOpDot:
1608 {
qining25262b32016-05-06 17:25:16 -04001609 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001610 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001611 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001612 binOp = glslang::EOpMul;
1613 break;
1614 }
1615 case glslang::EOpMod:
1616 // when an aggregate, this is the floating-point mod built-in function,
1617 // which can be emitted by the one in createBinaryOperation()
1618 binOp = glslang::EOpMod;
1619 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001620 case glslang::EOpEmitVertex:
1621 case glslang::EOpEndPrimitive:
1622 case glslang::EOpBarrier:
1623 case glslang::EOpMemoryBarrier:
1624 case glslang::EOpMemoryBarrierAtomicCounter:
1625 case glslang::EOpMemoryBarrierBuffer:
1626 case glslang::EOpMemoryBarrierImage:
1627 case glslang::EOpMemoryBarrierShared:
1628 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001629 case glslang::EOpAllMemoryBarrierWithGroupSync:
1630 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1631 case glslang::EOpWorkgroupMemoryBarrier:
1632 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001633 noReturnValue = true;
1634 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1635 break;
1636
John Kessenich426394d2015-07-23 10:22:48 -06001637 case glslang::EOpAtomicAdd:
1638 case glslang::EOpAtomicMin:
1639 case glslang::EOpAtomicMax:
1640 case glslang::EOpAtomicAnd:
1641 case glslang::EOpAtomicOr:
1642 case glslang::EOpAtomicXor:
1643 case glslang::EOpAtomicExchange:
1644 case glslang::EOpAtomicCompSwap:
1645 atomic = true;
1646 break;
1647
John Kessenich140f3df2015-06-26 16:58:36 -06001648 default:
1649 break;
1650 }
1651
1652 //
1653 // See if it maps to a regular operation.
1654 //
John Kessenich140f3df2015-06-26 16:58:36 -06001655 if (binOp != glslang::EOpNull) {
1656 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1657 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1658 assert(left && right);
1659
1660 builder.clearAccessChain();
1661 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001662 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001663
1664 builder.clearAccessChain();
1665 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001666 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001667
qining25262b32016-05-06 17:25:16 -04001668 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001669 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001670 left->getType().getBasicType(), reduceComparison);
1671
1672 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001673 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001674 builder.clearAccessChain();
1675 builder.setAccessChainRValue(result);
1676
1677 return false;
1678 }
1679
John Kessenich426394d2015-07-23 10:22:48 -06001680 //
1681 // Create the list of operands.
1682 //
John Kessenich140f3df2015-06-26 16:58:36 -06001683 glslang::TIntermSequence& glslangOperands = node->getSequence();
1684 std::vector<spv::Id> operands;
1685 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001686 // special case l-value operands; there are just a few
1687 bool lvalue = false;
1688 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001689 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001690 case glslang::EOpModf:
1691 if (arg == 1)
1692 lvalue = true;
1693 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001694 case glslang::EOpInterpolateAtSample:
1695 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001696#ifdef AMD_EXTENSIONS
1697 case glslang::EOpInterpolateAtVertex:
1698#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001699 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001700 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001701
1702 // Does it need a swizzle inversion? If so, evaluation is inverted;
1703 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001704 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001705 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1706 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1707 }
Rex Xu7a26c172015-12-08 17:12:09 +08001708 break;
Rex Xud4782c12015-09-06 16:30:11 +08001709 case glslang::EOpAtomicAdd:
1710 case glslang::EOpAtomicMin:
1711 case glslang::EOpAtomicMax:
1712 case glslang::EOpAtomicAnd:
1713 case glslang::EOpAtomicOr:
1714 case glslang::EOpAtomicXor:
1715 case glslang::EOpAtomicExchange:
1716 case glslang::EOpAtomicCompSwap:
1717 if (arg == 0)
1718 lvalue = true;
1719 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001720 case glslang::EOpAddCarry:
1721 case glslang::EOpSubBorrow:
1722 if (arg == 2)
1723 lvalue = true;
1724 break;
1725 case glslang::EOpUMulExtended:
1726 case glslang::EOpIMulExtended:
1727 if (arg >= 2)
1728 lvalue = true;
1729 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001730 default:
1731 break;
1732 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001733 builder.clearAccessChain();
1734 if (invertedType != spv::NoType && arg == 0)
1735 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1736 else
1737 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001738 if (lvalue)
1739 operands.push_back(builder.accessChainGetLValue());
1740 else
John Kessenich32cfd492016-02-02 12:37:46 -07001741 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001742 }
John Kessenich426394d2015-07-23 10:22:48 -06001743
1744 if (atomic) {
1745 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001746 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001747 } else {
1748 // Pass through to generic operations.
1749 switch (glslangOperands.size()) {
1750 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001751 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001752 break;
1753 case 1:
qining25262b32016-05-06 17:25:16 -04001754 result = createUnaryOperation(
1755 node->getOp(), precision,
1756 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001758 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001759 break;
1760 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001761 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001762 break;
1763 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001764 if (invertedType)
1765 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001766 }
1767
1768 if (noReturnValue)
1769 return false;
1770
1771 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001772 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001773 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001774 } else {
1775 builder.clearAccessChain();
1776 builder.setAccessChainRValue(result);
1777 return false;
1778 }
1779}
1780
John Kessenich433e9ff2017-01-26 20:31:11 -07001781// This path handles both if-then-else and ?:
1782// The if-then-else has a node type of void, while
1783// ?: has either a void or a non-void node type
1784//
1785// Leaving the result, when not void:
1786// GLSL only has r-values as the result of a :?, but
1787// if we have an l-value, that can be more efficient if it will
1788// become the base of a complex r-value expression, because the
1789// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001790bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1791{
John Kessenich433e9ff2017-01-26 20:31:11 -07001792 // See if it simple and safe to generate OpSelect instead of using control flow.
1793 // Crucially, side effects must be avoided, and there are performance trade-offs.
1794 // Return true if good idea (and safe) for OpSelect, false otherwise.
1795 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001796 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1797 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001798 return false;
1799
1800 if (node->getTrueBlock() == nullptr ||
1801 node->getFalseBlock() == nullptr)
1802 return false;
1803
1804 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1805 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1806
1807 // return true if a single operand to ? : is okay for OpSelect
1808 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001809 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001810 };
1811
1812 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1813 operandOkay(node->getFalseBlock()->getAsTyped());
1814 };
1815
1816 // Emit OpSelect for this selection.
1817 const auto handleAsOpSelect = [&]() {
1818 node->getCondition()->traverse(this);
1819 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1820 node->getTrueBlock()->traverse(this);
1821 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1822 node->getFalseBlock()->traverse(this);
1823 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1824
1825 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1826 builder.clearAccessChain();
1827 builder.setAccessChainRValue(select);
1828 };
1829
1830 // Try for OpSelect
1831
1832 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001833 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1834 if (node->getType().getQualifier().isSpecConstant())
1835 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1836
John Kessenich433e9ff2017-01-26 20:31:11 -07001837 handleAsOpSelect();
1838 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001839 }
1840
John Kessenich433e9ff2017-01-26 20:31:11 -07001841 // Instead, emit control flow...
1842
1843 // Don't handle results as temporaries, because there will be two names
1844 // and better to leave SSA to later passes.
1845 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1846 ? spv::NoResult
1847 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1848
John Kessenich140f3df2015-06-26 16:58:36 -06001849 // emit the condition before doing anything with selection
1850 node->getCondition()->traverse(this);
1851
1852 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001853 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001854
John Kessenich433e9ff2017-01-26 20:31:11 -07001855 // emit the "then" statement
1856 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001857 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001858 if (result != spv::NoResult)
1859 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861
John Kessenich433e9ff2017-01-26 20:31:11 -07001862 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001863 ifBuilder.makeBeginElse();
1864 // emit the "else" statement
1865 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001866 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001867 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001868 }
1869
John Kessenich433e9ff2017-01-26 20:31:11 -07001870 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001871 ifBuilder.makeEndIf();
1872
John Kessenich433e9ff2017-01-26 20:31:11 -07001873 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001874 // GLSL only has r-values as the result of a :?, but
1875 // if we have an l-value, that can be more efficient if it will
1876 // become the base of a complex r-value expression, because the
1877 // next layer copies r-values into memory to use the access-chain mechanism
1878 builder.clearAccessChain();
1879 builder.setAccessChainLValue(result);
1880 }
1881
1882 return false;
1883}
1884
1885bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1886{
1887 // emit and get the condition before doing anything with switch
1888 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001889 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001890
1891 // browse the children to sort out code segments
1892 int defaultSegment = -1;
1893 std::vector<TIntermNode*> codeSegments;
1894 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1895 std::vector<int> caseValues;
1896 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1897 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1898 TIntermNode* child = *c;
1899 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001900 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001901 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001902 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001903 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1904 } else
1905 codeSegments.push_back(child);
1906 }
1907
qining25262b32016-05-06 17:25:16 -04001908 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001909 // statements between the last case and the end of the switch statement
1910 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1911 (int)codeSegments.size() == defaultSegment)
1912 codeSegments.push_back(nullptr);
1913
1914 // make the switch statement
1915 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001916 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001917
1918 // emit all the code in the segments
1919 breakForLoop.push(false);
1920 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1921 builder.nextSwitchSegment(segmentBlocks, s);
1922 if (codeSegments[s])
1923 codeSegments[s]->traverse(this);
1924 else
1925 builder.addSwitchBreak();
1926 }
1927 breakForLoop.pop();
1928
1929 builder.endSwitch(segmentBlocks);
1930
1931 return false;
1932}
1933
1934void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1935{
1936 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001937 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001938
1939 builder.clearAccessChain();
1940 builder.setAccessChainRValue(constant);
1941}
1942
1943bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1944{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001945 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001946 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001947 // Spec requires back edges to target header blocks, and every header block
1948 // must dominate its merge block. Make a header block first to ensure these
1949 // conditions are met. By definition, it will contain OpLoopMerge, followed
1950 // by a block-ending branch. But we don't want to put any other body/test
1951 // instructions in it, since the body/test may have arbitrary instructions,
1952 // including merges of its own.
1953 builder.setBuildPoint(&blocks.head);
1954 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001955 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001956 spv::Block& test = builder.makeNewBlock();
1957 builder.createBranch(&test);
1958
1959 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001960 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001961 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001962 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001963 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1964
1965 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001966 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001967 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001968 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001969 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001970 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001971
1972 builder.setBuildPoint(&blocks.continue_target);
1973 if (node->getTerminal())
1974 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001975 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001976 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001977 builder.createBranch(&blocks.body);
1978
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001979 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001980 builder.setBuildPoint(&blocks.body);
1981 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001982 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001983 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001984 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001985
1986 builder.setBuildPoint(&blocks.continue_target);
1987 if (node->getTerminal())
1988 node->getTerminal()->traverse(this);
1989 if (node->getTest()) {
1990 node->getTest()->traverse(this);
1991 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001992 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001993 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001994 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001995 // TODO: unless there was a break/return/discard instruction
1996 // somewhere in the body, this is an infinite loop, so we should
1997 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001998 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001999 }
John Kessenich140f3df2015-06-26 16:58:36 -06002000 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002001 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002002 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002003 return false;
2004}
2005
2006bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2007{
2008 if (node->getExpression())
2009 node->getExpression()->traverse(this);
2010
2011 switch (node->getFlowOp()) {
2012 case glslang::EOpKill:
2013 builder.makeDiscard();
2014 break;
2015 case glslang::EOpBreak:
2016 if (breakForLoop.top())
2017 builder.createLoopExit();
2018 else
2019 builder.addSwitchBreak();
2020 break;
2021 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002022 builder.createLoopContinue();
2023 break;
2024 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002025 if (node->getExpression()) {
2026 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2027 spv::Id returnId = accessChainLoad(glslangReturnType);
2028 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2029 builder.clearAccessChain();
2030 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2031 builder.setAccessChainLValue(copyId);
2032 multiTypeStore(glslangReturnType, returnId);
2033 returnId = builder.createLoad(copyId);
2034 }
2035 builder.makeReturn(false, returnId);
2036 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002037 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002038
2039 builder.clearAccessChain();
2040 break;
2041
2042 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002043 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002044 break;
2045 }
2046
2047 return false;
2048}
2049
2050spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2051{
qining25262b32016-05-06 17:25:16 -04002052 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002053 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002054 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002055 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002056 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002057 }
2058
2059 // Now, handle actual variables
2060 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2061 spv::Id spvType = convertGlslangToSpvType(node->getType());
2062
2063 const char* name = node->getName().c_str();
2064 if (glslang::IsAnonymous(name))
2065 name = "";
2066
2067 return builder.createVariable(storageClass, spvType, name);
2068}
2069
2070// Return type Id of the sampled type.
2071spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2072{
2073 switch (sampler.type) {
2074 case glslang::EbtFloat: return builder.makeFloatType(32);
2075 case glslang::EbtInt: return builder.makeIntType(32);
2076 case glslang::EbtUint: return builder.makeUintType(32);
2077 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002078 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002079 return builder.makeFloatType(32);
2080 }
2081}
2082
John Kessenich8c8505c2016-07-26 12:50:38 -06002083// If node is a swizzle operation, return the type that should be used if
2084// the swizzle base is first consumed by another operation, before the swizzle
2085// is applied.
2086spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2087{
John Kessenichecba76f2017-01-06 00:34:48 -07002088 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002089 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2090 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2091 else
2092 return spv::NoType;
2093}
2094
2095// When inverting a swizzle with a parent op, this function
2096// will apply the swizzle operation to a completed parent operation.
2097spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2098{
2099 std::vector<unsigned> swizzle;
2100 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2101 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2102}
2103
John Kessenich8c8505c2016-07-26 12:50:38 -06002104// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2105void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2106{
2107 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2108 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2109 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2110}
2111
John Kessenich3ac051e2015-12-20 11:29:16 -07002112// Convert from a glslang type to an SPV type, by calling into a
2113// recursive version of this function. This establishes the inherited
2114// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002115spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2116{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002117 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002118}
2119
2120// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002121// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002122// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002123spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002124{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002125 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002126
2127 switch (type.getBasicType()) {
2128 case glslang::EbtVoid:
2129 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002130 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002131 break;
2132 case glslang::EbtFloat:
2133 spvType = builder.makeFloatType(32);
2134 break;
2135 case glslang::EbtDouble:
2136 spvType = builder.makeFloatType(64);
2137 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002138#ifdef AMD_EXTENSIONS
2139 case glslang::EbtFloat16:
2140 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002141 spvType = builder.makeFloatType(16);
2142 break;
2143#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002144 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002145 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2146 // a 32-bit int where non-0 means true.
2147 if (explicitLayout != glslang::ElpNone)
2148 spvType = builder.makeUintType(32);
2149 else
2150 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002151 break;
2152 case glslang::EbtInt:
2153 spvType = builder.makeIntType(32);
2154 break;
2155 case glslang::EbtUint:
2156 spvType = builder.makeUintType(32);
2157 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002158 case glslang::EbtInt64:
2159 builder.addCapability(spv::CapabilityInt64);
2160 spvType = builder.makeIntType(64);
2161 break;
2162 case glslang::EbtUint64:
2163 builder.addCapability(spv::CapabilityInt64);
2164 spvType = builder.makeUintType(64);
2165 break;
John Kessenich426394d2015-07-23 10:22:48 -06002166 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002167 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002168 spvType = builder.makeUintType(32);
2169 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002170 case glslang::EbtSampler:
2171 {
2172 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002173 if (sampler.sampler) {
2174 // pure sampler
2175 spvType = builder.makeSamplerType();
2176 } else {
2177 // an image is present, make its type
2178 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2179 sampler.image ? 2 : 1, TranslateImageFormat(type));
2180 if (sampler.combined) {
2181 // already has both image and sampler, make the combined type
2182 spvType = builder.makeSampledImageType(spvType);
2183 }
John Kessenich55e7d112015-11-15 21:33:39 -07002184 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002185 }
John Kessenich140f3df2015-06-26 16:58:36 -06002186 break;
2187 case glslang::EbtStruct:
2188 case glslang::EbtBlock:
2189 {
2190 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002191 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002192
2193 // Try to share structs for different layouts, but not yet for other
2194 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002195 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002196 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002197 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002198 break;
2199
2200 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002201 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002202 memberRemapper[glslangMembers].resize(glslangMembers->size());
2203 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002204 }
2205 break;
2206 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002207 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002208 break;
2209 }
2210
2211 if (type.isMatrix())
2212 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2213 else {
2214 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2215 if (type.getVectorSize() > 1)
2216 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2217 }
2218
2219 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002220 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2221
John Kessenichc9a80832015-09-12 12:17:44 -06002222 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002223 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002224 // We need to decorate array strides for types needing explicit layout, except blocks.
2225 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002226 // Use a dummy glslang type for querying internal strides of
2227 // arrays of arrays, but using just a one-dimensional array.
2228 glslang::TType simpleArrayType(type, 0); // deference type of the array
2229 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2230 simpleArrayType.getArraySizes().dereference();
2231
2232 // Will compute the higher-order strides here, rather than making a whole
2233 // pile of types and doing repetitive recursion on their contents.
2234 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2235 }
John Kessenichf8842e52016-01-04 19:22:56 -07002236
2237 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002238 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002239 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002240 if (stride > 0)
2241 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002242 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002243 }
2244 } else {
2245 // single-dimensional array, and don't yet have stride
2246
John Kessenichf8842e52016-01-04 19:22:56 -07002247 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002248 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2249 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002250 }
John Kessenich31ed4832015-09-09 17:51:38 -06002251
John Kessenichc9a80832015-09-12 12:17:44 -06002252 // Do the outer dimension, which might not be known for a runtime-sized array
2253 if (type.isRuntimeSizedArray()) {
2254 spvType = builder.makeRuntimeArray(spvType);
2255 } else {
2256 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002257 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002258 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002259 if (stride > 0)
2260 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002261 }
2262
2263 return spvType;
2264}
2265
John Kessenich6090df02016-06-30 21:18:02 -06002266// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2267// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2268// Mutually recursive with convertGlslangToSpvType().
2269spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2270 const glslang::TTypeList* glslangMembers,
2271 glslang::TLayoutPacking explicitLayout,
2272 const glslang::TQualifier& qualifier)
2273{
2274 // Create a vector of struct types for SPIR-V to consume
2275 std::vector<spv::Id> spvMembers;
2276 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2277 int locationOffset = 0; // for use across struct members, when they are called recursively
2278 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2279 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2280 if (glslangMember.hiddenMember()) {
2281 ++memberDelta;
2282 if (type.getBasicType() == glslang::EbtBlock)
2283 memberRemapper[glslangMembers][i] = -1;
2284 } else {
2285 if (type.getBasicType() == glslang::EbtBlock)
2286 memberRemapper[glslangMembers][i] = i - memberDelta;
2287 // modify just this child's view of the qualifier
2288 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2289 InheritQualifiers(memberQualifier, qualifier);
2290
2291 // manually inherit location; it's more complex
2292 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2293 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2294 if (qualifier.hasLocation())
2295 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2296
2297 // recurse
2298 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2299 }
2300 }
2301
2302 // Make the SPIR-V type
2303 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002304 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002305 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2306
2307 // Decorate it
2308 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2309
2310 return spvType;
2311}
2312
2313void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2314 const glslang::TTypeList* glslangMembers,
2315 glslang::TLayoutPacking explicitLayout,
2316 const glslang::TQualifier& qualifier,
2317 spv::Id spvType)
2318{
2319 // Name and decorate the non-hidden members
2320 int offset = -1;
2321 int locationOffset = 0; // for use within the members of this struct
2322 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2323 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2324 int member = i;
2325 if (type.getBasicType() == glslang::EbtBlock)
2326 member = memberRemapper[glslangMembers][i];
2327
2328 // modify just this child's view of the qualifier
2329 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2330 InheritQualifiers(memberQualifier, qualifier);
2331
2332 // using -1 above to indicate a hidden member
2333 if (member >= 0) {
2334 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2335 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2336 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2337 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002338 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2339 type.getQualifier().storage == glslang::EvqVaryingOut) {
2340 if (type.getBasicType() == glslang::EbtBlock ||
2341 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002342 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2343 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2344 }
2345 }
2346 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2347
2348 if (qualifier.storage == glslang::EvqBuffer) {
2349 std::vector<spv::Decoration> memory;
2350 TranslateMemoryDecoration(memberQualifier, memory);
2351 for (unsigned int i = 0; i < memory.size(); ++i)
2352 addMemberDecoration(spvType, member, memory[i]);
2353 }
2354
John Kessenich2f47bc92016-06-30 21:47:35 -06002355 // Compute location decoration; tricky based on whether inheritance is at play and
2356 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002357 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2358 // probably move to the linker stage of the front end proper, and just have the
2359 // answer sitting already distributed throughout the individual member locations.
2360 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002361 // Ignore member locations if the container is an array, as that's
2362 // ill-specified and decisions have been made to not allow this anyway.
2363 // The object itself must have a location, and that comes out from decorating the object,
2364 // not the type (this code decorates types).
2365 if (! type.isArray()) {
2366 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2367 // struct members should not have explicit locations
2368 assert(type.getBasicType() != glslang::EbtStruct);
2369 location = memberQualifier.layoutLocation;
2370 } else if (type.getBasicType() != glslang::EbtBlock) {
2371 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2372 // The members, and their nested types, must not themselves have Location decorations.
2373 } else if (qualifier.hasLocation()) // inheritance
2374 location = qualifier.layoutLocation + locationOffset;
2375 }
John Kessenich6090df02016-06-30 21:18:02 -06002376 if (location >= 0)
2377 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2378
John Kessenich2f47bc92016-06-30 21:47:35 -06002379 if (qualifier.hasLocation()) // track for upcoming inheritance
2380 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2381
John Kessenich6090df02016-06-30 21:18:02 -06002382 // component, XFB, others
2383 if (glslangMember.getQualifier().hasComponent())
2384 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2385 if (glslangMember.getQualifier().hasXfbOffset())
2386 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2387 else if (explicitLayout != glslang::ElpNone) {
2388 // figure out what to do with offset, which is accumulating
2389 int nextOffset;
2390 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2391 if (offset >= 0)
2392 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2393 offset = nextOffset;
2394 }
2395
2396 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2397 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2398
2399 // built-in variable decorations
2400 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002401 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002402 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002403
2404#ifdef NV_EXTENSIONS
2405 if (builtIn == spv::BuiltInLayer) {
2406 // SPV_NV_viewport_array2 extension
2407 if (glslangMember.getQualifier().layoutViewportRelative){
2408 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2409 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2410 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2411 }
2412 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2413 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2414 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2415 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2416 }
2417 }
chaocdf3956c2017-02-14 14:52:34 -08002418 if (glslangMember.getQualifier().layoutPassthrough) {
2419 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2420 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2421 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2422 }
chaoc771d89f2017-01-13 01:10:53 -08002423#endif
John Kessenich6090df02016-06-30 21:18:02 -06002424 }
2425 }
2426
2427 // Decorate the structure
2428 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2429 addDecoration(spvType, TranslateBlockDecoration(type));
2430 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2431 builder.addCapability(spv::CapabilityGeometryStreams);
2432 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2433 }
2434 if (glslangIntermediate->getXfbMode()) {
2435 builder.addCapability(spv::CapabilityTransformFeedback);
2436 if (type.getQualifier().hasXfbStride())
2437 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2438 if (type.getQualifier().hasXfbBuffer())
2439 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2440 }
2441}
2442
John Kessenich6c292d32016-02-15 20:58:50 -07002443// Turn the expression forming the array size into an id.
2444// This is not quite trivial, because of specialization constants.
2445// Sometimes, a raw constant is turned into an Id, and sometimes
2446// a specialization constant expression is.
2447spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2448{
2449 // First, see if this is sized with a node, meaning a specialization constant:
2450 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2451 if (specNode != nullptr) {
2452 builder.clearAccessChain();
2453 specNode->traverse(this);
2454 return accessChainLoad(specNode->getAsTyped()->getType());
2455 }
qining25262b32016-05-06 17:25:16 -04002456
John Kessenich6c292d32016-02-15 20:58:50 -07002457 // Otherwise, need a compile-time (front end) size, get it:
2458 int size = arraySizes.getDimSize(dim);
2459 assert(size > 0);
2460 return builder.makeUintConstant(size);
2461}
2462
John Kessenich103bef92016-02-08 21:38:15 -07002463// Wrap the builder's accessChainLoad to:
2464// - localize handling of RelaxedPrecision
2465// - use the SPIR-V inferred type instead of another conversion of the glslang type
2466// (avoids unnecessary work and possible type punning for structures)
2467// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002468spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2469{
John Kessenich103bef92016-02-08 21:38:15 -07002470 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2471 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2472
2473 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002474 if (type.getBasicType() == glslang::EbtBool) {
2475 if (builder.isScalarType(nominalTypeId)) {
2476 // Conversion for bool
2477 spv::Id boolType = builder.makeBoolType();
2478 if (nominalTypeId != boolType)
2479 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2480 } else if (builder.isVectorType(nominalTypeId)) {
2481 // Conversion for bvec
2482 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2483 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2484 if (nominalTypeId != bvecType)
2485 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2486 }
2487 }
John Kessenich103bef92016-02-08 21:38:15 -07002488
2489 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002490}
2491
Rex Xu27253232016-02-23 17:51:09 +08002492// Wrap the builder's accessChainStore to:
2493// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002494//
2495// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002496void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2497{
2498 // Need to convert to abstract types when necessary
2499 if (type.getBasicType() == glslang::EbtBool) {
2500 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2501
2502 if (builder.isScalarType(nominalTypeId)) {
2503 // Conversion for bool
2504 spv::Id boolType = builder.makeBoolType();
2505 if (nominalTypeId != boolType) {
2506 spv::Id zero = builder.makeUintConstant(0);
2507 spv::Id one = builder.makeUintConstant(1);
2508 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2509 }
2510 } else if (builder.isVectorType(nominalTypeId)) {
2511 // Conversion for bvec
2512 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2513 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2514 if (nominalTypeId != bvecType) {
2515 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2516 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2517 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2518 }
2519 }
2520 }
2521
2522 builder.accessChainStore(rvalue);
2523}
2524
John Kessenich4bf71552016-09-02 11:20:21 -06002525// For storing when types match at the glslang level, but not might match at the
2526// SPIR-V level.
2527//
2528// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002529// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002530// as in a member-decorated way.
2531//
2532// NOTE: This function can handle any store request; if it's not special it
2533// simplifies to a simple OpStore.
2534//
2535// Implicitly uses the existing builder.accessChain as the storage target.
2536void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2537{
John Kessenichb3e24e42016-09-11 12:33:43 -06002538 // we only do the complex path here if it's an aggregate
2539 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002540 accessChainStore(type, rValue);
2541 return;
2542 }
2543
John Kessenichb3e24e42016-09-11 12:33:43 -06002544 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002545 spv::Id rType = builder.getTypeId(rValue);
2546 spv::Id lValue = builder.accessChainGetLValue();
2547 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2548 if (lType == rType) {
2549 accessChainStore(type, rValue);
2550 return;
2551 }
2552
John Kessenichb3e24e42016-09-11 12:33:43 -06002553 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002554 // where the two types were the same type in GLSL. This requires member
2555 // by member copy, recursively.
2556
John Kessenichb3e24e42016-09-11 12:33:43 -06002557 // If an array, copy element by element.
2558 if (type.isArray()) {
2559 glslang::TType glslangElementType(type, 0);
2560 spv::Id elementRType = builder.getContainedTypeId(rType);
2561 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2562 // get the source member
2563 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002564
John Kessenichb3e24e42016-09-11 12:33:43 -06002565 // set up the target storage
2566 builder.clearAccessChain();
2567 builder.setAccessChainLValue(lValue);
2568 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002569
John Kessenichb3e24e42016-09-11 12:33:43 -06002570 // store the member
2571 multiTypeStore(glslangElementType, elementRValue);
2572 }
2573 } else {
2574 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002575
John Kessenichb3e24e42016-09-11 12:33:43 -06002576 // loop over structure members
2577 const glslang::TTypeList& members = *type.getStruct();
2578 for (int m = 0; m < (int)members.size(); ++m) {
2579 const glslang::TType& glslangMemberType = *members[m].type;
2580
2581 // get the source member
2582 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2583 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2584
2585 // set up the target storage
2586 builder.clearAccessChain();
2587 builder.setAccessChainLValue(lValue);
2588 builder.accessChainPush(builder.makeIntConstant(m));
2589
2590 // store the member
2591 multiTypeStore(glslangMemberType, memberRValue);
2592 }
John Kessenich4bf71552016-09-02 11:20:21 -06002593 }
2594}
2595
John Kessenichf85e8062015-12-19 13:57:10 -07002596// Decide whether or not this type should be
2597// decorated with offsets and strides, and if so
2598// whether std140 or std430 rules should be applied.
2599glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002600{
John Kessenichf85e8062015-12-19 13:57:10 -07002601 // has to be a block
2602 if (type.getBasicType() != glslang::EbtBlock)
2603 return glslang::ElpNone;
2604
2605 // has to be a uniform or buffer block
2606 if (type.getQualifier().storage != glslang::EvqUniform &&
2607 type.getQualifier().storage != glslang::EvqBuffer)
2608 return glslang::ElpNone;
2609
2610 // return the layout to use
2611 switch (type.getQualifier().layoutPacking) {
2612 case glslang::ElpStd140:
2613 case glslang::ElpStd430:
2614 return type.getQualifier().layoutPacking;
2615 default:
2616 return glslang::ElpNone;
2617 }
John Kessenich31ed4832015-09-09 17:51:38 -06002618}
2619
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002620// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002621int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002622{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002623 int size;
John Kessenich49987892015-12-29 17:11:44 -07002624 int stride;
2625 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002626
2627 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002628}
2629
John Kessenich49987892015-12-29 17:11:44 -07002630// 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 -07002631// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002632int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002633{
John Kessenich49987892015-12-29 17:11:44 -07002634 glslang::TType elementType;
2635 elementType.shallowCopy(matrixType);
2636 elementType.clearArraySizes();
2637
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002638 int size;
John Kessenich49987892015-12-29 17:11:44 -07002639 int stride;
2640 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2641
2642 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002643}
2644
John Kessenich5e4b1242015-08-06 22:53:06 -06002645// Given a member type of a struct, realign the current offset for it, and compute
2646// the next (not yet aligned) offset for the next member, which will get aligned
2647// on the next call.
2648// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2649// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2650// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002651void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002652 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002653{
2654 // this will get a positive value when deemed necessary
2655 nextOffset = -1;
2656
John Kessenich5e4b1242015-08-06 22:53:06 -06002657 // override anything in currentOffset with user-set offset
2658 if (memberType.getQualifier().hasOffset())
2659 currentOffset = memberType.getQualifier().layoutOffset;
2660
2661 // It could be that current linker usage in glslang updated all the layoutOffset,
2662 // in which case the following code does not matter. But, that's not quite right
2663 // once cross-compilation unit GLSL validation is done, as the original user
2664 // settings are needed in layoutOffset, and then the following will come into play.
2665
John Kessenichf85e8062015-12-19 13:57:10 -07002666 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002667 if (! memberType.getQualifier().hasOffset())
2668 currentOffset = -1;
2669
2670 return;
2671 }
2672
John Kessenichf85e8062015-12-19 13:57:10 -07002673 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002674 if (currentOffset < 0)
2675 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002676
John Kessenich5e4b1242015-08-06 22:53:06 -06002677 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2678 // but possibly not yet correctly aligned.
2679
2680 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002681 int dummyStride;
2682 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 glslang::RoundToPow2(currentOffset, memberAlignment);
2684 nextOffset = currentOffset + memberSize;
2685}
2686
David Netoa901ffe2016-06-08 14:11:40 +01002687void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002688{
David Netoa901ffe2016-06-08 14:11:40 +01002689 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2690 switch (glslangBuiltIn)
2691 {
2692 case glslang::EbvClipDistance:
2693 case glslang::EbvCullDistance:
2694 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002695#ifdef NV_EXTENSIONS
2696 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002697 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002698 case glslang::EbvViewportMaskNV:
2699 case glslang::EbvSecondaryPositionNV:
2700 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002701 case glslang::EbvPositionPerViewNV:
2702 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002703#endif
David Netoa901ffe2016-06-08 14:11:40 +01002704 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2705 // Alternately, we could just call this for any glslang built-in, since the
2706 // capability already guards against duplicates.
2707 TranslateBuiltInDecoration(glslangBuiltIn, false);
2708 break;
2709 default:
2710 // Capabilities were already generated when the struct was declared.
2711 break;
2712 }
John Kessenichebb50532016-05-16 19:22:05 -06002713}
2714
John Kessenich6fccb3c2016-09-19 16:01:41 -06002715bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002716{
John Kessenicheee9d532016-09-19 18:09:30 -06002717 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002718}
2719
2720// Make all the functions, skeletally, without actually visiting their bodies.
2721void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2722{
2723 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2724 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002725 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002726 continue;
2727
2728 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002729 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002730 //
qining25262b32016-05-06 17:25:16 -04002731 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002732 // function. What it is an address of varies:
2733 //
John Kessenich4bf71552016-09-02 11:20:21 -06002734 // - "in" parameters not marked as "const" can be written to without modifying the calling
2735 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002736 //
2737 // - "const in" parameters can just be the r-value, as no writes need occur.
2738 //
John Kessenich4bf71552016-09-02 11:20:21 -06002739 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2740 // 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 -06002741
2742 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002743 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002744 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2745
2746 for (int p = 0; p < (int)parameters.size(); ++p) {
2747 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2748 spv::Id typeId = convertGlslangToSpvType(paramType);
steve-lunargdd8287a2017-02-23 18:04:12 -07002749 if (paramType.containsOpaque() ||
John Kessenich4960baa2017-03-19 18:09:59 -06002750 (paramType.getBasicType() == glslang::EbtBlock &&
2751 paramType.getQualifier().storage == glslang::EvqBuffer))
Jason Ekstranded15ef12016-06-08 13:54:48 -07002752 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2753 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002754 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2755 else
John Kessenich4bf71552016-09-02 11:20:21 -06002756 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002757 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002758 paramTypes.push_back(typeId);
2759 }
2760
2761 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002762 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2763 convertGlslangToSpvType(glslFunction->getType()),
2764 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002765
2766 // Track function to emit/call later
2767 functionMap[glslFunction->getName().c_str()] = function;
2768
2769 // Set the parameter id's
2770 for (int p = 0; p < (int)parameters.size(); ++p) {
2771 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2772 // give a name too
2773 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2774 }
2775 }
2776}
2777
2778// Process all the initializers, while skipping the functions and link objects
2779void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2780{
2781 builder.setBuildPoint(shaderEntry->getLastBlock());
2782 for (int i = 0; i < (int)initializers.size(); ++i) {
2783 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2784 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2785
2786 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002787 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002788 initializer->traverse(this);
2789 }
2790 }
2791}
2792
2793// Process all the functions, while skipping initializers.
2794void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2795{
2796 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2797 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002798 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002799 node->traverse(this);
2800 }
2801}
2802
2803void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2804{
qining25262b32016-05-06 17:25:16 -04002805 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002806 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002807 currentFunction = functionMap[node->getName().c_str()];
2808 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002809 builder.setBuildPoint(functionBlock);
2810}
2811
Rex Xu04db3f52015-09-16 11:44:02 +08002812void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002813{
Rex Xufc618912015-09-09 16:42:49 +08002814 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002815
2816 glslang::TSampler sampler = {};
2817 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002818 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002819 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2820 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2821 }
2822
John Kessenich140f3df2015-06-26 16:58:36 -06002823 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2824 builder.clearAccessChain();
2825 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002826
2827 // Special case l-value operands
2828 bool lvalue = false;
2829 switch (node.getOp()) {
2830 case glslang::EOpImageAtomicAdd:
2831 case glslang::EOpImageAtomicMin:
2832 case glslang::EOpImageAtomicMax:
2833 case glslang::EOpImageAtomicAnd:
2834 case glslang::EOpImageAtomicOr:
2835 case glslang::EOpImageAtomicXor:
2836 case glslang::EOpImageAtomicExchange:
2837 case glslang::EOpImageAtomicCompSwap:
2838 if (i == 0)
2839 lvalue = true;
2840 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002841 case glslang::EOpSparseImageLoad:
2842 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2843 lvalue = true;
2844 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002845 case glslang::EOpSparseTexture:
2846 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2847 lvalue = true;
2848 break;
2849 case glslang::EOpSparseTextureClamp:
2850 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2851 lvalue = true;
2852 break;
2853 case glslang::EOpSparseTextureLod:
2854 case glslang::EOpSparseTextureOffset:
2855 if (i == 3)
2856 lvalue = true;
2857 break;
2858 case glslang::EOpSparseTextureFetch:
2859 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2860 lvalue = true;
2861 break;
2862 case glslang::EOpSparseTextureFetchOffset:
2863 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2864 lvalue = true;
2865 break;
2866 case glslang::EOpSparseTextureLodOffset:
2867 case glslang::EOpSparseTextureGrad:
2868 case glslang::EOpSparseTextureOffsetClamp:
2869 if (i == 4)
2870 lvalue = true;
2871 break;
2872 case glslang::EOpSparseTextureGradOffset:
2873 case glslang::EOpSparseTextureGradClamp:
2874 if (i == 5)
2875 lvalue = true;
2876 break;
2877 case glslang::EOpSparseTextureGradOffsetClamp:
2878 if (i == 6)
2879 lvalue = true;
2880 break;
2881 case glslang::EOpSparseTextureGather:
2882 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2883 lvalue = true;
2884 break;
2885 case glslang::EOpSparseTextureGatherOffset:
2886 case glslang::EOpSparseTextureGatherOffsets:
2887 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2888 lvalue = true;
2889 break;
Rex Xufc618912015-09-09 16:42:49 +08002890 default:
2891 break;
2892 }
2893
Rex Xu6b86d492015-09-16 17:48:22 +08002894 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002895 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002896 else
John Kessenich32cfd492016-02-02 12:37:46 -07002897 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002898 }
2899}
2900
John Kessenichfc51d282015-08-19 13:34:18 -06002901void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002902{
John Kessenichfc51d282015-08-19 13:34:18 -06002903 builder.clearAccessChain();
2904 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002905 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002906}
John Kessenich140f3df2015-06-26 16:58:36 -06002907
John Kessenichfc51d282015-08-19 13:34:18 -06002908spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2909{
Rex Xufc618912015-09-09 16:42:49 +08002910 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002911 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002912 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002913 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002914
John Kessenichfc51d282015-08-19 13:34:18 -06002915 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002916 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2917 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2918 std::vector<spv::Id> arguments;
2919 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002920 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002921 else
2922 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002923 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002924
2925 spv::Builder::TextureParameters params = { };
2926 params.sampler = arguments[0];
2927
Rex Xu04db3f52015-09-16 11:44:02 +08002928 glslang::TCrackedTextureOp cracked;
2929 node->crackTexture(sampler, cracked);
2930
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002931 const bool isUnsignedResult =
2932 node->getType().getBasicType() == glslang::EbtUint64 ||
2933 node->getType().getBasicType() == glslang::EbtUint;
2934
John Kessenichfc51d282015-08-19 13:34:18 -06002935 // Check for queries
2936 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002937 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2938 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002939 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002940
John Kessenichfc51d282015-08-19 13:34:18 -06002941 switch (node->getOp()) {
2942 case glslang::EOpImageQuerySize:
2943 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002944 if (arguments.size() > 1) {
2945 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002946 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002947 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002948 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002949 case glslang::EOpImageQuerySamples:
2950 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002951 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002952 case glslang::EOpTextureQueryLod:
2953 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002954 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002955 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002956 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08002957 case glslang::EOpSparseTexelsResident:
2958 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002959 default:
2960 assert(0);
2961 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002962 }
John Kessenich140f3df2015-06-26 16:58:36 -06002963 }
2964
Rex Xufc618912015-09-09 16:42:49 +08002965 // Check for image functions other than queries
2966 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002967 std::vector<spv::Id> operands;
2968 auto opIt = arguments.begin();
2969 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002970
2971 // Handle subpass operations
2972 // TODO: GLSL should change to have the "MS" only on the type rather than the
2973 // built-in function.
2974 if (cracked.subpass) {
2975 // add on the (0,0) coordinate
2976 spv::Id zero = builder.makeIntConstant(0);
2977 std::vector<spv::Id> comps;
2978 comps.push_back(zero);
2979 comps.push_back(zero);
2980 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2981 if (sampler.ms) {
2982 operands.push_back(spv::ImageOperandsSampleMask);
2983 operands.push_back(*(opIt++));
2984 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002985 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002986 }
2987
John Kessenich56bab042015-09-16 10:54:31 -06002988 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002989 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002990 if (sampler.ms) {
2991 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002992 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002993 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002994 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2995 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002996 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002997 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002998 if (sampler.ms) {
2999 operands.push_back(*(opIt + 1));
3000 operands.push_back(spv::ImageOperandsSampleMask);
3001 operands.push_back(*opIt);
3002 } else
3003 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003004 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003005 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3006 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003007 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003008 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3009 builder.addCapability(spv::CapabilitySparseResidency);
3010 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3011 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3012
3013 if (sampler.ms) {
3014 operands.push_back(spv::ImageOperandsSampleMask);
3015 operands.push_back(*opIt++);
3016 }
3017
3018 // Create the return type that was a special structure
3019 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003020 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003021 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3022 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3023
3024 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3025
3026 // Decode the return type
3027 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3028 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003029 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003030 // Process image atomic operations
3031
3032 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3033 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003034 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003035
John Kessenich8c8505c2016-07-26 12:50:38 -06003036 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003037 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003038
3039 std::vector<spv::Id> operands;
3040 operands.push_back(pointer);
3041 for (; opIt != arguments.end(); ++opIt)
3042 operands.push_back(*opIt);
3043
John Kessenich8c8505c2016-07-26 12:50:38 -06003044 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003045 }
3046 }
3047
3048 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003049 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003050 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3051
John Kessenichfc51d282015-08-19 13:34:18 -06003052 // check for bias argument
3053 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003054 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003055 int nonBiasArgCount = 2;
3056 if (cracked.offset)
3057 ++nonBiasArgCount;
3058 if (cracked.grad)
3059 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003060 if (cracked.lodClamp)
3061 ++nonBiasArgCount;
3062 if (sparse)
3063 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003064
3065 if ((int)arguments.size() > nonBiasArgCount)
3066 bias = true;
3067 }
3068
John Kessenicha5c33d62016-06-02 23:45:21 -06003069 // See if the sampler param should really be just the SPV image part
3070 if (cracked.fetch) {
3071 // a fetch needs to have the image extracted first
3072 if (builder.isSampledImage(params.sampler))
3073 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3074 }
3075
John Kessenichfc51d282015-08-19 13:34:18 -06003076 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003077
John Kessenichfc51d282015-08-19 13:34:18 -06003078 params.coords = arguments[1];
3079 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003080 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003081
3082 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003083 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003084 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003085 ++extraArgs;
3086 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003087 params.Dref = arguments[2];
3088 ++extraArgs;
3089 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003090 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003091 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003092 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003093 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003094 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003095 dRefComp = builder.getNumComponents(params.coords) - 1;
3096 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003097 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3098 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003099
3100 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003101 if (cracked.lod) {
3102 params.lod = arguments[2];
3103 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003104 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3105 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3106 noImplicitLod = true;
3107 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003108
3109 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003110 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003111 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003112 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003113 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003114
3115 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003116 if (cracked.grad) {
3117 params.gradX = arguments[2 + extraArgs];
3118 params.gradY = arguments[3 + extraArgs];
3119 extraArgs += 2;
3120 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003121
3122 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003123 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003124 params.offset = arguments[2 + extraArgs];
3125 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003126 } else if (cracked.offsets) {
3127 params.offsets = arguments[2 + extraArgs];
3128 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003130
3131 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003132 if (cracked.lodClamp) {
3133 params.lodClamp = arguments[2 + extraArgs];
3134 ++extraArgs;
3135 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003136
3137 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003138 if (sparse) {
3139 params.texelOut = arguments[2 + extraArgs];
3140 ++extraArgs;
3141 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003142
3143 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003144 if (bias) {
3145 params.bias = arguments[2 + extraArgs];
3146 ++extraArgs;
3147 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003148
3149 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003150 if (cracked.gather && ! sampler.shadow) {
3151 // default component is 0, if missing, otherwise an argument
3152 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003153 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003154 ++extraArgs;
3155 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003156 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003157 }
3158 }
John Kessenichfc51d282015-08-19 13:34:18 -06003159
John Kessenich65336482016-06-16 14:06:26 -06003160 // projective component (might not to move)
3161 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3162 // are divided by the last component of P."
3163 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3164 // unused components will appear after all used components."
3165 if (cracked.proj) {
3166 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3167 int projTargetComp;
3168 switch (sampler.dim) {
3169 case glslang::Esd1D: projTargetComp = 1; break;
3170 case glslang::Esd2D: projTargetComp = 2; break;
3171 case glslang::EsdRect: projTargetComp = 2; break;
3172 default: projTargetComp = projSourceComp; break;
3173 }
3174 // copy the projective coordinate if we have to
3175 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003176 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003177 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3178 projSourceComp);
3179 params.coords = builder.createCompositeInsert(projComp, params.coords,
3180 builder.getTypeId(params.coords), projTargetComp);
3181 }
3182 }
3183
John Kessenich8c8505c2016-07-26 12:50:38 -06003184 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003185}
3186
3187spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3188{
3189 // Grab the function's pointer from the previously created function
3190 spv::Function* function = functionMap[node->getName().c_str()];
3191 if (! function)
3192 return 0;
3193
3194 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3195 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3196
3197 // See comments in makeFunctions() for details about the semantics for parameter passing.
3198 //
3199 // These imply we need a four step process:
3200 // 1. Evaluate the arguments
3201 // 2. Allocate and make copies of in, out, and inout arguments
3202 // 3. Make the call
3203 // 4. Copy back the results
3204
3205 // 1. Evaluate the arguments
3206 std::vector<spv::Builder::AccessChain> lValues;
3207 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003208 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003209 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003210 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003211 // build l-value
3212 builder.clearAccessChain();
3213 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003214 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003215 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003216 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003217 // save l-value
3218 lValues.push_back(builder.getAccessChain());
3219 } else {
3220 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003221 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003222 }
3223 }
3224
3225 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3226 // copy the original into that space.
3227 //
3228 // Also, build up the list of actual arguments to pass in for the call
3229 int lValueCount = 0;
3230 int rValueCount = 0;
3231 std::vector<spv::Id> spvArgs;
3232 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003233 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003234 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003235 if (paramType.containsOpaque() ||
3236 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003237 builder.setAccessChain(lValues[lValueCount]);
3238 arg = builder.accessChainGetLValue();
3239 ++lValueCount;
3240 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003241 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003242 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3243 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3244 // need to copy the input into output space
3245 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003246 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003247 builder.clearAccessChain();
3248 builder.setAccessChainLValue(arg);
3249 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003250 }
3251 ++lValueCount;
3252 } else {
3253 arg = rValues[rValueCount];
3254 ++rValueCount;
3255 }
3256 spvArgs.push_back(arg);
3257 }
3258
3259 // 3. Make the call.
3260 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003261 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003262
3263 // 4. Copy back out an "out" arguments.
3264 lValueCount = 0;
3265 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003266 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003267 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3268 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3269 spv::Id copy = builder.createLoad(spvArgs[a]);
3270 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003271 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003272 }
3273 ++lValueCount;
3274 }
3275 }
3276
3277 return result;
3278}
3279
3280// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003281spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3282 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003283 spv::Id typeId, spv::Id left, spv::Id right,
3284 glslang::TBasicType typeProxy, bool reduceComparison)
3285{
Rex Xu8ff43de2016-04-22 16:51:45 +08003286 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003287#ifdef AMD_EXTENSIONS
3288 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3289#else
John Kessenich140f3df2015-06-26 16:58:36 -06003290 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003291#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003292 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003293
3294 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003295 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003296 bool comparison = false;
3297
3298 switch (op) {
3299 case glslang::EOpAdd:
3300 case glslang::EOpAddAssign:
3301 if (isFloat)
3302 binOp = spv::OpFAdd;
3303 else
3304 binOp = spv::OpIAdd;
3305 break;
3306 case glslang::EOpSub:
3307 case glslang::EOpSubAssign:
3308 if (isFloat)
3309 binOp = spv::OpFSub;
3310 else
3311 binOp = spv::OpISub;
3312 break;
3313 case glslang::EOpMul:
3314 case glslang::EOpMulAssign:
3315 if (isFloat)
3316 binOp = spv::OpFMul;
3317 else
3318 binOp = spv::OpIMul;
3319 break;
3320 case glslang::EOpVectorTimesScalar:
3321 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003322 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003323 if (builder.isVector(right))
3324 std::swap(left, right);
3325 assert(builder.isScalar(right));
3326 needMatchingVectors = false;
3327 binOp = spv::OpVectorTimesScalar;
3328 } else
3329 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003330 break;
3331 case glslang::EOpVectorTimesMatrix:
3332 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003333 binOp = spv::OpVectorTimesMatrix;
3334 break;
3335 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003336 binOp = spv::OpMatrixTimesVector;
3337 break;
3338 case glslang::EOpMatrixTimesScalar:
3339 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003340 binOp = spv::OpMatrixTimesScalar;
3341 break;
3342 case glslang::EOpMatrixTimesMatrix:
3343 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003344 binOp = spv::OpMatrixTimesMatrix;
3345 break;
3346 case glslang::EOpOuterProduct:
3347 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003348 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003349 break;
3350
3351 case glslang::EOpDiv:
3352 case glslang::EOpDivAssign:
3353 if (isFloat)
3354 binOp = spv::OpFDiv;
3355 else if (isUnsigned)
3356 binOp = spv::OpUDiv;
3357 else
3358 binOp = spv::OpSDiv;
3359 break;
3360 case glslang::EOpMod:
3361 case glslang::EOpModAssign:
3362 if (isFloat)
3363 binOp = spv::OpFMod;
3364 else if (isUnsigned)
3365 binOp = spv::OpUMod;
3366 else
3367 binOp = spv::OpSMod;
3368 break;
3369 case glslang::EOpRightShift:
3370 case glslang::EOpRightShiftAssign:
3371 if (isUnsigned)
3372 binOp = spv::OpShiftRightLogical;
3373 else
3374 binOp = spv::OpShiftRightArithmetic;
3375 break;
3376 case glslang::EOpLeftShift:
3377 case glslang::EOpLeftShiftAssign:
3378 binOp = spv::OpShiftLeftLogical;
3379 break;
3380 case glslang::EOpAnd:
3381 case glslang::EOpAndAssign:
3382 binOp = spv::OpBitwiseAnd;
3383 break;
3384 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003385 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003386 binOp = spv::OpLogicalAnd;
3387 break;
3388 case glslang::EOpInclusiveOr:
3389 case glslang::EOpInclusiveOrAssign:
3390 binOp = spv::OpBitwiseOr;
3391 break;
3392 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003393 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003394 binOp = spv::OpLogicalOr;
3395 break;
3396 case glslang::EOpExclusiveOr:
3397 case glslang::EOpExclusiveOrAssign:
3398 binOp = spv::OpBitwiseXor;
3399 break;
3400 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003401 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003402 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003403 break;
3404
3405 case glslang::EOpLessThan:
3406 case glslang::EOpGreaterThan:
3407 case glslang::EOpLessThanEqual:
3408 case glslang::EOpGreaterThanEqual:
3409 case glslang::EOpEqual:
3410 case glslang::EOpNotEqual:
3411 case glslang::EOpVectorEqual:
3412 case glslang::EOpVectorNotEqual:
3413 comparison = true;
3414 break;
3415 default:
3416 break;
3417 }
3418
John Kessenich7c1aa102015-10-15 13:29:11 -06003419 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003420 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003421 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003422 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003423 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003424
3425 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003426 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003427 builder.promoteScalar(precision, left, right);
3428
qining25262b32016-05-06 17:25:16 -04003429 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3430 addDecoration(result, noContraction);
3431 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003432 }
3433
3434 if (! comparison)
3435 return 0;
3436
John Kessenich7c1aa102015-10-15 13:29:11 -06003437 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003438
John Kessenich4583b612016-08-07 19:14:22 -06003439 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3440 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003441 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003442
3443 switch (op) {
3444 case glslang::EOpLessThan:
3445 if (isFloat)
3446 binOp = spv::OpFOrdLessThan;
3447 else if (isUnsigned)
3448 binOp = spv::OpULessThan;
3449 else
3450 binOp = spv::OpSLessThan;
3451 break;
3452 case glslang::EOpGreaterThan:
3453 if (isFloat)
3454 binOp = spv::OpFOrdGreaterThan;
3455 else if (isUnsigned)
3456 binOp = spv::OpUGreaterThan;
3457 else
3458 binOp = spv::OpSGreaterThan;
3459 break;
3460 case glslang::EOpLessThanEqual:
3461 if (isFloat)
3462 binOp = spv::OpFOrdLessThanEqual;
3463 else if (isUnsigned)
3464 binOp = spv::OpULessThanEqual;
3465 else
3466 binOp = spv::OpSLessThanEqual;
3467 break;
3468 case glslang::EOpGreaterThanEqual:
3469 if (isFloat)
3470 binOp = spv::OpFOrdGreaterThanEqual;
3471 else if (isUnsigned)
3472 binOp = spv::OpUGreaterThanEqual;
3473 else
3474 binOp = spv::OpSGreaterThanEqual;
3475 break;
3476 case glslang::EOpEqual:
3477 case glslang::EOpVectorEqual:
3478 if (isFloat)
3479 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003480 else if (isBool)
3481 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 else
3483 binOp = spv::OpIEqual;
3484 break;
3485 case glslang::EOpNotEqual:
3486 case glslang::EOpVectorNotEqual:
3487 if (isFloat)
3488 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003489 else if (isBool)
3490 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003491 else
3492 binOp = spv::OpINotEqual;
3493 break;
3494 default:
3495 break;
3496 }
3497
qining25262b32016-05-06 17:25:16 -04003498 if (binOp != spv::OpNop) {
3499 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3500 addDecoration(result, noContraction);
3501 return builder.setPrecision(result, precision);
3502 }
John Kessenich140f3df2015-06-26 16:58:36 -06003503
3504 return 0;
3505}
3506
John Kessenich04bb8a02015-12-12 12:28:14 -07003507//
3508// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3509// These can be any of:
3510//
3511// matrix * scalar
3512// scalar * matrix
3513// matrix * matrix linear algebraic
3514// matrix * vector
3515// vector * matrix
3516// matrix * matrix componentwise
3517// matrix op matrix op in {+, -, /}
3518// matrix op scalar op in {+, -, /}
3519// scalar op matrix op in {+, -, /}
3520//
qining25262b32016-05-06 17:25:16 -04003521spv::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 -07003522{
3523 bool firstClass = true;
3524
3525 // First, handle first-class matrix operations (* and matrix/scalar)
3526 switch (op) {
3527 case spv::OpFDiv:
3528 if (builder.isMatrix(left) && builder.isScalar(right)) {
3529 // turn matrix / scalar into a multiply...
3530 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3531 op = spv::OpMatrixTimesScalar;
3532 } else
3533 firstClass = false;
3534 break;
3535 case spv::OpMatrixTimesScalar:
3536 if (builder.isMatrix(right))
3537 std::swap(left, right);
3538 assert(builder.isScalar(right));
3539 break;
3540 case spv::OpVectorTimesMatrix:
3541 assert(builder.isVector(left));
3542 assert(builder.isMatrix(right));
3543 break;
3544 case spv::OpMatrixTimesVector:
3545 assert(builder.isMatrix(left));
3546 assert(builder.isVector(right));
3547 break;
3548 case spv::OpMatrixTimesMatrix:
3549 assert(builder.isMatrix(left));
3550 assert(builder.isMatrix(right));
3551 break;
3552 default:
3553 firstClass = false;
3554 break;
3555 }
3556
qining25262b32016-05-06 17:25:16 -04003557 if (firstClass) {
3558 spv::Id result = builder.createBinOp(op, typeId, left, right);
3559 addDecoration(result, noContraction);
3560 return builder.setPrecision(result, precision);
3561 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003562
LoopDawg592860c2016-06-09 08:57:35 -06003563 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003564 // The result type of all of them is the same type as the (a) matrix operand.
3565 // The algorithm is to:
3566 // - break the matrix(es) into vectors
3567 // - smear any scalar to a vector
3568 // - do vector operations
3569 // - make a matrix out the vector results
3570 switch (op) {
3571 case spv::OpFAdd:
3572 case spv::OpFSub:
3573 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003574 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003575 case spv::OpFMul:
3576 {
3577 // one time set up...
3578 bool leftMat = builder.isMatrix(left);
3579 bool rightMat = builder.isMatrix(right);
3580 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3581 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3582 spv::Id scalarType = builder.getScalarTypeId(typeId);
3583 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3584 std::vector<spv::Id> results;
3585 spv::Id smearVec = spv::NoResult;
3586 if (builder.isScalar(left))
3587 smearVec = builder.smearScalar(precision, left, vecType);
3588 else if (builder.isScalar(right))
3589 smearVec = builder.smearScalar(precision, right, vecType);
3590
3591 // do each vector op
3592 for (unsigned int c = 0; c < numCols; ++c) {
3593 std::vector<unsigned int> indexes;
3594 indexes.push_back(c);
3595 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3596 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003597 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3598 addDecoration(result, noContraction);
3599 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003600 }
3601
3602 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003603 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003604 }
3605 default:
3606 assert(0);
3607 return spv::NoResult;
3608 }
3609}
3610
qining25262b32016-05-06 17:25:16 -04003611spv::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 -06003612{
3613 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003614 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003615 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003616 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003617#ifdef AMD_EXTENSIONS
3618 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3619#else
Rex Xu04db3f52015-09-16 11:44:02 +08003620 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003621#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003622
3623 switch (op) {
3624 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003625 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003626 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003627 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003628 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003629 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003630 unaryOp = spv::OpSNegate;
3631 break;
3632
3633 case glslang::EOpLogicalNot:
3634 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003635 unaryOp = spv::OpLogicalNot;
3636 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003637 case glslang::EOpBitwiseNot:
3638 unaryOp = spv::OpNot;
3639 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003640
John Kessenich140f3df2015-06-26 16:58:36 -06003641 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003642 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003643 break;
3644 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003645 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003646 break;
3647 case glslang::EOpTranspose:
3648 unaryOp = spv::OpTranspose;
3649 break;
3650
3651 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003652 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003653 break;
3654 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003655 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003656 break;
3657 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003658 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003659 break;
3660 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003661 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003662 break;
3663 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003664 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003665 break;
3666 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003667 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003668 break;
3669 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003670 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003671 break;
3672 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003673 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003674 break;
3675
3676 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003677 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003678 break;
3679 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003680 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003681 break;
3682 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003683 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003684 break;
3685 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003686 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003689 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003690 break;
3691 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003692 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003693 break;
3694
3695 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701
3702 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003703 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003704 break;
3705 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003706 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003707 break;
3708 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003709 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 break;
3717 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003718 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720
3721 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003722 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003723 break;
3724 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003731 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003732 break;
3733 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003734 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003735 break;
3736 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003738 break;
3739
3740 case glslang::EOpIsNan:
3741 unaryOp = spv::OpIsNan;
3742 break;
3743 case glslang::EOpIsInf:
3744 unaryOp = spv::OpIsInf;
3745 break;
LoopDawg592860c2016-06-09 08:57:35 -06003746 case glslang::EOpIsFinite:
3747 unaryOp = spv::OpIsFinite;
3748 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003749
Rex Xucbc426e2015-12-15 16:03:10 +08003750 case glslang::EOpFloatBitsToInt:
3751 case glslang::EOpFloatBitsToUint:
3752 case glslang::EOpIntBitsToFloat:
3753 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003754 case glslang::EOpDoubleBitsToInt64:
3755 case glslang::EOpDoubleBitsToUint64:
3756 case glslang::EOpInt64BitsToDouble:
3757 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003758 unaryOp = spv::OpBitcast;
3759 break;
3760
John Kessenich140f3df2015-06-26 16:58:36 -06003761 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003762 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003763 break;
3764 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003765 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003766 break;
3767 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003768 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003769 break;
3770 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
3773 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003774 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003775 break;
3776 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003779 case glslang::EOpPackSnorm4x8:
3780 libCall = spv::GLSLstd450PackSnorm4x8;
3781 break;
3782 case glslang::EOpUnpackSnorm4x8:
3783 libCall = spv::GLSLstd450UnpackSnorm4x8;
3784 break;
3785 case glslang::EOpPackUnorm4x8:
3786 libCall = spv::GLSLstd450PackUnorm4x8;
3787 break;
3788 case glslang::EOpUnpackUnorm4x8:
3789 libCall = spv::GLSLstd450UnpackUnorm4x8;
3790 break;
3791 case glslang::EOpPackDouble2x32:
3792 libCall = spv::GLSLstd450PackDouble2x32;
3793 break;
3794 case glslang::EOpUnpackDouble2x32:
3795 libCall = spv::GLSLstd450UnpackDouble2x32;
3796 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003797
Rex Xu8ff43de2016-04-22 16:51:45 +08003798 case glslang::EOpPackInt2x32:
3799 case glslang::EOpUnpackInt2x32:
3800 case glslang::EOpPackUint2x32:
3801 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003802 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003803 break;
3804
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003805#ifdef AMD_EXTENSIONS
3806 case glslang::EOpPackFloat2x16:
3807 case glslang::EOpUnpackFloat2x16:
3808 unaryOp = spv::OpBitcast;
3809 break;
3810#endif
3811
John Kessenich140f3df2015-06-26 16:58:36 -06003812 case glslang::EOpDPdx:
3813 unaryOp = spv::OpDPdx;
3814 break;
3815 case glslang::EOpDPdy:
3816 unaryOp = spv::OpDPdy;
3817 break;
3818 case glslang::EOpFwidth:
3819 unaryOp = spv::OpFwidth;
3820 break;
3821 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003822 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003823 unaryOp = spv::OpDPdxFine;
3824 break;
3825 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003826 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003827 unaryOp = spv::OpDPdyFine;
3828 break;
3829 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003830 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003831 unaryOp = spv::OpFwidthFine;
3832 break;
3833 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003834 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003835 unaryOp = spv::OpDPdxCoarse;
3836 break;
3837 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003838 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003839 unaryOp = spv::OpDPdyCoarse;
3840 break;
3841 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003842 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003843 unaryOp = spv::OpFwidthCoarse;
3844 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003845 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003846 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003847 libCall = spv::GLSLstd450InterpolateAtCentroid;
3848 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003849 case glslang::EOpAny:
3850 unaryOp = spv::OpAny;
3851 break;
3852 case glslang::EOpAll:
3853 unaryOp = spv::OpAll;
3854 break;
3855
3856 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 if (isFloat)
3858 libCall = spv::GLSLstd450FAbs;
3859 else
3860 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003861 break;
3862 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003863 if (isFloat)
3864 libCall = spv::GLSLstd450FSign;
3865 else
3866 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003867 break;
3868
John Kessenichfc51d282015-08-19 13:34:18 -06003869 case glslang::EOpAtomicCounterIncrement:
3870 case glslang::EOpAtomicCounterDecrement:
3871 case glslang::EOpAtomicCounter:
3872 {
3873 // Handle all of the atomics in one place, in createAtomicOperation()
3874 std::vector<spv::Id> operands;
3875 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003876 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003877 }
3878
John Kessenichfc51d282015-08-19 13:34:18 -06003879 case glslang::EOpBitFieldReverse:
3880 unaryOp = spv::OpBitReverse;
3881 break;
3882 case glslang::EOpBitCount:
3883 unaryOp = spv::OpBitCount;
3884 break;
3885 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003886 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003887 break;
3888 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003889 if (isUnsigned)
3890 libCall = spv::GLSLstd450FindUMsb;
3891 else
3892 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003893 break;
3894
Rex Xu574ab042016-04-14 16:53:07 +08003895 case glslang::EOpBallot:
3896 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003897 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003898 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003899 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003900#ifdef AMD_EXTENSIONS
3901 case glslang::EOpMinInvocations:
3902 case glslang::EOpMaxInvocations:
3903 case glslang::EOpAddInvocations:
3904 case glslang::EOpMinInvocationsNonUniform:
3905 case glslang::EOpMaxInvocationsNonUniform:
3906 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003907 case glslang::EOpMinInvocationsInclusiveScan:
3908 case glslang::EOpMaxInvocationsInclusiveScan:
3909 case glslang::EOpAddInvocationsInclusiveScan:
3910 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3911 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3912 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3913 case glslang::EOpMinInvocationsExclusiveScan:
3914 case glslang::EOpMaxInvocationsExclusiveScan:
3915 case glslang::EOpAddInvocationsExclusiveScan:
3916 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3917 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3918 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003919#endif
Rex Xu51596642016-09-21 18:56:12 +08003920 {
3921 std::vector<spv::Id> operands;
3922 operands.push_back(operand);
3923 return createInvocationsOperation(op, typeId, operands, typeProxy);
3924 }
Rex Xu9d93a232016-05-05 12:30:44 +08003925
3926#ifdef AMD_EXTENSIONS
3927 case glslang::EOpMbcnt:
3928 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3929 libCall = spv::MbcntAMD;
3930 break;
3931
3932 case glslang::EOpCubeFaceIndex:
3933 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3934 libCall = spv::CubeFaceIndexAMD;
3935 break;
3936
3937 case glslang::EOpCubeFaceCoord:
3938 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3939 libCall = spv::CubeFaceCoordAMD;
3940 break;
3941#endif
Rex Xu338b1852016-05-05 20:38:33 +08003942
John Kessenich140f3df2015-06-26 16:58:36 -06003943 default:
3944 return 0;
3945 }
3946
3947 spv::Id id;
3948 if (libCall >= 0) {
3949 std::vector<spv::Id> args;
3950 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003951 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003952 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003953 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003954 }
John Kessenich140f3df2015-06-26 16:58:36 -06003955
qining25262b32016-05-06 17:25:16 -04003956 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003957 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003958}
3959
John Kessenich7a53f762016-01-20 11:19:27 -07003960// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003961spv::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 -07003962{
3963 // Handle unary operations vector by vector.
3964 // The result type is the same type as the original type.
3965 // The algorithm is to:
3966 // - break the matrix into vectors
3967 // - apply the operation to each vector
3968 // - make a matrix out the vector results
3969
3970 // get the types sorted out
3971 int numCols = builder.getNumColumns(operand);
3972 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003973 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3974 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003975 std::vector<spv::Id> results;
3976
3977 // do each vector op
3978 for (int c = 0; c < numCols; ++c) {
3979 std::vector<unsigned int> indexes;
3980 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003981 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3982 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3983 addDecoration(destVec, noContraction);
3984 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003985 }
3986
3987 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003988 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003989}
3990
Rex Xu73e3ce72016-04-27 18:48:17 +08003991spv::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 -06003992{
3993 spv::Op convOp = spv::OpNop;
3994 spv::Id zero = 0;
3995 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003996 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003997
3998 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3999
4000 switch (op) {
4001 case glslang::EOpConvIntToBool:
4002 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004003 case glslang::EOpConvInt64ToBool:
4004 case glslang::EOpConvUint64ToBool:
4005 zero = (op == glslang::EOpConvInt64ToBool ||
4006 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004007 zero = makeSmearedConstant(zero, vectorSize);
4008 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4009
4010 case glslang::EOpConvFloatToBool:
4011 zero = builder.makeFloatConstant(0.0F);
4012 zero = makeSmearedConstant(zero, vectorSize);
4013 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4014
4015 case glslang::EOpConvDoubleToBool:
4016 zero = builder.makeDoubleConstant(0.0);
4017 zero = makeSmearedConstant(zero, vectorSize);
4018 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4019
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004020#ifdef AMD_EXTENSIONS
4021 case glslang::EOpConvFloat16ToBool:
4022 zero = builder.makeFloat16Constant(0.0F);
4023 zero = makeSmearedConstant(zero, vectorSize);
4024 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4025#endif
4026
John Kessenich140f3df2015-06-26 16:58:36 -06004027 case glslang::EOpConvBoolToFloat:
4028 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004029 zero = builder.makeFloatConstant(0.0F);
4030 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004031 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004032
John Kessenich140f3df2015-06-26 16:58:36 -06004033 case glslang::EOpConvBoolToDouble:
4034 convOp = spv::OpSelect;
4035 zero = builder.makeDoubleConstant(0.0);
4036 one = builder.makeDoubleConstant(1.0);
4037 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004038
4039#ifdef AMD_EXTENSIONS
4040 case glslang::EOpConvBoolToFloat16:
4041 convOp = spv::OpSelect;
4042 zero = builder.makeFloat16Constant(0.0F);
4043 one = builder.makeFloat16Constant(1.0F);
4044 break;
4045#endif
4046
John Kessenich140f3df2015-06-26 16:58:36 -06004047 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004048 case glslang::EOpConvBoolToInt64:
4049 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4050 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004051 convOp = spv::OpSelect;
4052 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004053
John Kessenich140f3df2015-06-26 16:58:36 -06004054 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004055 case glslang::EOpConvBoolToUint64:
4056 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4057 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004058 convOp = spv::OpSelect;
4059 break;
4060
4061 case glslang::EOpConvIntToFloat:
4062 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004063 case glslang::EOpConvInt64ToFloat:
4064 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004065#ifdef AMD_EXTENSIONS
4066 case glslang::EOpConvIntToFloat16:
4067 case glslang::EOpConvInt64ToFloat16:
4068#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004069 convOp = spv::OpConvertSToF;
4070 break;
4071
4072 case glslang::EOpConvUintToFloat:
4073 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004074 case glslang::EOpConvUint64ToFloat:
4075 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004076#ifdef AMD_EXTENSIONS
4077 case glslang::EOpConvUintToFloat16:
4078 case glslang::EOpConvUint64ToFloat16:
4079#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004080 convOp = spv::OpConvertUToF;
4081 break;
4082
4083 case glslang::EOpConvDoubleToFloat:
4084 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004085#ifdef AMD_EXTENSIONS
4086 case glslang::EOpConvDoubleToFloat16:
4087 case glslang::EOpConvFloat16ToDouble:
4088 case glslang::EOpConvFloatToFloat16:
4089 case glslang::EOpConvFloat16ToFloat:
4090#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004091 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004092 if (builder.isMatrixType(destType))
4093 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095
4096 case glslang::EOpConvFloatToInt:
4097 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004098 case glslang::EOpConvFloatToInt64:
4099 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004100#ifdef AMD_EXTENSIONS
4101 case glslang::EOpConvFloat16ToInt:
4102 case glslang::EOpConvFloat16ToInt64:
4103#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004104 convOp = spv::OpConvertFToS;
4105 break;
4106
4107 case glslang::EOpConvUintToInt:
4108 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004109 case glslang::EOpConvUint64ToInt64:
4110 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004111 if (builder.isInSpecConstCodeGenMode()) {
4112 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004113 zero = (op == glslang::EOpConvUint64ToInt64 ||
4114 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004115 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004116 // Use OpIAdd, instead of OpBitcast to do the conversion when
4117 // generating for OpSpecConstantOp instruction.
4118 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4119 }
4120 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004121 convOp = spv::OpBitcast;
4122 break;
4123
4124 case glslang::EOpConvFloatToUint:
4125 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004126 case glslang::EOpConvFloatToUint64:
4127 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004128#ifdef AMD_EXTENSIONS
4129 case glslang::EOpConvFloat16ToUint:
4130 case glslang::EOpConvFloat16ToUint64:
4131#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004132 convOp = spv::OpConvertFToU;
4133 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004134
4135 case glslang::EOpConvIntToInt64:
4136 case glslang::EOpConvInt64ToInt:
4137 convOp = spv::OpSConvert;
4138 break;
4139
4140 case glslang::EOpConvUintToUint64:
4141 case glslang::EOpConvUint64ToUint:
4142 convOp = spv::OpUConvert;
4143 break;
4144
4145 case glslang::EOpConvIntToUint64:
4146 case glslang::EOpConvInt64ToUint:
4147 case glslang::EOpConvUint64ToInt:
4148 case glslang::EOpConvUintToInt64:
4149 // OpSConvert/OpUConvert + OpBitCast
4150 switch (op) {
4151 case glslang::EOpConvIntToUint64:
4152 convOp = spv::OpSConvert;
4153 type = builder.makeIntType(64);
4154 break;
4155 case glslang::EOpConvInt64ToUint:
4156 convOp = spv::OpSConvert;
4157 type = builder.makeIntType(32);
4158 break;
4159 case glslang::EOpConvUint64ToInt:
4160 convOp = spv::OpUConvert;
4161 type = builder.makeUintType(32);
4162 break;
4163 case glslang::EOpConvUintToInt64:
4164 convOp = spv::OpUConvert;
4165 type = builder.makeUintType(64);
4166 break;
4167 default:
4168 assert(0);
4169 break;
4170 }
4171
4172 if (vectorSize > 0)
4173 type = builder.makeVectorType(type, vectorSize);
4174
4175 operand = builder.createUnaryOp(convOp, type, operand);
4176
4177 if (builder.isInSpecConstCodeGenMode()) {
4178 // Build zero scalar or vector for OpIAdd.
4179 zero = (op == glslang::EOpConvIntToUint64 ||
4180 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4181 zero = makeSmearedConstant(zero, vectorSize);
4182 // Use OpIAdd, instead of OpBitcast to do the conversion when
4183 // generating for OpSpecConstantOp instruction.
4184 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4185 }
4186 // For normal run-time conversion instruction, use OpBitcast.
4187 convOp = spv::OpBitcast;
4188 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004189 default:
4190 break;
4191 }
4192
4193 spv::Id result = 0;
4194 if (convOp == spv::OpNop)
4195 return result;
4196
4197 if (convOp == spv::OpSelect) {
4198 zero = makeSmearedConstant(zero, vectorSize);
4199 one = makeSmearedConstant(one, vectorSize);
4200 result = builder.createTriOp(convOp, destType, operand, one, zero);
4201 } else
4202 result = builder.createUnaryOp(convOp, destType, operand);
4203
John Kessenich32cfd492016-02-02 12:37:46 -07004204 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004205}
4206
4207spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4208{
4209 if (vectorSize == 0)
4210 return constant;
4211
4212 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4213 std::vector<spv::Id> components;
4214 for (int c = 0; c < vectorSize; ++c)
4215 components.push_back(constant);
4216 return builder.makeCompositeConstant(vectorTypeId, components);
4217}
4218
John Kessenich426394d2015-07-23 10:22:48 -06004219// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004220spv::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 -06004221{
4222 spv::Op opCode = spv::OpNop;
4223
4224 switch (op) {
4225 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004226 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004227 opCode = spv::OpAtomicIAdd;
4228 break;
4229 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004230 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004231 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004232 break;
4233 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004234 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004235 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004236 break;
4237 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004238 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004239 opCode = spv::OpAtomicAnd;
4240 break;
4241 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004242 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004243 opCode = spv::OpAtomicOr;
4244 break;
4245 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004246 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004247 opCode = spv::OpAtomicXor;
4248 break;
4249 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004250 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004251 opCode = spv::OpAtomicExchange;
4252 break;
4253 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004254 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004255 opCode = spv::OpAtomicCompareExchange;
4256 break;
4257 case glslang::EOpAtomicCounterIncrement:
4258 opCode = spv::OpAtomicIIncrement;
4259 break;
4260 case glslang::EOpAtomicCounterDecrement:
4261 opCode = spv::OpAtomicIDecrement;
4262 break;
4263 case glslang::EOpAtomicCounter:
4264 opCode = spv::OpAtomicLoad;
4265 break;
4266 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004267 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004268 break;
4269 }
4270
4271 // Sort out the operands
4272 // - mapping from glslang -> SPV
4273 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004274 // - compare-exchange swaps the value and comparator
4275 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004276 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4277 auto opIt = operands.begin(); // walk the glslang operands
4278 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004279 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4280 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4281 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004282 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4283 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004284 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004285 spvAtomicOperands.push_back(*(opIt + 1));
4286 spvAtomicOperands.push_back(*opIt);
4287 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004288 }
John Kessenich426394d2015-07-23 10:22:48 -06004289
John Kessenich3e60a6f2015-09-14 22:45:16 -06004290 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004291 for (; opIt != operands.end(); ++opIt)
4292 spvAtomicOperands.push_back(*opIt);
4293
4294 return builder.createOp(opCode, typeId, spvAtomicOperands);
4295}
4296
John Kessenich91cef522016-05-05 16:45:40 -06004297// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004298spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004299{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004300#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004301 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004302 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004303#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004304
Rex Xu51596642016-09-21 18:56:12 +08004305 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004306 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004307 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4308
chaocf200da82016-12-20 12:44:35 -08004309 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4310 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004311 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4312 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004313 } else if (op == glslang::EOpAnyInvocation ||
4314 op == glslang::EOpAllInvocations ||
4315 op == glslang::EOpAllInvocationsEqual) {
4316 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4317 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004318 } else {
4319 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004320#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004321 if (op == glslang::EOpMinInvocationsNonUniform ||
4322 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004323 op == glslang::EOpAddInvocationsNonUniform ||
4324 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4325 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4326 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4327 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4328 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4329 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004330 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004331#endif
Rex Xu51596642016-09-21 18:56:12 +08004332
4333 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004334#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004335 switch (op) {
4336 case glslang::EOpMinInvocations:
4337 case glslang::EOpMaxInvocations:
4338 case glslang::EOpAddInvocations:
4339 case glslang::EOpMinInvocationsNonUniform:
4340 case glslang::EOpMaxInvocationsNonUniform:
4341 case glslang::EOpAddInvocationsNonUniform:
4342 groupOperation = spv::GroupOperationReduce;
4343 spvGroupOperands.push_back(groupOperation);
4344 break;
4345 case glslang::EOpMinInvocationsInclusiveScan:
4346 case glslang::EOpMaxInvocationsInclusiveScan:
4347 case glslang::EOpAddInvocationsInclusiveScan:
4348 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4349 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4350 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4351 groupOperation = spv::GroupOperationInclusiveScan;
4352 spvGroupOperands.push_back(groupOperation);
4353 break;
4354 case glslang::EOpMinInvocationsExclusiveScan:
4355 case glslang::EOpMaxInvocationsExclusiveScan:
4356 case glslang::EOpAddInvocationsExclusiveScan:
4357 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4358 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4359 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4360 groupOperation = spv::GroupOperationExclusiveScan;
4361 spvGroupOperands.push_back(groupOperation);
4362 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004363 default:
4364 break;
Rex Xu430ef402016-10-14 17:22:23 +08004365 }
Rex Xu9d93a232016-05-05 12:30:44 +08004366#endif
Rex Xu51596642016-09-21 18:56:12 +08004367 }
4368
4369 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4370 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004371
4372 switch (op) {
4373 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004374 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004375 break;
John Kessenich91cef522016-05-05 16:45:40 -06004376 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004377 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004378 break;
John Kessenich91cef522016-05-05 16:45:40 -06004379 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004380 opCode = spv::OpSubgroupAllEqualKHR;
4381 break;
Rex Xu51596642016-09-21 18:56:12 +08004382 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004383 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004384 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004385 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004386 break;
4387 case glslang::EOpReadFirstInvocation:
4388 opCode = spv::OpSubgroupFirstInvocationKHR;
4389 break;
4390 case glslang::EOpBallot:
4391 {
4392 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4393 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4394 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4395 //
4396 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4397 //
4398 spv::Id uintType = builder.makeUintType(32);
4399 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4400 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4401
4402 std::vector<spv::Id> components;
4403 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4404 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4405
4406 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4407 return builder.createUnaryOp(spv::OpBitcast, typeId,
4408 builder.createCompositeConstruct(uvec2Type, components));
4409 }
4410
Rex Xu9d93a232016-05-05 12:30:44 +08004411#ifdef AMD_EXTENSIONS
4412 case glslang::EOpMinInvocations:
4413 case glslang::EOpMaxInvocations:
4414 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004415 case glslang::EOpMinInvocationsInclusiveScan:
4416 case glslang::EOpMaxInvocationsInclusiveScan:
4417 case glslang::EOpAddInvocationsInclusiveScan:
4418 case glslang::EOpMinInvocationsExclusiveScan:
4419 case glslang::EOpMaxInvocationsExclusiveScan:
4420 case glslang::EOpAddInvocationsExclusiveScan:
4421 if (op == glslang::EOpMinInvocations ||
4422 op == glslang::EOpMinInvocationsInclusiveScan ||
4423 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004424 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004425 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004426 else {
4427 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004428 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004429 else
Rex Xu51596642016-09-21 18:56:12 +08004430 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004431 }
Rex Xu430ef402016-10-14 17:22:23 +08004432 } else if (op == glslang::EOpMaxInvocations ||
4433 op == glslang::EOpMaxInvocationsInclusiveScan ||
4434 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004435 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004436 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004437 else {
4438 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004439 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004440 else
Rex Xu51596642016-09-21 18:56:12 +08004441 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004442 }
4443 } else {
4444 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004445 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004446 else
Rex Xu51596642016-09-21 18:56:12 +08004447 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004448 }
4449
Rex Xu2bbbe062016-08-23 15:41:05 +08004450 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004451 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004452
4453 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004454 case glslang::EOpMinInvocationsNonUniform:
4455 case glslang::EOpMaxInvocationsNonUniform:
4456 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004457 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4458 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4459 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4460 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4461 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4462 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4463 if (op == glslang::EOpMinInvocationsNonUniform ||
4464 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4465 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004466 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004467 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004468 else {
4469 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004470 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004471 else
Rex Xu51596642016-09-21 18:56:12 +08004472 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004473 }
4474 }
Rex Xu430ef402016-10-14 17:22:23 +08004475 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4476 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4477 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004478 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004479 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004480 else {
4481 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004482 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004483 else
Rex Xu51596642016-09-21 18:56:12 +08004484 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004485 }
4486 }
4487 else {
4488 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004489 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004490 else
Rex Xu51596642016-09-21 18:56:12 +08004491 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004492 }
4493
Rex Xu2bbbe062016-08-23 15:41:05 +08004494 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004495 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004496
4497 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004498#endif
John Kessenich91cef522016-05-05 16:45:40 -06004499 default:
4500 logger->missingFunctionality("invocation operation");
4501 return spv::NoResult;
4502 }
Rex Xu51596642016-09-21 18:56:12 +08004503
4504 assert(opCode != spv::OpNop);
4505 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004506}
4507
Rex Xu2bbbe062016-08-23 15:41:05 +08004508// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004509spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004510{
Rex Xub7072052016-09-26 15:53:40 +08004511#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004512 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4513 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004514 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004515 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004516 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4517 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4518 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004519#else
4520 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4521 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004522 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4523 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004524#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004525
4526 // Handle group invocation operations scalar by scalar.
4527 // The result type is the same type as the original type.
4528 // The algorithm is to:
4529 // - break the vector into scalars
4530 // - apply the operation to each scalar
4531 // - make a vector out the scalar results
4532
4533 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004534 int numComponents = builder.getNumComponents(operands[0]);
4535 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004536 std::vector<spv::Id> results;
4537
4538 // do each scalar op
4539 for (int comp = 0; comp < numComponents; ++comp) {
4540 std::vector<unsigned int> indexes;
4541 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004542 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004543 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004544 if (op == spv::OpSubgroupReadInvocationKHR) {
4545 spvGroupOperands.push_back(scalar);
4546 spvGroupOperands.push_back(operands[1]);
4547 } else if (op == spv::OpGroupBroadcast) {
4548 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004549 spvGroupOperands.push_back(scalar);
4550 spvGroupOperands.push_back(operands[1]);
4551 } else {
chaocf200da82016-12-20 12:44:35 -08004552 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004553 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004554 spvGroupOperands.push_back(scalar);
4555 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004556
Rex Xub7072052016-09-26 15:53:40 +08004557 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004558 }
4559
4560 // put the pieces together
4561 return builder.createCompositeConstruct(typeId, results);
4562}
Rex Xu2bbbe062016-08-23 15:41:05 +08004563
John Kessenich5e4b1242015-08-06 22:53:06 -06004564spv::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 -06004565{
Rex Xu8ff43de2016-04-22 16:51:45 +08004566 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004567#ifdef AMD_EXTENSIONS
4568 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4569#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004570 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004571#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004572
John Kessenich140f3df2015-06-26 16:58:36 -06004573 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004574 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004575 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004576 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004577 spv::Id typeId0 = 0;
4578 if (consumedOperands > 0)
4579 typeId0 = builder.getTypeId(operands[0]);
4580 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004581
4582 switch (op) {
4583 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004584 if (isFloat)
4585 libCall = spv::GLSLstd450FMin;
4586 else if (isUnsigned)
4587 libCall = spv::GLSLstd450UMin;
4588 else
4589 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004590 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004591 break;
4592 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004593 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004594 break;
4595 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004596 if (isFloat)
4597 libCall = spv::GLSLstd450FMax;
4598 else if (isUnsigned)
4599 libCall = spv::GLSLstd450UMax;
4600 else
4601 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004602 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004603 break;
4604 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004605 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004606 break;
4607 case glslang::EOpDot:
4608 opCode = spv::OpDot;
4609 break;
4610 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004611 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004612 break;
4613
4614 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004615 if (isFloat)
4616 libCall = spv::GLSLstd450FClamp;
4617 else if (isUnsigned)
4618 libCall = spv::GLSLstd450UClamp;
4619 else
4620 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004621 builder.promoteScalar(precision, operands.front(), operands[1]);
4622 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004623 break;
4624 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004625 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4626 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004627 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004628 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004629 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004630 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004631 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004632 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004633 break;
4634 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004635 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004636 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004637 break;
4638 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004639 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004640 builder.promoteScalar(precision, operands[0], operands[2]);
4641 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004642 break;
4643
4644 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004645 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004646 break;
4647 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004648 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004649 break;
4650 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004651 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004652 break;
4653 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004654 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004655 break;
4656 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004657 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004658 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004659 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004660 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004661 libCall = spv::GLSLstd450InterpolateAtSample;
4662 break;
4663 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004664 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004665 libCall = spv::GLSLstd450InterpolateAtOffset;
4666 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004667 case glslang::EOpAddCarry:
4668 opCode = spv::OpIAddCarry;
4669 typeId = builder.makeStructResultType(typeId0, typeId0);
4670 consumedOperands = 2;
4671 break;
4672 case glslang::EOpSubBorrow:
4673 opCode = spv::OpISubBorrow;
4674 typeId = builder.makeStructResultType(typeId0, typeId0);
4675 consumedOperands = 2;
4676 break;
4677 case glslang::EOpUMulExtended:
4678 opCode = spv::OpUMulExtended;
4679 typeId = builder.makeStructResultType(typeId0, typeId0);
4680 consumedOperands = 2;
4681 break;
4682 case glslang::EOpIMulExtended:
4683 opCode = spv::OpSMulExtended;
4684 typeId = builder.makeStructResultType(typeId0, typeId0);
4685 consumedOperands = 2;
4686 break;
4687 case glslang::EOpBitfieldExtract:
4688 if (isUnsigned)
4689 opCode = spv::OpBitFieldUExtract;
4690 else
4691 opCode = spv::OpBitFieldSExtract;
4692 break;
4693 case glslang::EOpBitfieldInsert:
4694 opCode = spv::OpBitFieldInsert;
4695 break;
4696
4697 case glslang::EOpFma:
4698 libCall = spv::GLSLstd450Fma;
4699 break;
4700 case glslang::EOpFrexp:
4701 libCall = spv::GLSLstd450FrexpStruct;
4702 if (builder.getNumComponents(operands[0]) == 1)
4703 frexpIntType = builder.makeIntegerType(32, true);
4704 else
4705 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4706 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4707 consumedOperands = 1;
4708 break;
4709 case glslang::EOpLdexp:
4710 libCall = spv::GLSLstd450Ldexp;
4711 break;
4712
Rex Xu574ab042016-04-14 16:53:07 +08004713 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004714 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004715
Rex Xu9d93a232016-05-05 12:30:44 +08004716#ifdef AMD_EXTENSIONS
4717 case glslang::EOpSwizzleInvocations:
4718 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4719 libCall = spv::SwizzleInvocationsAMD;
4720 break;
4721 case glslang::EOpSwizzleInvocationsMasked:
4722 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4723 libCall = spv::SwizzleInvocationsMaskedAMD;
4724 break;
4725 case glslang::EOpWriteInvocation:
4726 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4727 libCall = spv::WriteInvocationAMD;
4728 break;
4729
4730 case glslang::EOpMin3:
4731 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4732 if (isFloat)
4733 libCall = spv::FMin3AMD;
4734 else {
4735 if (isUnsigned)
4736 libCall = spv::UMin3AMD;
4737 else
4738 libCall = spv::SMin3AMD;
4739 }
4740 break;
4741 case glslang::EOpMax3:
4742 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4743 if (isFloat)
4744 libCall = spv::FMax3AMD;
4745 else {
4746 if (isUnsigned)
4747 libCall = spv::UMax3AMD;
4748 else
4749 libCall = spv::SMax3AMD;
4750 }
4751 break;
4752 case glslang::EOpMid3:
4753 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4754 if (isFloat)
4755 libCall = spv::FMid3AMD;
4756 else {
4757 if (isUnsigned)
4758 libCall = spv::UMid3AMD;
4759 else
4760 libCall = spv::SMid3AMD;
4761 }
4762 break;
4763
4764 case glslang::EOpInterpolateAtVertex:
4765 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4766 libCall = spv::InterpolateAtVertexAMD;
4767 break;
4768#endif
4769
John Kessenich140f3df2015-06-26 16:58:36 -06004770 default:
4771 return 0;
4772 }
4773
4774 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004775 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004776 // Use an extended instruction from the standard library.
4777 // Construct the call arguments, without modifying the original operands vector.
4778 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4779 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004780 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004781 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004782 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004783 case 0:
4784 // should all be handled by visitAggregate and createNoArgOperation
4785 assert(0);
4786 return 0;
4787 case 1:
4788 // should all be handled by createUnaryOperation
4789 assert(0);
4790 return 0;
4791 case 2:
4792 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4793 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004794 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004795 // anything 3 or over doesn't have l-value operands, so all should be consumed
4796 assert(consumedOperands == operands.size());
4797 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004798 break;
4799 }
4800 }
4801
John Kessenich55e7d112015-11-15 21:33:39 -07004802 // Decode the return types that were structures
4803 switch (op) {
4804 case glslang::EOpAddCarry:
4805 case glslang::EOpSubBorrow:
4806 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4807 id = builder.createCompositeExtract(id, typeId0, 0);
4808 break;
4809 case glslang::EOpUMulExtended:
4810 case glslang::EOpIMulExtended:
4811 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4812 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4813 break;
4814 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004815 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004816 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4817 id = builder.createCompositeExtract(id, typeId0, 0);
4818 break;
4819 default:
4820 break;
4821 }
4822
John Kessenich32cfd492016-02-02 12:37:46 -07004823 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004824}
4825
Rex Xu9d93a232016-05-05 12:30:44 +08004826// Intrinsics with no arguments (or no return value, and no precision).
4827spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004828{
4829 // TODO: get the barrier operands correct
4830
4831 switch (op) {
4832 case glslang::EOpEmitVertex:
4833 builder.createNoResultOp(spv::OpEmitVertex);
4834 return 0;
4835 case glslang::EOpEndPrimitive:
4836 builder.createNoResultOp(spv::OpEndPrimitive);
4837 return 0;
4838 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004839 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004840 return 0;
4841 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004842 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004843 return 0;
4844 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004845 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004846 return 0;
4847 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004848 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004849 return 0;
4850 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004851 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004852 return 0;
4853 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004854 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004855 return 0;
4856 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004857 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004858 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004859 case glslang::EOpAllMemoryBarrierWithGroupSync:
4860 // Control barrier with non-"None" semantic is also a memory barrier.
4861 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4862 return 0;
4863 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4864 // Control barrier with non-"None" semantic is also a memory barrier.
4865 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4866 return 0;
4867 case glslang::EOpWorkgroupMemoryBarrier:
4868 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4869 return 0;
4870 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4871 // Control barrier with non-"None" semantic is also a memory barrier.
4872 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4873 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004874#ifdef AMD_EXTENSIONS
4875 case glslang::EOpTime:
4876 {
4877 std::vector<spv::Id> args; // Dummy arguments
4878 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4879 return builder.setPrecision(id, precision);
4880 }
4881#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004882 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004883 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004884 return 0;
4885 }
4886}
4887
4888spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4889{
John Kessenich2f273362015-07-18 22:34:27 -06004890 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004891 spv::Id id;
4892 if (symbolValues.end() != iter) {
4893 id = iter->second;
4894 return id;
4895 }
4896
4897 // it was not found, create it
4898 id = createSpvVariable(symbol);
4899 symbolValues[symbol->getId()] = id;
4900
Rex Xuc884b4a2016-06-29 15:03:44 +08004901 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004902 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004903 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004904 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004905 if (symbol->getType().getQualifier().hasSpecConstantId())
4906 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004907 if (symbol->getQualifier().hasIndex())
4908 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4909 if (symbol->getQualifier().hasComponent())
4910 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4911 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004912 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004913 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004914 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004915 if (symbol->getQualifier().hasXfbBuffer())
4916 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4917 if (symbol->getQualifier().hasXfbOffset())
4918 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4919 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004920 // atomic counters use this:
4921 if (symbol->getQualifier().hasOffset())
4922 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004923 }
4924
scygan2c864272016-05-18 18:09:17 +02004925 if (symbol->getQualifier().hasLocation())
4926 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004927 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004928 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004929 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004930 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004931 }
John Kessenich140f3df2015-06-26 16:58:36 -06004932 if (symbol->getQualifier().hasSet())
4933 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004934 else if (IsDescriptorResource(symbol->getType())) {
4935 // default to 0
4936 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4937 }
John Kessenich140f3df2015-06-26 16:58:36 -06004938 if (symbol->getQualifier().hasBinding())
4939 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004940 if (symbol->getQualifier().hasAttachment())
4941 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004942 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004943 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004944 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004945 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004946 if (symbol->getQualifier().hasXfbBuffer())
4947 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4948 }
4949
Rex Xu1da878f2016-02-21 20:59:01 +08004950 if (symbol->getType().isImage()) {
4951 std::vector<spv::Decoration> memory;
4952 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4953 for (unsigned int i = 0; i < memory.size(); ++i)
4954 addDecoration(id, memory[i]);
4955 }
4956
John Kessenich140f3df2015-06-26 16:58:36 -06004957 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004958 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004959 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004960 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004961
John Kessenichecba76f2017-01-06 00:34:48 -07004962#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004963 if (builtIn == spv::BuiltInSampleMask) {
4964 spv::Decoration decoration;
4965 // GL_NV_sample_mask_override_coverage extension
4966 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004967 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004968 else
4969 decoration = (spv::Decoration)spv::DecorationMax;
4970 addDecoration(id, decoration);
4971 if (decoration != spv::DecorationMax) {
4972 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4973 }
4974 }
chaoc771d89f2017-01-13 01:10:53 -08004975 else if (builtIn == spv::BuiltInLayer) {
4976 // SPV_NV_viewport_array2 extension
4977 if (symbol->getQualifier().layoutViewportRelative)
4978 {
4979 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4980 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4981 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4982 }
4983 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4984 {
4985 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4986 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4987 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4988 }
4989 }
4990
chaoc6e5acae2016-12-20 13:28:52 -08004991 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004992 addDecoration(id, spv::DecorationPassthroughNV);
4993 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004994 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4995 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004996#endif
4997
John Kessenich140f3df2015-06-26 16:58:36 -06004998 return id;
4999}
5000
John Kessenich55e7d112015-11-15 21:33:39 -07005001// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005002void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5003{
John Kessenich4016e382016-07-15 11:53:56 -06005004 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005005 builder.addDecoration(id, dec);
5006}
5007
John Kessenich55e7d112015-11-15 21:33:39 -07005008// If 'dec' is valid, add a one-operand decoration to an object
5009void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5010{
John Kessenich4016e382016-07-15 11:53:56 -06005011 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005012 builder.addDecoration(id, dec, value);
5013}
5014
5015// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005016void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5017{
John Kessenich4016e382016-07-15 11:53:56 -06005018 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005019 builder.addMemberDecoration(id, (unsigned)member, dec);
5020}
5021
John Kessenich92187592016-02-01 13:45:25 -07005022// If 'dec' is valid, add a one-operand decoration to a struct member
5023void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5024{
John Kessenich4016e382016-07-15 11:53:56 -06005025 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005026 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5027}
5028
John Kessenich55e7d112015-11-15 21:33:39 -07005029// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005030// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005031//
5032// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5033//
5034// Recursively walk the nodes. The nodes form a tree whose leaves are
5035// regular constants, which themselves are trees that createSpvConstant()
5036// recursively walks. So, this function walks the "top" of the tree:
5037// - emit specialization constant-building instructions for specConstant
5038// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005039spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005040{
John Kessenich7cc0e282016-03-20 00:46:02 -06005041 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005042
qining4f4bb812016-04-03 23:55:17 -04005043 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005044 if (! node.getQualifier().specConstant) {
5045 // hand off to the non-spec-constant path
5046 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5047 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005048 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005049 nextConst, false);
5050 }
5051
5052 // We now know we have a specialization constant to build
5053
John Kessenichd94c0032016-05-30 19:29:40 -06005054 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005055 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5056 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5057 std::vector<spv::Id> dimConstId;
5058 for (int dim = 0; dim < 3; ++dim) {
5059 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5060 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5061 if (specConst)
5062 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5063 }
5064 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5065 }
5066
5067 // An AST node labelled as specialization constant should be a symbol node.
5068 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5069 if (auto* sn = node.getAsSymbolNode()) {
5070 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005071 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5072 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5073 // will set the builder into spec constant op instruction generating mode.
5074 sub_tree->traverse(this);
5075 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005076 } else if (auto* const_union_array = &sn->getConstArray()){
5077 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005078 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5079 builder.addName(id, sn->getName().c_str());
5080 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005081 }
5082 }
qining4f4bb812016-04-03 23:55:17 -04005083
5084 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5085 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005086 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005087 exit(1);
5088 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005089}
5090
John Kessenich140f3df2015-06-26 16:58:36 -06005091// Use 'consts' as the flattened glslang source of scalar constants to recursively
5092// build the aggregate SPIR-V constant.
5093//
5094// If there are not enough elements present in 'consts', 0 will be substituted;
5095// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5096//
qining08408382016-03-21 09:51:37 -04005097spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005098{
5099 // vector of constants for SPIR-V
5100 std::vector<spv::Id> spvConsts;
5101
5102 // Type is used for struct and array constants
5103 spv::Id typeId = convertGlslangToSpvType(glslangType);
5104
5105 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005106 glslang::TType elementType(glslangType, 0);
5107 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005108 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005109 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005110 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005111 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005112 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005113 } else if (glslangType.getStruct()) {
5114 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5115 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005116 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005117 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005118 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5119 bool zero = nextConst >= consts.size();
5120 switch (glslangType.getBasicType()) {
5121 case glslang::EbtInt:
5122 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5123 break;
5124 case glslang::EbtUint:
5125 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5126 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005127 case glslang::EbtInt64:
5128 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5129 break;
5130 case glslang::EbtUint64:
5131 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5132 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005133 case glslang::EbtFloat:
5134 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5135 break;
5136 case glslang::EbtDouble:
5137 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5138 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005139#ifdef AMD_EXTENSIONS
5140 case glslang::EbtFloat16:
5141 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5142 break;
5143#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005144 case glslang::EbtBool:
5145 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5146 break;
5147 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005148 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005149 break;
5150 }
5151 ++nextConst;
5152 }
5153 } else {
5154 // we have a non-aggregate (scalar) constant
5155 bool zero = nextConst >= consts.size();
5156 spv::Id scalar = 0;
5157 switch (glslangType.getBasicType()) {
5158 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005159 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005160 break;
5161 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005162 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005163 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005164 case glslang::EbtInt64:
5165 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5166 break;
5167 case glslang::EbtUint64:
5168 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5169 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005170 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005171 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005172 break;
5173 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005174 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005175 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005176#ifdef AMD_EXTENSIONS
5177 case glslang::EbtFloat16:
5178 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5179 break;
5180#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005181 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005182 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005183 break;
5184 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005185 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005186 break;
5187 }
5188 ++nextConst;
5189 return scalar;
5190 }
5191
5192 return builder.makeCompositeConstant(typeId, spvConsts);
5193}
5194
John Kessenich7c1aa102015-10-15 13:29:11 -06005195// Return true if the node is a constant or symbol whose reading has no
5196// non-trivial observable cost or effect.
5197bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5198{
5199 // don't know what this is
5200 if (node == nullptr)
5201 return false;
5202
5203 // a constant is safe
5204 if (node->getAsConstantUnion() != nullptr)
5205 return true;
5206
5207 // not a symbol means non-trivial
5208 if (node->getAsSymbolNode() == nullptr)
5209 return false;
5210
5211 // a symbol, depends on what's being read
5212 switch (node->getType().getQualifier().storage) {
5213 case glslang::EvqTemporary:
5214 case glslang::EvqGlobal:
5215 case glslang::EvqIn:
5216 case glslang::EvqInOut:
5217 case glslang::EvqConst:
5218 case glslang::EvqConstReadOnly:
5219 case glslang::EvqUniform:
5220 return true;
5221 default:
5222 return false;
5223 }
qining25262b32016-05-06 17:25:16 -04005224}
John Kessenich7c1aa102015-10-15 13:29:11 -06005225
5226// A node is trivial if it is a single operation with no side effects.
5227// Error on the side of saying non-trivial.
5228// Return true if trivial.
5229bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5230{
5231 if (node == nullptr)
5232 return false;
5233
5234 // symbols and constants are trivial
5235 if (isTrivialLeaf(node))
5236 return true;
5237
5238 // otherwise, it needs to be a simple operation or one or two leaf nodes
5239
5240 // not a simple operation
5241 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5242 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5243 if (binaryNode == nullptr && unaryNode == nullptr)
5244 return false;
5245
5246 // not on leaf nodes
5247 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5248 return false;
5249
5250 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5251 return false;
5252 }
5253
5254 switch (node->getAsOperator()->getOp()) {
5255 case glslang::EOpLogicalNot:
5256 case glslang::EOpConvIntToBool:
5257 case glslang::EOpConvUintToBool:
5258 case glslang::EOpConvFloatToBool:
5259 case glslang::EOpConvDoubleToBool:
5260 case glslang::EOpEqual:
5261 case glslang::EOpNotEqual:
5262 case glslang::EOpLessThan:
5263 case glslang::EOpGreaterThan:
5264 case glslang::EOpLessThanEqual:
5265 case glslang::EOpGreaterThanEqual:
5266 case glslang::EOpIndexDirect:
5267 case glslang::EOpIndexDirectStruct:
5268 case glslang::EOpLogicalXor:
5269 case glslang::EOpAny:
5270 case glslang::EOpAll:
5271 return true;
5272 default:
5273 return false;
5274 }
5275}
5276
5277// Emit short-circuiting code, where 'right' is never evaluated unless
5278// the left side is true (for &&) or false (for ||).
5279spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5280{
5281 spv::Id boolTypeId = builder.makeBoolType();
5282
5283 // emit left operand
5284 builder.clearAccessChain();
5285 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005286 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005287
5288 // Operands to accumulate OpPhi operands
5289 std::vector<spv::Id> phiOperands;
5290 // accumulate left operand's phi information
5291 phiOperands.push_back(leftId);
5292 phiOperands.push_back(builder.getBuildPoint()->getId());
5293
5294 // Make the two kinds of operation symmetric with a "!"
5295 // || => emit "if (! left) result = right"
5296 // && => emit "if ( left) result = right"
5297 //
5298 // TODO: this runtime "not" for || could be avoided by adding functionality
5299 // to 'builder' to have an "else" without an "then"
5300 if (op == glslang::EOpLogicalOr)
5301 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5302
5303 // make an "if" based on the left value
5304 spv::Builder::If ifBuilder(leftId, builder);
5305
5306 // emit right operand as the "then" part of the "if"
5307 builder.clearAccessChain();
5308 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005309 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005310
5311 // accumulate left operand's phi information
5312 phiOperands.push_back(rightId);
5313 phiOperands.push_back(builder.getBuildPoint()->getId());
5314
5315 // finish the "if"
5316 ifBuilder.makeEndIf();
5317
5318 // phi together the two results
5319 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5320}
5321
Rex Xu9d93a232016-05-05 12:30:44 +08005322// Return type Id of the imported set of extended instructions corresponds to the name.
5323// Import this set if it has not been imported yet.
5324spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5325{
5326 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5327 return extBuiltinMap[name];
5328 else {
Rex Xu51596642016-09-21 18:56:12 +08005329 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005330 spv::Id extBuiltins = builder.import(name);
5331 extBuiltinMap[name] = extBuiltins;
5332 return extBuiltins;
5333 }
5334}
5335
John Kessenich140f3df2015-06-26 16:58:36 -06005336}; // end anonymous namespace
5337
5338namespace glslang {
5339
John Kessenich68d78fd2015-07-12 19:28:10 -06005340void GetSpirvVersion(std::string& version)
5341{
John Kessenich9e55f632015-07-15 10:03:39 -06005342 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005343 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005344 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005345 version = buf;
5346}
5347
John Kessenich140f3df2015-06-26 16:58:36 -06005348// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005349void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005350{
5351 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005352 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005353 if (out.fail())
5354 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005355 for (int i = 0; i < (int)spirv.size(); ++i) {
5356 unsigned int word = spirv[i];
5357 out.write((const char*)&word, 4);
5358 }
5359 out.close();
5360}
5361
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005362// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005363void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005364{
5365 std::ofstream out;
5366 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005367 if (out.fail())
5368 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005369 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005370 if (varName != nullptr) {
5371 out << "\t #pragma once" << std::endl;
5372 out << "const uint32_t " << varName << "[] = {" << std::endl;
5373 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005374 const int WORDS_PER_LINE = 8;
5375 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5376 out << "\t";
5377 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5378 const unsigned int word = spirv[i + j];
5379 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5380 if (i + j + 1 < (int)spirv.size()) {
5381 out << ",";
5382 }
5383 }
5384 out << std::endl;
5385 }
Flavio15017db2017-02-15 14:29:33 -08005386 if (varName != nullptr) {
5387 out << "};";
5388 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005389 out.close();
5390}
5391
John Kessenich140f3df2015-06-26 16:58:36 -06005392//
5393// Set up the glslang traversal
5394//
5395void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5396{
Lei Zhang17535f72016-05-04 15:55:59 -04005397 spv::SpvBuildLogger logger;
5398 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005399}
5400
Lei Zhang17535f72016-05-04 15:55:59 -04005401void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005402{
John Kessenich140f3df2015-06-26 16:58:36 -06005403 TIntermNode* root = intermediate.getTreeRoot();
5404
5405 if (root == 0)
5406 return;
5407
5408 glslang::GetThreadPoolAllocator().push();
5409
Lei Zhang17535f72016-05-04 15:55:59 -04005410 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005411 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005412 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005413 it.dumpSpv(spirv);
5414
5415 glslang::GetThreadPoolAllocator().pop();
5416}
5417
5418}; // end namespace glslang