blob: 13bc305bb491c6d19af606a0b1baa0986fd79629 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6090df02016-06-30 21:18:02 -0600132 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
133 glslang::TLayoutPacking, const glslang::TQualifier&);
134 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
135 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700136 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700137 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800138 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600139 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700140 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700141 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
142 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100144 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600145
John Kessenich6fccb3c2016-09-19 16:01:41 -0600146 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600147 void makeFunctions(const glslang::TIntermSequence&);
148 void makeGlobalInitializers(const glslang::TIntermSequence&);
149 void visitFunctions(const glslang::TIntermSequence&);
150 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800151 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600152 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
153 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600154 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
155
qining25262b32016-05-06 17:25:16 -0400156 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
157 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
158 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800159 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800160 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800162 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800163 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800164 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600165 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800166 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600167 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
168 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700169 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400172 spv::Id createSpvConstant(const glslang::TIntermTyped&);
173 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600174 bool isTrivialLeaf(const glslang::TIntermTyped* node);
175 bool isTrivial(const glslang::TIntermTyped* node);
176 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800177 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600178
179 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600180 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700181 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600182 int sequenceDepth;
183
Lei Zhang17535f72016-05-04 15:55:59 -0400184 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400185
John Kessenich140f3df2015-06-26 16:58:36 -0600186 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
187 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700188 bool inEntryPoint;
189 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700190 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700191 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600192 const glslang::TIntermediate* glslangIntermediate;
193 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800194 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600195
John Kessenich2f273362015-07-18 22:34:27 -0600196 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600197 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600198 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700199 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600200 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600201 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600202};
203
204//
205// Helper functions for translating glslang representations to SPIR-V enumerants.
206//
207
208// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700209spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600210{
John Kessenich66e2faf2016-03-12 18:34:36 -0700211 switch (source) {
212 case glslang::EShSourceGlsl:
213 switch (profile) {
214 case ENoProfile:
215 case ECoreProfile:
216 case ECompatibilityProfile:
217 return spv::SourceLanguageGLSL;
218 case EEsProfile:
219 return spv::SourceLanguageESSL;
220 default:
221 return spv::SourceLanguageUnknown;
222 }
223 case glslang::EShSourceHlsl:
John Kessenich927608b2017-01-06 12:34:14 -0700224 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400225 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
248spv::StorageClass TranslateStorageClass(const glslang::TType& type)
249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtAtomicUint)
255 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700256 else if (type.containsOpaque())
257 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700259 if (type.getQualifier().layoutPushConstant)
260 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 if (type.getBasicType() == glslang::EbtBlock)
262 return spv::StorageClassUniform;
263 else
264 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 } else {
266 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
268 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
270 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400271 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600273 return spv::StorageClassFunction;
274 }
275 }
276}
277
278// Translate glslang sampler type to SPIR-V dimensionality.
279spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
280{
281 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700282 case glslang::Esd1D: return spv::Dim1D;
283 case glslang::Esd2D: return spv::Dim2D;
284 case glslang::Esd3D: return spv::Dim3D;
285 case glslang::EsdCube: return spv::DimCube;
286 case glslang::EsdRect: return spv::DimRect;
287 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700288 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::Dim2D;
292 }
293}
294
John Kessenichf6640762016-08-01 19:44:00 -0600295// Translate glslang precision to SPIR-V precision decorations.
296spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
John Kessenichf6640762016-08-01 19:44:00 -0600298 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700299 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600300 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600301 default:
302 return spv::NoPrecision;
303 }
304}
305
John Kessenichf6640762016-08-01 19:44:00 -0600306// Translate glslang type to SPIR-V precision decorations.
307spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
308{
309 return TranslatePrecisionDecoration(type.getQualifier().precision);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V block decorations.
313spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
314{
315 if (type.getBasicType() == glslang::EbtBlock) {
316 switch (type.getQualifier().storage) {
317 case glslang::EvqUniform: return spv::DecorationBlock;
318 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
319 case glslang::EvqVaryingIn: return spv::DecorationBlock;
320 case glslang::EvqVaryingOut: return spv::DecorationBlock;
321 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700322 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600323 break;
324 }
325 }
326
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328}
329
Rex Xu1da878f2016-02-21 20:59:01 +0800330// Translate glslang type to SPIR-V memory decorations.
331void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
332{
333 if (qualifier.coherent)
334 memory.push_back(spv::DecorationCoherent);
335 if (qualifier.volatil)
336 memory.push_back(spv::DecorationVolatile);
337 if (qualifier.restrict)
338 memory.push_back(spv::DecorationRestrict);
339 if (qualifier.readonly)
340 memory.push_back(spv::DecorationNonWritable);
341 if (qualifier.writeonly)
342 memory.push_back(spv::DecorationNonReadable);
343}
344
John Kessenich140f3df2015-06-26 16:58:36 -0600345// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700346spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600347{
348 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElmRowMajor:
351 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 default:
355 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 } else {
359 switch (type.getBasicType()) {
360 default:
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 break;
363 case glslang::EbtBlock:
364 switch (type.getQualifier().storage) {
365 case glslang::EvqUniform:
366 case glslang::EvqBuffer:
367 switch (type.getQualifier().layoutPacking) {
368 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 }
373 case glslang::EvqVaryingIn:
374 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700378 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 }
381 }
382 }
383}
384
385// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600386// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700387// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800388spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600389{
Rex Xubbceed72016-05-21 09:40:44 +0800390 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800393 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700394 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800397#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800398 else if (qualifier.explicitInterp) {
399 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800400 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800401 }
Rex Xu9d93a232016-05-05 12:30:44 +0800402#endif
Rex Xubbceed72016-05-21 09:40:44 +0800403 else
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800405}
406
407// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600408// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800409// should be applied.
410spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
411{
412 if (qualifier.patch)
413 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700414 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700416 else if (qualifier.sample) {
417 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700419 } else
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421}
422
John Kessenich92187592016-02-01 13:45:25 -0700423// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600425{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700426 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationInvariant;
428 else
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430}
431
qining9220dbb2016-05-04 17:34:38 -0400432// If glslang type is noContraction, return SPIR-V NoContraction decoration.
433spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
434{
435 if (qualifier.noContraction)
436 return spv::DecorationNoContraction;
437 else
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400439}
440
David Netoa901ffe2016-06-08 14:11:40 +0100441// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
442// associated capabilities when required. For some built-in variables, a capability
443// is generated only when using the variable in an executable instruction, but not when
444// just declaring a struct member variable with it. This is true for PointSize,
445// ClipDistance, and CullDistance.
446spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600447{
448 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700449 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600450 // Defer adding the capability until the built-in is actually used.
451 if (! memberDeclaration) {
452 switch (glslangIntermediate->getStage()) {
453 case EShLangGeometry:
454 builder.addCapability(spv::CapabilityGeometryPointSize);
455 break;
456 case EShLangTessControl:
457 case EShLangTessEvaluation:
458 builder.addCapability(spv::CapabilityTessellationPointSize);
459 break;
460 default:
461 break;
462 }
John Kessenich92187592016-02-01 13:45:25 -0700463 }
464 return spv::BuiltInPointSize;
465
John Kessenichebb50532016-05-16 19:22:05 -0600466 // These *Distance capabilities logically belong here, but if the member is declared and
467 // then never used, consumers of SPIR-V prefer the capability not be declared.
468 // They are now generated when used, rather than here when declared.
469 // Potentially, the specification should be more clear what the minimum
470 // use needed is to trigger the capability.
471 //
John Kessenich92187592016-02-01 13:45:25 -0700472 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800474 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInClipDistance;
476
477 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100478 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800479 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700480 return spv::BuiltInCullDistance;
481
482 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500483 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800484#ifdef NV_EXTENSIONS
485 if (glslangIntermediate->getStage() == EShLangVertex ||
486 glslangIntermediate->getStage() == EShLangTessControl ||
487 glslangIntermediate->getStage() == EShLangTessEvaluation)
488 {
489 builder.addExtension(spv::E_SPV_NV_viewport_array2);
490 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
491 }
492#endif
John Kessenich92187592016-02-01 13:45:25 -0700493 return spv::BuiltInViewportIndex;
494
John Kessenich5e801132016-02-15 11:09:46 -0700495 case glslang::EbvSampleId:
496 builder.addCapability(spv::CapabilitySampleRateShading);
497 return spv::BuiltInSampleId;
498
499 case glslang::EbvSamplePosition:
500 builder.addCapability(spv::CapabilitySampleRateShading);
501 return spv::BuiltInSamplePosition;
502
503 case glslang::EbvSampleMask:
504 builder.addCapability(spv::CapabilitySampleRateShading);
505 return spv::BuiltInSampleMask;
506
John Kessenich78a45572016-07-08 14:05:15 -0600507 case glslang::EbvLayer:
508 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800509#ifdef NV_EXTENSIONS
510 if (!memberDeclaration)
511 {
512 if (glslangIntermediate->getStage() == EShLangVertex ||
513 glslangIntermediate->getStage() == EShLangTessControl ||
514 glslangIntermediate->getStage() == EShLangTessEvaluation)
515 {
516 builder.addExtension(spv::E_SPV_NV_viewport_array2);
517 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
518 }
519 }
520#endif
John Kessenich78a45572016-07-08 14:05:15 -0600521 return spv::BuiltInLayer;
522
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvVertexId: return spv::BuiltInVertexId;
525 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700526 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
527 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800528
John Kessenichda581a22015-10-14 14:10:30 -0600529 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800530 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
531 builder.addCapability(spv::CapabilityDrawParameters);
532 return spv::BuiltInBaseVertex;
533
John Kessenichda581a22015-10-14 14:10:30 -0600534 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800535 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
536 builder.addCapability(spv::CapabilityDrawParameters);
537 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200538
John Kessenichda581a22015-10-14 14:10:30 -0600539 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
541 builder.addCapability(spv::CapabilityDrawParameters);
542 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200543
544 case glslang::EbvPrimitiveId:
545 if (glslangIntermediate->getStage() == EShLangFragment)
546 builder.addCapability(spv::CapabilityGeometry);
547 return spv::BuiltInPrimitiveId;
548
John Kessenich140f3df2015-06-26 16:58:36 -0600549 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600550 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
551 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
552 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
553 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
554 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
555 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
556 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600557 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
558 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
559 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
560 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
561 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
562 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
563 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
564 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800565
Rex Xu574ab042016-04-14 16:53:07 +0800566 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800567 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
569 return spv::BuiltInSubgroupSize;
570
Rex Xu574ab042016-04-14 16:53:07 +0800571 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800572 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
574 return spv::BuiltInSubgroupLocalInvocationId;
575
Rex Xu574ab042016-04-14 16:53:07 +0800576 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
578 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
579 return spv::BuiltInSubgroupEqMaskKHR;
580
Rex Xu574ab042016-04-14 16:53:07 +0800581 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800582 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
583 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
584 return spv::BuiltInSubgroupGeMaskKHR;
585
Rex Xu574ab042016-04-14 16:53:07 +0800586 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800587 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
588 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
589 return spv::BuiltInSubgroupGtMaskKHR;
590
Rex Xu574ab042016-04-14 16:53:07 +0800591 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800592 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
593 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
594 return spv::BuiltInSubgroupLeMaskKHR;
595
Rex Xu574ab042016-04-14 16:53:07 +0800596 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800597 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
598 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
599 return spv::BuiltInSubgroupLtMaskKHR;
600
Rex Xu9d93a232016-05-05 12:30:44 +0800601#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800602 case glslang::EbvBaryCoordNoPersp:
603 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
604 return spv::BuiltInBaryCoordNoPerspAMD;
605
606 case glslang::EbvBaryCoordNoPerspCentroid:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
609
610 case glslang::EbvBaryCoordNoPerspSample:
611 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
612 return spv::BuiltInBaryCoordNoPerspSampleAMD;
613
614 case glslang::EbvBaryCoordSmooth:
615 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
616 return spv::BuiltInBaryCoordSmoothAMD;
617
618 case glslang::EbvBaryCoordSmoothCentroid:
619 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
620 return spv::BuiltInBaryCoordSmoothCentroidAMD;
621
622 case glslang::EbvBaryCoordSmoothSample:
623 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
624 return spv::BuiltInBaryCoordSmoothSampleAMD;
625
626 case glslang::EbvBaryCoordPullModel:
627 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
628 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800629#endif
chaoc771d89f2017-01-13 01:10:53 -0800630
631#ifdef NV_EXTENSIONS
632 case glslang::EbvViewportMaskNV:
633 builder.addExtension(spv::E_SPV_NV_viewport_array2);
634 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
635 return spv::BuiltInViewportMaskNV;
636 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800637 if (!memberDeclaration) {
638 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
639 builder.addCapability(spv::CapabilityShaderStereoViewNV);
640 }
chaoc771d89f2017-01-13 01:10:53 -0800641 return spv::BuiltInSecondaryPositionNV;
642 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800643 if (!memberDeclaration) {
644 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
645 builder.addCapability(spv::CapabilityShaderStereoViewNV);
646 }
chaoc771d89f2017-01-13 01:10:53 -0800647 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800648 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800649 if (!memberDeclaration) {
650 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
651 builder.addCapability(spv::CapabilityPerViewAttributesNV);
652 }
chaocdf3956c2017-02-14 14:52:34 -0800653 return spv::BuiltInPositionPerViewNV;
654 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800655 if (!memberDeclaration) {
656 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
657 builder.addCapability(spv::CapabilityPerViewAttributesNV);
658 }
chaocdf3956c2017-02-14 14:52:34 -0800659 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800660#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800661 default:
662 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600663 }
664}
665
Rex Xufc618912015-09-09 16:42:49 +0800666// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700667spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800668{
669 assert(type.getBasicType() == glslang::EbtSampler);
670
John Kessenich5d0fa972016-02-15 11:57:00 -0700671 // Check for capabilities
672 switch (type.getQualifier().layoutFormat) {
673 case glslang::ElfRg32f:
674 case glslang::ElfRg16f:
675 case glslang::ElfR11fG11fB10f:
676 case glslang::ElfR16f:
677 case glslang::ElfRgba16:
678 case glslang::ElfRgb10A2:
679 case glslang::ElfRg16:
680 case glslang::ElfRg8:
681 case glslang::ElfR16:
682 case glslang::ElfR8:
683 case glslang::ElfRgba16Snorm:
684 case glslang::ElfRg16Snorm:
685 case glslang::ElfRg8Snorm:
686 case glslang::ElfR16Snorm:
687 case glslang::ElfR8Snorm:
688
689 case glslang::ElfRg32i:
690 case glslang::ElfRg16i:
691 case glslang::ElfRg8i:
692 case glslang::ElfR16i:
693 case glslang::ElfR8i:
694
695 case glslang::ElfRgb10a2ui:
696 case glslang::ElfRg32ui:
697 case glslang::ElfRg16ui:
698 case glslang::ElfRg8ui:
699 case glslang::ElfR16ui:
700 case glslang::ElfR8ui:
701 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
702 break;
703
704 default:
705 break;
706 }
707
708 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800709 switch (type.getQualifier().layoutFormat) {
710 case glslang::ElfNone: return spv::ImageFormatUnknown;
711 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
712 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
713 case glslang::ElfR32f: return spv::ImageFormatR32f;
714 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
715 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
716 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
717 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
718 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
719 case glslang::ElfR16f: return spv::ImageFormatR16f;
720 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
721 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
722 case glslang::ElfRg16: return spv::ImageFormatRg16;
723 case glslang::ElfRg8: return spv::ImageFormatRg8;
724 case glslang::ElfR16: return spv::ImageFormatR16;
725 case glslang::ElfR8: return spv::ImageFormatR8;
726 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
727 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
728 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
729 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
730 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
731 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
732 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
733 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
734 case glslang::ElfR32i: return spv::ImageFormatR32i;
735 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
736 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
737 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
738 case glslang::ElfR16i: return spv::ImageFormatR16i;
739 case glslang::ElfR8i: return spv::ImageFormatR8i;
740 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
741 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
742 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
743 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
744 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
745 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
746 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
747 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
748 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
749 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600750 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800751 }
752}
753
qining25262b32016-05-06 17:25:16 -0400754// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700755// descriptor set.
756bool IsDescriptorResource(const glslang::TType& type)
757{
John Kessenichf7497e22016-03-08 21:36:22 -0700758 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700759 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700760 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700761
762 // non block...
763 // basically samplerXXX/subpass/sampler/texture are all included
764 // if they are the global-scope-class, not the function parameter
765 // (or local, if they ever exist) class.
766 if (type.getBasicType() == glslang::EbtSampler)
767 return type.getQualifier().isUniformOrBuffer();
768
769 // None of the above.
770 return false;
771}
772
John Kesseniche0b6cad2015-12-24 10:30:13 -0700773void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
774{
775 if (child.layoutMatrix == glslang::ElmNone)
776 child.layoutMatrix = parent.layoutMatrix;
777
778 if (parent.invariant)
779 child.invariant = true;
780 if (parent.nopersp)
781 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800782#ifdef AMD_EXTENSIONS
783 if (parent.explicitInterp)
784 child.explicitInterp = true;
785#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700786 if (parent.flat)
787 child.flat = true;
788 if (parent.centroid)
789 child.centroid = true;
790 if (parent.patch)
791 child.patch = true;
792 if (parent.sample)
793 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800794 if (parent.coherent)
795 child.coherent = true;
796 if (parent.volatil)
797 child.volatil = true;
798 if (parent.restrict)
799 child.restrict = true;
800 if (parent.readonly)
801 child.readonly = true;
802 if (parent.writeonly)
803 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700804}
805
John Kessenichf2b7f332016-09-01 17:05:23 -0600806bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700807{
John Kessenich7b9fa252016-01-21 18:56:57 -0700808 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600809 // - struct members might inherit from a struct declaration
810 // (note that non-block structs don't explicitly inherit,
811 // only implicitly, meaning no decoration involved)
812 // - affect decorations on the struct members
813 // (note smooth does not, and expecting something like volatile
814 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700815 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600816 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817}
818
John Kessenich140f3df2015-06-26 16:58:36 -0600819//
820// Implement the TGlslangToSpvTraverser class.
821//
822
Lei Zhang17535f72016-05-04 15:55:59 -0400823TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600824 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
825 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400826 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700827 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600828 glslangIntermediate(glslangIntermediate)
829{
830 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
831
832 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700833 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600834 stdBuiltins = builder.import("GLSL.std.450");
835 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600836 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
837 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600838
839 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600840 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
841 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600842 builder.addSourceExtension(it->c_str());
843
844 // Add the top-level modes for this shader.
845
John Kessenich92187592016-02-01 13:45:25 -0700846 if (glslangIntermediate->getXfbMode()) {
847 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600848 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700849 }
John Kessenich140f3df2015-06-26 16:58:36 -0600850
851 unsigned int mode;
852 switch (glslangIntermediate->getStage()) {
853 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600854 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600855 break;
856
857 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600858 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600859 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
860 break;
861
862 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600863 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600864 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700865 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
866 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
867 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600868 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600869 }
John Kessenich4016e382016-07-15 11:53:56 -0600870 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600871 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
872
John Kesseniche6903322015-10-13 16:29:02 -0600873 switch (glslangIntermediate->getVertexSpacing()) {
874 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
875 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
876 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600877 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600878 }
John Kessenich4016e382016-07-15 11:53:56 -0600879 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600880 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
881
882 switch (glslangIntermediate->getVertexOrder()) {
883 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
884 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600885 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600886 }
John Kessenich4016e382016-07-15 11:53:56 -0600887 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600888 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
889
890 if (glslangIntermediate->getPointMode())
891 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600892 break;
893
894 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600895 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600896 switch (glslangIntermediate->getInputPrimitive()) {
897 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
898 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
899 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700900 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600901 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600902 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600903 }
John Kessenich4016e382016-07-15 11:53:56 -0600904 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600905 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600906
John Kessenich140f3df2015-06-26 16:58:36 -0600907 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
908
909 switch (glslangIntermediate->getOutputPrimitive()) {
910 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
911 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
912 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600913 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600914 }
John Kessenich4016e382016-07-15 11:53:56 -0600915 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600916 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
917 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
918 break;
919
920 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600921 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600922 if (glslangIntermediate->getPixelCenterInteger())
923 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600924
John Kessenich140f3df2015-06-26 16:58:36 -0600925 if (glslangIntermediate->getOriginUpperLeft())
926 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600927 else
928 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600929
930 if (glslangIntermediate->getEarlyFragmentTests())
931 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
932
933 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600934 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
935 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600936 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600937 }
John Kessenich4016e382016-07-15 11:53:56 -0600938 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600939 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
940
941 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
942 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600943 break;
944
945 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600946 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600947 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
948 glslangIntermediate->getLocalSize(1),
949 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600950 break;
951
952 default:
953 break;
954 }
John Kessenich140f3df2015-06-26 16:58:36 -0600955}
956
John Kessenichfca82622016-11-26 13:23:20 -0700957// Finish creating SPV, after the traversal is complete.
958void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700959{
John Kessenich517fe7a2016-11-26 13:31:47 -0700960 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700961 builder.setBuildPoint(shaderEntry->getLastBlock());
962 builder.leaveFunction();
963 }
964
John Kessenich7ba63412015-12-20 17:37:07 -0700965 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100966 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
967 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700968
qiningda397332016-03-09 19:54:03 -0500969 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700970}
971
John Kessenichfca82622016-11-26 13:23:20 -0700972// Write the SPV into 'out'.
973void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600974{
John Kessenichfca82622016-11-26 13:23:20 -0700975 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600976}
977
978//
979// Implement the traversal functions.
980//
981// Return true from interior nodes to have the external traversal
982// continue on to children. Return false if children were
983// already processed.
984//
985
986//
qining25262b32016-05-06 17:25:16 -0400987// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -0600988// - uniform/input reads
989// - output writes
990// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
991// - something simple that degenerates into the last bullet
992//
993void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
994{
qining75d1d802016-04-06 14:42:01 -0400995 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
996 if (symbol->getType().getQualifier().isSpecConstant())
997 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
998
John Kessenich140f3df2015-06-26 16:58:36 -0600999 // getSymbolId() will set up all the IO decorations on the first call.
1000 // Formal function parameters were mapped during makeFunctions().
1001 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001002
1003 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1004 if (builder.isPointer(id)) {
1005 spv::StorageClass sc = builder.getStorageClass(id);
1006 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1007 iOSet.insert(id);
1008 }
1009
1010 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001011 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001012 // Prepare to generate code for the access
1013
1014 // L-value chains will be computed left to right. We're on the symbol now,
1015 // which is the left-most part of the access chain, so now is "clear" time,
1016 // followed by setting the base.
1017 builder.clearAccessChain();
1018
1019 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001020 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001021 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001022 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001023 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001024 // These are also pure R-values.
1025 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001026 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001027 builder.setAccessChainRValue(id);
1028 else
1029 builder.setAccessChainLValue(id);
1030 }
1031}
1032
1033bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1034{
qining40887662016-04-03 22:20:42 -04001035 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1036 if (node->getType().getQualifier().isSpecConstant())
1037 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1038
John Kessenich140f3df2015-06-26 16:58:36 -06001039 // First, handle special cases
1040 switch (node->getOp()) {
1041 case glslang::EOpAssign:
1042 case glslang::EOpAddAssign:
1043 case glslang::EOpSubAssign:
1044 case glslang::EOpMulAssign:
1045 case glslang::EOpVectorTimesMatrixAssign:
1046 case glslang::EOpVectorTimesScalarAssign:
1047 case glslang::EOpMatrixTimesScalarAssign:
1048 case glslang::EOpMatrixTimesMatrixAssign:
1049 case glslang::EOpDivAssign:
1050 case glslang::EOpModAssign:
1051 case glslang::EOpAndAssign:
1052 case glslang::EOpInclusiveOrAssign:
1053 case glslang::EOpExclusiveOrAssign:
1054 case glslang::EOpLeftShiftAssign:
1055 case glslang::EOpRightShiftAssign:
1056 // A bin-op assign "a += b" means the same thing as "a = a + b"
1057 // where a is evaluated before b. For a simple assignment, GLSL
1058 // says to evaluate the left before the right. So, always, left
1059 // node then right node.
1060 {
1061 // get the left l-value, save it away
1062 builder.clearAccessChain();
1063 node->getLeft()->traverse(this);
1064 spv::Builder::AccessChain lValue = builder.getAccessChain();
1065
1066 // evaluate the right
1067 builder.clearAccessChain();
1068 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001069 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001070
1071 if (node->getOp() != glslang::EOpAssign) {
1072 // the left is also an r-value
1073 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001074 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001075
1076 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001077 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001078 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001079 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1080 node->getType().getBasicType());
1081
1082 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001083 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001084 }
1085
1086 // store the result
1087 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001088 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001089
1090 // assignments are expressions having an rValue after they are evaluated...
1091 builder.clearAccessChain();
1092 builder.setAccessChainRValue(rValue);
1093 }
1094 return false;
1095 case glslang::EOpIndexDirect:
1096 case glslang::EOpIndexDirectStruct:
1097 {
1098 // Get the left part of the access chain.
1099 node->getLeft()->traverse(this);
1100
1101 // Add the next element in the chain
1102
David Netoa901ffe2016-06-08 14:11:40 +01001103 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001104 if (! node->getLeft()->getType().isArray() &&
1105 node->getLeft()->getType().isVector() &&
1106 node->getOp() == glslang::EOpIndexDirect) {
1107 // This is essentially a hard-coded vector swizzle of size 1,
1108 // so short circuit the access-chain stuff with a swizzle.
1109 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001110 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001111 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001112 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001113 int spvIndex = glslangIndex;
1114 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1115 node->getOp() == glslang::EOpIndexDirectStruct)
1116 {
1117 // This may be, e.g., an anonymous block-member selection, which generally need
1118 // index remapping due to hidden members in anonymous blocks.
1119 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1120 assert(remapper.size() > 0);
1121 spvIndex = remapper[glslangIndex];
1122 }
John Kessenichebb50532016-05-16 19:22:05 -06001123
David Netoa901ffe2016-06-08 14:11:40 +01001124 // normal case for indexing array or structure or block
1125 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1126
1127 // Add capabilities here for accessing PointSize and clip/cull distance.
1128 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001129 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001130 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001131 }
1132 }
1133 return false;
1134 case glslang::EOpIndexIndirect:
1135 {
1136 // Structure or array or vector indirection.
1137 // Will use native SPIR-V access-chain for struct and array indirection;
1138 // matrices are arrays of vectors, so will also work for a matrix.
1139 // Will use the access chain's 'component' for variable index into a vector.
1140
1141 // This adapter is building access chains left to right.
1142 // Set up the access chain to the left.
1143 node->getLeft()->traverse(this);
1144
1145 // save it so that computing the right side doesn't trash it
1146 spv::Builder::AccessChain partial = builder.getAccessChain();
1147
1148 // compute the next index in the chain
1149 builder.clearAccessChain();
1150 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001151 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001152
1153 // restore the saved access chain
1154 builder.setAccessChain(partial);
1155
1156 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001157 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001158 else
John Kessenichfa668da2015-09-13 14:46:30 -06001159 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001160 }
1161 return false;
1162 case glslang::EOpVectorSwizzle:
1163 {
1164 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001165 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001166 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001167 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001168 }
1169 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001170 case glslang::EOpMatrixSwizzle:
1171 logger->missingFunctionality("matrix swizzle");
1172 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001173 case glslang::EOpLogicalOr:
1174 case glslang::EOpLogicalAnd:
1175 {
1176
1177 // These may require short circuiting, but can sometimes be done as straight
1178 // binary operations. The right operand must be short circuited if it has
1179 // side effects, and should probably be if it is complex.
1180 if (isTrivial(node->getRight()->getAsTyped()))
1181 break; // handle below as a normal binary operation
1182 // otherwise, we need to do dynamic short circuiting on the right operand
1183 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1184 builder.clearAccessChain();
1185 builder.setAccessChainRValue(result);
1186 }
1187 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001188 default:
1189 break;
1190 }
1191
1192 // Assume generic binary op...
1193
John Kessenich32cfd492016-02-02 12:37:46 -07001194 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001195 builder.clearAccessChain();
1196 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001197 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001198
John Kessenich32cfd492016-02-02 12:37:46 -07001199 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001200 builder.clearAccessChain();
1201 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001202 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001203
John Kessenich32cfd492016-02-02 12:37:46 -07001204 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001205 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001206 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001207 convertGlslangToSpvType(node->getType()), left, right,
1208 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001209
John Kessenich50e57562015-12-21 21:21:11 -07001210 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001211 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001212 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001213 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001214 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001215 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001216 return false;
1217 }
John Kessenich140f3df2015-06-26 16:58:36 -06001218}
1219
1220bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1221{
qining40887662016-04-03 22:20:42 -04001222 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1223 if (node->getType().getQualifier().isSpecConstant())
1224 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1225
John Kessenichfc51d282015-08-19 13:34:18 -06001226 spv::Id result = spv::NoResult;
1227
1228 // try texturing first
1229 result = createImageTextureFunctionCall(node);
1230 if (result != spv::NoResult) {
1231 builder.clearAccessChain();
1232 builder.setAccessChainRValue(result);
1233
1234 return false; // done with this node
1235 }
1236
1237 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001238
1239 if (node->getOp() == glslang::EOpArrayLength) {
1240 // Quite special; won't want to evaluate the operand.
1241
1242 // Normal .length() would have been constant folded by the front-end.
1243 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001244 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001245 assert(node->getOperand()->getType().isRuntimeSizedArray());
1246 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1247 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001248 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1249 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001250
1251 builder.clearAccessChain();
1252 builder.setAccessChainRValue(length);
1253
1254 return false;
1255 }
1256
John Kessenichfc51d282015-08-19 13:34:18 -06001257 // Start by evaluating the operand
1258
John Kessenich8c8505c2016-07-26 12:50:38 -06001259 // Does it need a swizzle inversion? If so, evaluation is inverted;
1260 // operate first on the swizzle base, then apply the swizzle.
1261 spv::Id invertedType = spv::NoType;
1262 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1263 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1264 invertedType = getInvertedSwizzleType(*node->getOperand());
1265
John Kessenich140f3df2015-06-26 16:58:36 -06001266 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001267 if (invertedType != spv::NoType)
1268 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1269 else
1270 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001271
Rex Xufc618912015-09-09 16:42:49 +08001272 spv::Id operand = spv::NoResult;
1273
1274 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1275 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001276 node->getOp() == glslang::EOpAtomicCounter ||
1277 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001278 operand = builder.accessChainGetLValue(); // Special case l-value operands
1279 else
John Kessenich32cfd492016-02-02 12:37:46 -07001280 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001281
John Kessenichf6640762016-08-01 19:44:00 -06001282 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001283 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001284
1285 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001286 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001287 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001288
1289 // if not, then possibly an operation
1290 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001291 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001292
1293 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001294 if (invertedType)
1295 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1296
John Kessenich140f3df2015-06-26 16:58:36 -06001297 builder.clearAccessChain();
1298 builder.setAccessChainRValue(result);
1299
1300 return false; // done with this node
1301 }
1302
1303 // it must be a special case, check...
1304 switch (node->getOp()) {
1305 case glslang::EOpPostIncrement:
1306 case glslang::EOpPostDecrement:
1307 case glslang::EOpPreIncrement:
1308 case glslang::EOpPreDecrement:
1309 {
1310 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001311 spv::Id one = 0;
1312 if (node->getBasicType() == glslang::EbtFloat)
1313 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001314 else if (node->getBasicType() == glslang::EbtDouble)
1315 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001316#ifdef AMD_EXTENSIONS
1317 else if (node->getBasicType() == glslang::EbtFloat16)
1318 one = builder.makeFloat16Constant(1.0F);
1319#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001320 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1321 one = builder.makeInt64Constant(1);
1322 else
1323 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001324 glslang::TOperator op;
1325 if (node->getOp() == glslang::EOpPreIncrement ||
1326 node->getOp() == glslang::EOpPostIncrement)
1327 op = glslang::EOpAdd;
1328 else
1329 op = glslang::EOpSub;
1330
John Kessenichf6640762016-08-01 19:44:00 -06001331 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001332 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001333 convertGlslangToSpvType(node->getType()), operand, one,
1334 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001335 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001336
1337 // The result of operation is always stored, but conditionally the
1338 // consumed result. The consumed result is always an r-value.
1339 builder.accessChainStore(result);
1340 builder.clearAccessChain();
1341 if (node->getOp() == glslang::EOpPreIncrement ||
1342 node->getOp() == glslang::EOpPreDecrement)
1343 builder.setAccessChainRValue(result);
1344 else
1345 builder.setAccessChainRValue(operand);
1346 }
1347
1348 return false;
1349
1350 case glslang::EOpEmitStreamVertex:
1351 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1352 return false;
1353 case glslang::EOpEndStreamPrimitive:
1354 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1355 return false;
1356
1357 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001358 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001359 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001360 }
John Kessenich140f3df2015-06-26 16:58:36 -06001361}
1362
1363bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1364{
qining27e04a02016-04-14 16:40:20 -04001365 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1366 if (node->getType().getQualifier().isSpecConstant())
1367 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1368
John Kessenichfc51d282015-08-19 13:34:18 -06001369 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001370 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1371 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001372
1373 // try texturing
1374 result = createImageTextureFunctionCall(node);
1375 if (result != spv::NoResult) {
1376 builder.clearAccessChain();
1377 builder.setAccessChainRValue(result);
1378
1379 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001380 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001381 // "imageStore" is a special case, which has no result
1382 return false;
1383 }
John Kessenichfc51d282015-08-19 13:34:18 -06001384
John Kessenich140f3df2015-06-26 16:58:36 -06001385 glslang::TOperator binOp = glslang::EOpNull;
1386 bool reduceComparison = true;
1387 bool isMatrix = false;
1388 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001389 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001390
1391 assert(node->getOp());
1392
John Kessenichf6640762016-08-01 19:44:00 -06001393 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001394
1395 switch (node->getOp()) {
1396 case glslang::EOpSequence:
1397 {
1398 if (preVisit)
1399 ++sequenceDepth;
1400 else
1401 --sequenceDepth;
1402
1403 if (sequenceDepth == 1) {
1404 // If this is the parent node of all the functions, we want to see them
1405 // early, so all call points have actual SPIR-V functions to reference.
1406 // In all cases, still let the traverser visit the children for us.
1407 makeFunctions(node->getAsAggregate()->getSequence());
1408
John Kessenich6fccb3c2016-09-19 16:01:41 -06001409 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001410 // anything else gets there, so visit out of order, doing them all now.
1411 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1412
John Kessenich6a60c2f2016-12-08 21:01:59 -07001413 // 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 -06001414 // so do them manually.
1415 visitFunctions(node->getAsAggregate()->getSequence());
1416
1417 return false;
1418 }
1419
1420 return true;
1421 }
1422 case glslang::EOpLinkerObjects:
1423 {
1424 if (visit == glslang::EvPreVisit)
1425 linkageOnly = true;
1426 else
1427 linkageOnly = false;
1428
1429 return true;
1430 }
1431 case glslang::EOpComma:
1432 {
1433 // processing from left to right naturally leaves the right-most
1434 // lying around in the access chain
1435 glslang::TIntermSequence& glslangOperands = node->getSequence();
1436 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1437 glslangOperands[i]->traverse(this);
1438
1439 return false;
1440 }
1441 case glslang::EOpFunction:
1442 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001443 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001444 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001445 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001446 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001447 } else {
1448 handleFunctionEntry(node);
1449 }
1450 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001451 if (inEntryPoint)
1452 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001453 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001454 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 }
1456
1457 return true;
1458 case glslang::EOpParameters:
1459 // Parameters will have been consumed by EOpFunction processing, but not
1460 // the body, so we still visited the function node's children, making this
1461 // child redundant.
1462 return false;
1463 case glslang::EOpFunctionCall:
1464 {
1465 if (node->isUserDefined())
1466 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001467 // 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 -07001468 if (result) {
1469 builder.clearAccessChain();
1470 builder.setAccessChainRValue(result);
1471 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001472 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001473
1474 return false;
1475 }
1476 case glslang::EOpConstructMat2x2:
1477 case glslang::EOpConstructMat2x3:
1478 case glslang::EOpConstructMat2x4:
1479 case glslang::EOpConstructMat3x2:
1480 case glslang::EOpConstructMat3x3:
1481 case glslang::EOpConstructMat3x4:
1482 case glslang::EOpConstructMat4x2:
1483 case glslang::EOpConstructMat4x3:
1484 case glslang::EOpConstructMat4x4:
1485 case glslang::EOpConstructDMat2x2:
1486 case glslang::EOpConstructDMat2x3:
1487 case glslang::EOpConstructDMat2x4:
1488 case glslang::EOpConstructDMat3x2:
1489 case glslang::EOpConstructDMat3x3:
1490 case glslang::EOpConstructDMat3x4:
1491 case glslang::EOpConstructDMat4x2:
1492 case glslang::EOpConstructDMat4x3:
1493 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001494#ifdef AMD_EXTENSIONS
1495 case glslang::EOpConstructF16Mat2x2:
1496 case glslang::EOpConstructF16Mat2x3:
1497 case glslang::EOpConstructF16Mat2x4:
1498 case glslang::EOpConstructF16Mat3x2:
1499 case glslang::EOpConstructF16Mat3x3:
1500 case glslang::EOpConstructF16Mat3x4:
1501 case glslang::EOpConstructF16Mat4x2:
1502 case glslang::EOpConstructF16Mat4x3:
1503 case glslang::EOpConstructF16Mat4x4:
1504#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001505 isMatrix = true;
1506 // fall through
1507 case glslang::EOpConstructFloat:
1508 case glslang::EOpConstructVec2:
1509 case glslang::EOpConstructVec3:
1510 case glslang::EOpConstructVec4:
1511 case glslang::EOpConstructDouble:
1512 case glslang::EOpConstructDVec2:
1513 case glslang::EOpConstructDVec3:
1514 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001515#ifdef AMD_EXTENSIONS
1516 case glslang::EOpConstructFloat16:
1517 case glslang::EOpConstructF16Vec2:
1518 case glslang::EOpConstructF16Vec3:
1519 case glslang::EOpConstructF16Vec4:
1520#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001521 case glslang::EOpConstructBool:
1522 case glslang::EOpConstructBVec2:
1523 case glslang::EOpConstructBVec3:
1524 case glslang::EOpConstructBVec4:
1525 case glslang::EOpConstructInt:
1526 case glslang::EOpConstructIVec2:
1527 case glslang::EOpConstructIVec3:
1528 case glslang::EOpConstructIVec4:
1529 case glslang::EOpConstructUint:
1530 case glslang::EOpConstructUVec2:
1531 case glslang::EOpConstructUVec3:
1532 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001533 case glslang::EOpConstructInt64:
1534 case glslang::EOpConstructI64Vec2:
1535 case glslang::EOpConstructI64Vec3:
1536 case glslang::EOpConstructI64Vec4:
1537 case glslang::EOpConstructUint64:
1538 case glslang::EOpConstructU64Vec2:
1539 case glslang::EOpConstructU64Vec3:
1540 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001541 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001542 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001543 {
1544 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001545 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001546 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001547 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001548 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001549 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001550 std::vector<spv::Id> constituents;
1551 for (int c = 0; c < (int)arguments.size(); ++c)
1552 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001553 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001554 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001555 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001556 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001557 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001558
1559 builder.clearAccessChain();
1560 builder.setAccessChainRValue(constructed);
1561
1562 return false;
1563 }
1564
1565 // These six are component-wise compares with component-wise results.
1566 // Forward on to createBinaryOperation(), requesting a vector result.
1567 case glslang::EOpLessThan:
1568 case glslang::EOpGreaterThan:
1569 case glslang::EOpLessThanEqual:
1570 case glslang::EOpGreaterThanEqual:
1571 case glslang::EOpVectorEqual:
1572 case glslang::EOpVectorNotEqual:
1573 {
1574 // Map the operation to a binary
1575 binOp = node->getOp();
1576 reduceComparison = false;
1577 switch (node->getOp()) {
1578 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1579 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1580 default: binOp = node->getOp(); break;
1581 }
1582
1583 break;
1584 }
1585 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001586 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001587 binOp = glslang::EOpMul;
1588 break;
1589 case glslang::EOpOuterProduct:
1590 // two vectors multiplied to make a matrix
1591 binOp = glslang::EOpOuterProduct;
1592 break;
1593 case glslang::EOpDot:
1594 {
qining25262b32016-05-06 17:25:16 -04001595 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001596 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001597 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001598 binOp = glslang::EOpMul;
1599 break;
1600 }
1601 case glslang::EOpMod:
1602 // when an aggregate, this is the floating-point mod built-in function,
1603 // which can be emitted by the one in createBinaryOperation()
1604 binOp = glslang::EOpMod;
1605 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001606 case glslang::EOpEmitVertex:
1607 case glslang::EOpEndPrimitive:
1608 case glslang::EOpBarrier:
1609 case glslang::EOpMemoryBarrier:
1610 case glslang::EOpMemoryBarrierAtomicCounter:
1611 case glslang::EOpMemoryBarrierBuffer:
1612 case glslang::EOpMemoryBarrierImage:
1613 case glslang::EOpMemoryBarrierShared:
1614 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001615 case glslang::EOpAllMemoryBarrierWithGroupSync:
1616 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1617 case glslang::EOpWorkgroupMemoryBarrier:
1618 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001619 noReturnValue = true;
1620 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1621 break;
1622
John Kessenich426394d2015-07-23 10:22:48 -06001623 case glslang::EOpAtomicAdd:
1624 case glslang::EOpAtomicMin:
1625 case glslang::EOpAtomicMax:
1626 case glslang::EOpAtomicAnd:
1627 case glslang::EOpAtomicOr:
1628 case glslang::EOpAtomicXor:
1629 case glslang::EOpAtomicExchange:
1630 case glslang::EOpAtomicCompSwap:
1631 atomic = true;
1632 break;
1633
John Kessenich140f3df2015-06-26 16:58:36 -06001634 default:
1635 break;
1636 }
1637
1638 //
1639 // See if it maps to a regular operation.
1640 //
John Kessenich140f3df2015-06-26 16:58:36 -06001641 if (binOp != glslang::EOpNull) {
1642 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1643 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1644 assert(left && right);
1645
1646 builder.clearAccessChain();
1647 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001648 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001649
1650 builder.clearAccessChain();
1651 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001652 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001653
qining25262b32016-05-06 17:25:16 -04001654 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001655 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001656 left->getType().getBasicType(), reduceComparison);
1657
1658 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001659 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001660 builder.clearAccessChain();
1661 builder.setAccessChainRValue(result);
1662
1663 return false;
1664 }
1665
John Kessenich426394d2015-07-23 10:22:48 -06001666 //
1667 // Create the list of operands.
1668 //
John Kessenich140f3df2015-06-26 16:58:36 -06001669 glslang::TIntermSequence& glslangOperands = node->getSequence();
1670 std::vector<spv::Id> operands;
1671 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001672 // special case l-value operands; there are just a few
1673 bool lvalue = false;
1674 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001675 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001676 case glslang::EOpModf:
1677 if (arg == 1)
1678 lvalue = true;
1679 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001680 case glslang::EOpInterpolateAtSample:
1681 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001682#ifdef AMD_EXTENSIONS
1683 case glslang::EOpInterpolateAtVertex:
1684#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001685 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001686 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001687
1688 // Does it need a swizzle inversion? If so, evaluation is inverted;
1689 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001690 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001691 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1692 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1693 }
Rex Xu7a26c172015-12-08 17:12:09 +08001694 break;
Rex Xud4782c12015-09-06 16:30:11 +08001695 case glslang::EOpAtomicAdd:
1696 case glslang::EOpAtomicMin:
1697 case glslang::EOpAtomicMax:
1698 case glslang::EOpAtomicAnd:
1699 case glslang::EOpAtomicOr:
1700 case glslang::EOpAtomicXor:
1701 case glslang::EOpAtomicExchange:
1702 case glslang::EOpAtomicCompSwap:
1703 if (arg == 0)
1704 lvalue = true;
1705 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001706 case glslang::EOpAddCarry:
1707 case glslang::EOpSubBorrow:
1708 if (arg == 2)
1709 lvalue = true;
1710 break;
1711 case glslang::EOpUMulExtended:
1712 case glslang::EOpIMulExtended:
1713 if (arg >= 2)
1714 lvalue = true;
1715 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001716 default:
1717 break;
1718 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001719 builder.clearAccessChain();
1720 if (invertedType != spv::NoType && arg == 0)
1721 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1722 else
1723 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001724 if (lvalue)
1725 operands.push_back(builder.accessChainGetLValue());
1726 else
John Kessenich32cfd492016-02-02 12:37:46 -07001727 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001728 }
John Kessenich426394d2015-07-23 10:22:48 -06001729
1730 if (atomic) {
1731 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001732 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001733 } else {
1734 // Pass through to generic operations.
1735 switch (glslangOperands.size()) {
1736 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001737 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001738 break;
1739 case 1:
qining25262b32016-05-06 17:25:16 -04001740 result = createUnaryOperation(
1741 node->getOp(), precision,
1742 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001743 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001744 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001745 break;
1746 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001747 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001748 break;
1749 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001750 if (invertedType)
1751 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001752 }
1753
1754 if (noReturnValue)
1755 return false;
1756
1757 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001758 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001759 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001760 } else {
1761 builder.clearAccessChain();
1762 builder.setAccessChainRValue(result);
1763 return false;
1764 }
1765}
1766
John Kessenich433e9ff2017-01-26 20:31:11 -07001767// This path handles both if-then-else and ?:
1768// The if-then-else has a node type of void, while
1769// ?: has either a void or a non-void node type
1770//
1771// Leaving the result, when not void:
1772// GLSL only has r-values as the result of a :?, but
1773// if we have an l-value, that can be more efficient if it will
1774// become the base of a complex r-value expression, because the
1775// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001776bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1777{
John Kessenich433e9ff2017-01-26 20:31:11 -07001778 // See if it simple and safe to generate OpSelect instead of using control flow.
1779 // Crucially, side effects must be avoided, and there are performance trade-offs.
1780 // Return true if good idea (and safe) for OpSelect, false otherwise.
1781 const auto selectPolicy = [&]() -> bool {
1782 if (node->getBasicType() == glslang::EbtVoid)
1783 return false;
1784
1785 if (node->getTrueBlock() == nullptr ||
1786 node->getFalseBlock() == nullptr)
1787 return false;
1788
1789 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1790 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1791
1792 // return true if a single operand to ? : is okay for OpSelect
1793 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001794 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001795 };
1796
1797 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1798 operandOkay(node->getFalseBlock()->getAsTyped());
1799 };
1800
1801 // Emit OpSelect for this selection.
1802 const auto handleAsOpSelect = [&]() {
1803 node->getCondition()->traverse(this);
1804 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1805 node->getTrueBlock()->traverse(this);
1806 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1807 node->getFalseBlock()->traverse(this);
1808 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1809
1810 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1811 builder.clearAccessChain();
1812 builder.setAccessChainRValue(select);
1813 };
1814
1815 // Try for OpSelect
1816
1817 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001818 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1819 if (node->getType().getQualifier().isSpecConstant())
1820 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1821
John Kessenich433e9ff2017-01-26 20:31:11 -07001822 handleAsOpSelect();
1823 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001824 }
1825
John Kessenich433e9ff2017-01-26 20:31:11 -07001826 // Instead, emit control flow...
1827
1828 // Don't handle results as temporaries, because there will be two names
1829 // and better to leave SSA to later passes.
1830 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1831 ? spv::NoResult
1832 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1833
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // emit the condition before doing anything with selection
1835 node->getCondition()->traverse(this);
1836
1837 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001838 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001839
John Kessenich433e9ff2017-01-26 20:31:11 -07001840 // emit the "then" statement
1841 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001842 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001843 if (result != spv::NoResult)
1844 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001845 }
1846
John Kessenich433e9ff2017-01-26 20:31:11 -07001847 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001848 ifBuilder.makeBeginElse();
1849 // emit the "else" statement
1850 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001851 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001852 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001853 }
1854
John Kessenich433e9ff2017-01-26 20:31:11 -07001855 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001856 ifBuilder.makeEndIf();
1857
John Kessenich433e9ff2017-01-26 20:31:11 -07001858 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001859 // GLSL only has r-values as the result of a :?, but
1860 // if we have an l-value, that can be more efficient if it will
1861 // become the base of a complex r-value expression, because the
1862 // next layer copies r-values into memory to use the access-chain mechanism
1863 builder.clearAccessChain();
1864 builder.setAccessChainLValue(result);
1865 }
1866
1867 return false;
1868}
1869
1870bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1871{
1872 // emit and get the condition before doing anything with switch
1873 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001874 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001875
1876 // browse the children to sort out code segments
1877 int defaultSegment = -1;
1878 std::vector<TIntermNode*> codeSegments;
1879 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1880 std::vector<int> caseValues;
1881 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1882 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1883 TIntermNode* child = *c;
1884 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001885 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001886 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001887 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001888 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1889 } else
1890 codeSegments.push_back(child);
1891 }
1892
qining25262b32016-05-06 17:25:16 -04001893 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001894 // statements between the last case and the end of the switch statement
1895 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1896 (int)codeSegments.size() == defaultSegment)
1897 codeSegments.push_back(nullptr);
1898
1899 // make the switch statement
1900 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001901 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001902
1903 // emit all the code in the segments
1904 breakForLoop.push(false);
1905 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1906 builder.nextSwitchSegment(segmentBlocks, s);
1907 if (codeSegments[s])
1908 codeSegments[s]->traverse(this);
1909 else
1910 builder.addSwitchBreak();
1911 }
1912 breakForLoop.pop();
1913
1914 builder.endSwitch(segmentBlocks);
1915
1916 return false;
1917}
1918
1919void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1920{
1921 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001922 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001923
1924 builder.clearAccessChain();
1925 builder.setAccessChainRValue(constant);
1926}
1927
1928bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1929{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001930 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001931 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001932 // Spec requires back edges to target header blocks, and every header block
1933 // must dominate its merge block. Make a header block first to ensure these
1934 // conditions are met. By definition, it will contain OpLoopMerge, followed
1935 // by a block-ending branch. But we don't want to put any other body/test
1936 // instructions in it, since the body/test may have arbitrary instructions,
1937 // including merges of its own.
1938 builder.setBuildPoint(&blocks.head);
1939 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001940 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001941 spv::Block& test = builder.makeNewBlock();
1942 builder.createBranch(&test);
1943
1944 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001945 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001946 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001947 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001948 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1949
1950 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001951 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001952 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001953 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001954 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001955 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001956
1957 builder.setBuildPoint(&blocks.continue_target);
1958 if (node->getTerminal())
1959 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001960 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001961 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001962 builder.createBranch(&blocks.body);
1963
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001964 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001965 builder.setBuildPoint(&blocks.body);
1966 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001967 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001968 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001969 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001970
1971 builder.setBuildPoint(&blocks.continue_target);
1972 if (node->getTerminal())
1973 node->getTerminal()->traverse(this);
1974 if (node->getTest()) {
1975 node->getTest()->traverse(this);
1976 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001977 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001978 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001979 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001980 // TODO: unless there was a break/return/discard instruction
1981 // somewhere in the body, this is an infinite loop, so we should
1982 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001983 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001984 }
John Kessenich140f3df2015-06-26 16:58:36 -06001985 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001986 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001987 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001988 return false;
1989}
1990
1991bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1992{
1993 if (node->getExpression())
1994 node->getExpression()->traverse(this);
1995
1996 switch (node->getFlowOp()) {
1997 case glslang::EOpKill:
1998 builder.makeDiscard();
1999 break;
2000 case glslang::EOpBreak:
2001 if (breakForLoop.top())
2002 builder.createLoopExit();
2003 else
2004 builder.addSwitchBreak();
2005 break;
2006 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002007 builder.createLoopContinue();
2008 break;
2009 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002010 if (node->getExpression()) {
2011 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2012 spv::Id returnId = accessChainLoad(glslangReturnType);
2013 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2014 builder.clearAccessChain();
2015 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2016 builder.setAccessChainLValue(copyId);
2017 multiTypeStore(glslangReturnType, returnId);
2018 returnId = builder.createLoad(copyId);
2019 }
2020 builder.makeReturn(false, returnId);
2021 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002022 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002023
2024 builder.clearAccessChain();
2025 break;
2026
2027 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002028 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002029 break;
2030 }
2031
2032 return false;
2033}
2034
2035spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2036{
qining25262b32016-05-06 17:25:16 -04002037 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002038 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002039 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002040 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002041 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002042 }
2043
2044 // Now, handle actual variables
2045 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2046 spv::Id spvType = convertGlslangToSpvType(node->getType());
2047
2048 const char* name = node->getName().c_str();
2049 if (glslang::IsAnonymous(name))
2050 name = "";
2051
2052 return builder.createVariable(storageClass, spvType, name);
2053}
2054
2055// Return type Id of the sampled type.
2056spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2057{
2058 switch (sampler.type) {
2059 case glslang::EbtFloat: return builder.makeFloatType(32);
2060 case glslang::EbtInt: return builder.makeIntType(32);
2061 case glslang::EbtUint: return builder.makeUintType(32);
2062 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002063 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002064 return builder.makeFloatType(32);
2065 }
2066}
2067
John Kessenich8c8505c2016-07-26 12:50:38 -06002068// If node is a swizzle operation, return the type that should be used if
2069// the swizzle base is first consumed by another operation, before the swizzle
2070// is applied.
2071spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2072{
John Kessenichecba76f2017-01-06 00:34:48 -07002073 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002074 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2075 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2076 else
2077 return spv::NoType;
2078}
2079
2080// When inverting a swizzle with a parent op, this function
2081// will apply the swizzle operation to a completed parent operation.
2082spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2083{
2084 std::vector<unsigned> swizzle;
2085 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2086 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2087}
2088
John Kessenich8c8505c2016-07-26 12:50:38 -06002089// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2090void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2091{
2092 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2093 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2094 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2095}
2096
John Kessenich3ac051e2015-12-20 11:29:16 -07002097// Convert from a glslang type to an SPV type, by calling into a
2098// recursive version of this function. This establishes the inherited
2099// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002100spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2101{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002102 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002103}
2104
2105// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002106// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002107// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002108spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002109{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002110 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002111
2112 switch (type.getBasicType()) {
2113 case glslang::EbtVoid:
2114 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002115 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002116 break;
2117 case glslang::EbtFloat:
2118 spvType = builder.makeFloatType(32);
2119 break;
2120 case glslang::EbtDouble:
2121 spvType = builder.makeFloatType(64);
2122 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002123#ifdef AMD_EXTENSIONS
2124 case glslang::EbtFloat16:
2125 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002126 spvType = builder.makeFloatType(16);
2127 break;
2128#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002129 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002130 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2131 // a 32-bit int where non-0 means true.
2132 if (explicitLayout != glslang::ElpNone)
2133 spvType = builder.makeUintType(32);
2134 else
2135 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002136 break;
2137 case glslang::EbtInt:
2138 spvType = builder.makeIntType(32);
2139 break;
2140 case glslang::EbtUint:
2141 spvType = builder.makeUintType(32);
2142 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002143 case glslang::EbtInt64:
2144 builder.addCapability(spv::CapabilityInt64);
2145 spvType = builder.makeIntType(64);
2146 break;
2147 case glslang::EbtUint64:
2148 builder.addCapability(spv::CapabilityInt64);
2149 spvType = builder.makeUintType(64);
2150 break;
John Kessenich426394d2015-07-23 10:22:48 -06002151 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002152 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002153 spvType = builder.makeUintType(32);
2154 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002155 case glslang::EbtSampler:
2156 {
2157 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002158 if (sampler.sampler) {
2159 // pure sampler
2160 spvType = builder.makeSamplerType();
2161 } else {
2162 // an image is present, make its type
2163 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2164 sampler.image ? 2 : 1, TranslateImageFormat(type));
2165 if (sampler.combined) {
2166 // already has both image and sampler, make the combined type
2167 spvType = builder.makeSampledImageType(spvType);
2168 }
John Kessenich55e7d112015-11-15 21:33:39 -07002169 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002170 }
John Kessenich140f3df2015-06-26 16:58:36 -06002171 break;
2172 case glslang::EbtStruct:
2173 case glslang::EbtBlock:
2174 {
2175 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002176 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002177
2178 // Try to share structs for different layouts, but not yet for other
2179 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002180 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002181 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002182 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002183 break;
2184
2185 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002186 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002187 memberRemapper[glslangMembers].resize(glslangMembers->size());
2188 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002189 }
2190 break;
2191 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002192 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002193 break;
2194 }
2195
2196 if (type.isMatrix())
2197 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2198 else {
2199 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2200 if (type.getVectorSize() > 1)
2201 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2202 }
2203
2204 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002205 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2206
John Kessenichc9a80832015-09-12 12:17:44 -06002207 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002208 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002209 // We need to decorate array strides for types needing explicit layout, except blocks.
2210 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002211 // Use a dummy glslang type for querying internal strides of
2212 // arrays of arrays, but using just a one-dimensional array.
2213 glslang::TType simpleArrayType(type, 0); // deference type of the array
2214 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2215 simpleArrayType.getArraySizes().dereference();
2216
2217 // Will compute the higher-order strides here, rather than making a whole
2218 // pile of types and doing repetitive recursion on their contents.
2219 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2220 }
John Kessenichf8842e52016-01-04 19:22:56 -07002221
2222 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002223 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002224 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002225 if (stride > 0)
2226 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002227 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002228 }
2229 } else {
2230 // single-dimensional array, and don't yet have stride
2231
John Kessenichf8842e52016-01-04 19:22:56 -07002232 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002233 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2234 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002235 }
John Kessenich31ed4832015-09-09 17:51:38 -06002236
John Kessenichc9a80832015-09-12 12:17:44 -06002237 // Do the outer dimension, which might not be known for a runtime-sized array
2238 if (type.isRuntimeSizedArray()) {
2239 spvType = builder.makeRuntimeArray(spvType);
2240 } else {
2241 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002242 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002243 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002244 if (stride > 0)
2245 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002246 }
2247
2248 return spvType;
2249}
2250
John Kessenich6090df02016-06-30 21:18:02 -06002251// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2252// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2253// Mutually recursive with convertGlslangToSpvType().
2254spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2255 const glslang::TTypeList* glslangMembers,
2256 glslang::TLayoutPacking explicitLayout,
2257 const glslang::TQualifier& qualifier)
2258{
2259 // Create a vector of struct types for SPIR-V to consume
2260 std::vector<spv::Id> spvMembers;
2261 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2262 int locationOffset = 0; // for use across struct members, when they are called recursively
2263 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2264 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2265 if (glslangMember.hiddenMember()) {
2266 ++memberDelta;
2267 if (type.getBasicType() == glslang::EbtBlock)
2268 memberRemapper[glslangMembers][i] = -1;
2269 } else {
2270 if (type.getBasicType() == glslang::EbtBlock)
2271 memberRemapper[glslangMembers][i] = i - memberDelta;
2272 // modify just this child's view of the qualifier
2273 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2274 InheritQualifiers(memberQualifier, qualifier);
2275
2276 // manually inherit location; it's more complex
2277 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2278 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2279 if (qualifier.hasLocation())
2280 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2281
2282 // recurse
2283 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2284 }
2285 }
2286
2287 // Make the SPIR-V type
2288 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002289 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002290 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2291
2292 // Decorate it
2293 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2294
2295 return spvType;
2296}
2297
2298void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2299 const glslang::TTypeList* glslangMembers,
2300 glslang::TLayoutPacking explicitLayout,
2301 const glslang::TQualifier& qualifier,
2302 spv::Id spvType)
2303{
2304 // Name and decorate the non-hidden members
2305 int offset = -1;
2306 int locationOffset = 0; // for use within the members of this struct
2307 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2308 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2309 int member = i;
2310 if (type.getBasicType() == glslang::EbtBlock)
2311 member = memberRemapper[glslangMembers][i];
2312
2313 // modify just this child's view of the qualifier
2314 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2315 InheritQualifiers(memberQualifier, qualifier);
2316
2317 // using -1 above to indicate a hidden member
2318 if (member >= 0) {
2319 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2320 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2321 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2322 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002323 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2324 type.getQualifier().storage == glslang::EvqVaryingOut) {
2325 if (type.getBasicType() == glslang::EbtBlock ||
2326 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002327 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2328 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2329 }
2330 }
2331 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2332
2333 if (qualifier.storage == glslang::EvqBuffer) {
2334 std::vector<spv::Decoration> memory;
2335 TranslateMemoryDecoration(memberQualifier, memory);
2336 for (unsigned int i = 0; i < memory.size(); ++i)
2337 addMemberDecoration(spvType, member, memory[i]);
2338 }
2339
John Kessenich2f47bc92016-06-30 21:47:35 -06002340 // Compute location decoration; tricky based on whether inheritance is at play and
2341 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002342 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2343 // probably move to the linker stage of the front end proper, and just have the
2344 // answer sitting already distributed throughout the individual member locations.
2345 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002346 // Ignore member locations if the container is an array, as that's
2347 // ill-specified and decisions have been made to not allow this anyway.
2348 // The object itself must have a location, and that comes out from decorating the object,
2349 // not the type (this code decorates types).
2350 if (! type.isArray()) {
2351 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2352 // struct members should not have explicit locations
2353 assert(type.getBasicType() != glslang::EbtStruct);
2354 location = memberQualifier.layoutLocation;
2355 } else if (type.getBasicType() != glslang::EbtBlock) {
2356 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2357 // The members, and their nested types, must not themselves have Location decorations.
2358 } else if (qualifier.hasLocation()) // inheritance
2359 location = qualifier.layoutLocation + locationOffset;
2360 }
John Kessenich6090df02016-06-30 21:18:02 -06002361 if (location >= 0)
2362 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2363
John Kessenich2f47bc92016-06-30 21:47:35 -06002364 if (qualifier.hasLocation()) // track for upcoming inheritance
2365 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2366
John Kessenich6090df02016-06-30 21:18:02 -06002367 // component, XFB, others
2368 if (glslangMember.getQualifier().hasComponent())
2369 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2370 if (glslangMember.getQualifier().hasXfbOffset())
2371 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2372 else if (explicitLayout != glslang::ElpNone) {
2373 // figure out what to do with offset, which is accumulating
2374 int nextOffset;
2375 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2376 if (offset >= 0)
2377 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2378 offset = nextOffset;
2379 }
2380
2381 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2382 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2383
2384 // built-in variable decorations
2385 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002386 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002387 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002388
2389#ifdef NV_EXTENSIONS
2390 if (builtIn == spv::BuiltInLayer) {
2391 // SPV_NV_viewport_array2 extension
2392 if (glslangMember.getQualifier().layoutViewportRelative){
2393 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2394 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2395 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2396 }
2397 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2398 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2399 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2400 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2401 }
2402 }
chaocdf3956c2017-02-14 14:52:34 -08002403 if (glslangMember.getQualifier().layoutPassthrough) {
2404 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2405 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2406 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2407 }
chaoc771d89f2017-01-13 01:10:53 -08002408#endif
John Kessenich6090df02016-06-30 21:18:02 -06002409 }
2410 }
2411
2412 // Decorate the structure
2413 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2414 addDecoration(spvType, TranslateBlockDecoration(type));
2415 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2416 builder.addCapability(spv::CapabilityGeometryStreams);
2417 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2418 }
2419 if (glslangIntermediate->getXfbMode()) {
2420 builder.addCapability(spv::CapabilityTransformFeedback);
2421 if (type.getQualifier().hasXfbStride())
2422 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2423 if (type.getQualifier().hasXfbBuffer())
2424 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2425 }
2426}
2427
John Kessenich6c292d32016-02-15 20:58:50 -07002428// Turn the expression forming the array size into an id.
2429// This is not quite trivial, because of specialization constants.
2430// Sometimes, a raw constant is turned into an Id, and sometimes
2431// a specialization constant expression is.
2432spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2433{
2434 // First, see if this is sized with a node, meaning a specialization constant:
2435 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2436 if (specNode != nullptr) {
2437 builder.clearAccessChain();
2438 specNode->traverse(this);
2439 return accessChainLoad(specNode->getAsTyped()->getType());
2440 }
qining25262b32016-05-06 17:25:16 -04002441
John Kessenich6c292d32016-02-15 20:58:50 -07002442 // Otherwise, need a compile-time (front end) size, get it:
2443 int size = arraySizes.getDimSize(dim);
2444 assert(size > 0);
2445 return builder.makeUintConstant(size);
2446}
2447
John Kessenich103bef92016-02-08 21:38:15 -07002448// Wrap the builder's accessChainLoad to:
2449// - localize handling of RelaxedPrecision
2450// - use the SPIR-V inferred type instead of another conversion of the glslang type
2451// (avoids unnecessary work and possible type punning for structures)
2452// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002453spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2454{
John Kessenich103bef92016-02-08 21:38:15 -07002455 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2456 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2457
2458 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002459 if (type.getBasicType() == glslang::EbtBool) {
2460 if (builder.isScalarType(nominalTypeId)) {
2461 // Conversion for bool
2462 spv::Id boolType = builder.makeBoolType();
2463 if (nominalTypeId != boolType)
2464 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2465 } else if (builder.isVectorType(nominalTypeId)) {
2466 // Conversion for bvec
2467 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2468 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2469 if (nominalTypeId != bvecType)
2470 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2471 }
2472 }
John Kessenich103bef92016-02-08 21:38:15 -07002473
2474 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002475}
2476
Rex Xu27253232016-02-23 17:51:09 +08002477// Wrap the builder's accessChainStore to:
2478// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002479//
2480// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002481void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2482{
2483 // Need to convert to abstract types when necessary
2484 if (type.getBasicType() == glslang::EbtBool) {
2485 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2486
2487 if (builder.isScalarType(nominalTypeId)) {
2488 // Conversion for bool
2489 spv::Id boolType = builder.makeBoolType();
2490 if (nominalTypeId != boolType) {
2491 spv::Id zero = builder.makeUintConstant(0);
2492 spv::Id one = builder.makeUintConstant(1);
2493 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2494 }
2495 } else if (builder.isVectorType(nominalTypeId)) {
2496 // Conversion for bvec
2497 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2498 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2499 if (nominalTypeId != bvecType) {
2500 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2501 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2502 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2503 }
2504 }
2505 }
2506
2507 builder.accessChainStore(rvalue);
2508}
2509
John Kessenich4bf71552016-09-02 11:20:21 -06002510// For storing when types match at the glslang level, but not might match at the
2511// SPIR-V level.
2512//
2513// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002514// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002515// as in a member-decorated way.
2516//
2517// NOTE: This function can handle any store request; if it's not special it
2518// simplifies to a simple OpStore.
2519//
2520// Implicitly uses the existing builder.accessChain as the storage target.
2521void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2522{
John Kessenichb3e24e42016-09-11 12:33:43 -06002523 // we only do the complex path here if it's an aggregate
2524 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002525 accessChainStore(type, rValue);
2526 return;
2527 }
2528
John Kessenichb3e24e42016-09-11 12:33:43 -06002529 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002530 spv::Id rType = builder.getTypeId(rValue);
2531 spv::Id lValue = builder.accessChainGetLValue();
2532 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2533 if (lType == rType) {
2534 accessChainStore(type, rValue);
2535 return;
2536 }
2537
John Kessenichb3e24e42016-09-11 12:33:43 -06002538 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002539 // where the two types were the same type in GLSL. This requires member
2540 // by member copy, recursively.
2541
John Kessenichb3e24e42016-09-11 12:33:43 -06002542 // If an array, copy element by element.
2543 if (type.isArray()) {
2544 glslang::TType glslangElementType(type, 0);
2545 spv::Id elementRType = builder.getContainedTypeId(rType);
2546 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2547 // get the source member
2548 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002549
John Kessenichb3e24e42016-09-11 12:33:43 -06002550 // set up the target storage
2551 builder.clearAccessChain();
2552 builder.setAccessChainLValue(lValue);
2553 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002554
John Kessenichb3e24e42016-09-11 12:33:43 -06002555 // store the member
2556 multiTypeStore(glslangElementType, elementRValue);
2557 }
2558 } else {
2559 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002560
John Kessenichb3e24e42016-09-11 12:33:43 -06002561 // loop over structure members
2562 const glslang::TTypeList& members = *type.getStruct();
2563 for (int m = 0; m < (int)members.size(); ++m) {
2564 const glslang::TType& glslangMemberType = *members[m].type;
2565
2566 // get the source member
2567 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2568 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2569
2570 // set up the target storage
2571 builder.clearAccessChain();
2572 builder.setAccessChainLValue(lValue);
2573 builder.accessChainPush(builder.makeIntConstant(m));
2574
2575 // store the member
2576 multiTypeStore(glslangMemberType, memberRValue);
2577 }
John Kessenich4bf71552016-09-02 11:20:21 -06002578 }
2579}
2580
John Kessenichf85e8062015-12-19 13:57:10 -07002581// Decide whether or not this type should be
2582// decorated with offsets and strides, and if so
2583// whether std140 or std430 rules should be applied.
2584glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002585{
John Kessenichf85e8062015-12-19 13:57:10 -07002586 // has to be a block
2587 if (type.getBasicType() != glslang::EbtBlock)
2588 return glslang::ElpNone;
2589
2590 // has to be a uniform or buffer block
2591 if (type.getQualifier().storage != glslang::EvqUniform &&
2592 type.getQualifier().storage != glslang::EvqBuffer)
2593 return glslang::ElpNone;
2594
2595 // return the layout to use
2596 switch (type.getQualifier().layoutPacking) {
2597 case glslang::ElpStd140:
2598 case glslang::ElpStd430:
2599 return type.getQualifier().layoutPacking;
2600 default:
2601 return glslang::ElpNone;
2602 }
John Kessenich31ed4832015-09-09 17:51:38 -06002603}
2604
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002605// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002606int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002607{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002608 int size;
John Kessenich49987892015-12-29 17:11:44 -07002609 int stride;
2610 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002611
2612 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002613}
2614
John Kessenich49987892015-12-29 17:11:44 -07002615// 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 -07002616// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002617int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002618{
John Kessenich49987892015-12-29 17:11:44 -07002619 glslang::TType elementType;
2620 elementType.shallowCopy(matrixType);
2621 elementType.clearArraySizes();
2622
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002623 int size;
John Kessenich49987892015-12-29 17:11:44 -07002624 int stride;
2625 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2626
2627 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002628}
2629
John Kessenich5e4b1242015-08-06 22:53:06 -06002630// Given a member type of a struct, realign the current offset for it, and compute
2631// the next (not yet aligned) offset for the next member, which will get aligned
2632// on the next call.
2633// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2634// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2635// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002636void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002637 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002638{
2639 // this will get a positive value when deemed necessary
2640 nextOffset = -1;
2641
John Kessenich5e4b1242015-08-06 22:53:06 -06002642 // override anything in currentOffset with user-set offset
2643 if (memberType.getQualifier().hasOffset())
2644 currentOffset = memberType.getQualifier().layoutOffset;
2645
2646 // It could be that current linker usage in glslang updated all the layoutOffset,
2647 // in which case the following code does not matter. But, that's not quite right
2648 // once cross-compilation unit GLSL validation is done, as the original user
2649 // settings are needed in layoutOffset, and then the following will come into play.
2650
John Kessenichf85e8062015-12-19 13:57:10 -07002651 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002652 if (! memberType.getQualifier().hasOffset())
2653 currentOffset = -1;
2654
2655 return;
2656 }
2657
John Kessenichf85e8062015-12-19 13:57:10 -07002658 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002659 if (currentOffset < 0)
2660 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002661
John Kessenich5e4b1242015-08-06 22:53:06 -06002662 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2663 // but possibly not yet correctly aligned.
2664
2665 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002666 int dummyStride;
2667 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002668 glslang::RoundToPow2(currentOffset, memberAlignment);
2669 nextOffset = currentOffset + memberSize;
2670}
2671
David Netoa901ffe2016-06-08 14:11:40 +01002672void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002673{
David Netoa901ffe2016-06-08 14:11:40 +01002674 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2675 switch (glslangBuiltIn)
2676 {
2677 case glslang::EbvClipDistance:
2678 case glslang::EbvCullDistance:
2679 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002680#ifdef NV_EXTENSIONS
2681 case glslang::EbvLayer:
2682 case glslang::EbvViewportMaskNV:
2683 case glslang::EbvSecondaryPositionNV:
2684 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002685 case glslang::EbvPositionPerViewNV:
2686 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002687#endif
David Netoa901ffe2016-06-08 14:11:40 +01002688 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2689 // Alternately, we could just call this for any glslang built-in, since the
2690 // capability already guards against duplicates.
2691 TranslateBuiltInDecoration(glslangBuiltIn, false);
2692 break;
2693 default:
2694 // Capabilities were already generated when the struct was declared.
2695 break;
2696 }
John Kessenichebb50532016-05-16 19:22:05 -06002697}
2698
John Kessenich6fccb3c2016-09-19 16:01:41 -06002699bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002700{
John Kessenicheee9d532016-09-19 18:09:30 -06002701 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002702}
2703
2704// Make all the functions, skeletally, without actually visiting their bodies.
2705void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2706{
2707 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2708 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002709 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002710 continue;
2711
2712 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002713 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002714 //
qining25262b32016-05-06 17:25:16 -04002715 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002716 // function. What it is an address of varies:
2717 //
John Kessenich4bf71552016-09-02 11:20:21 -06002718 // - "in" parameters not marked as "const" can be written to without modifying the calling
2719 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002720 //
2721 // - "const in" parameters can just be the r-value, as no writes need occur.
2722 //
John Kessenich4bf71552016-09-02 11:20:21 -06002723 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2724 // 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 -06002725
2726 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002727 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002728 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2729
2730 for (int p = 0; p < (int)parameters.size(); ++p) {
2731 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2732 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich4a57dce2017-02-24 19:15:46 -07002733 if (paramType.containsOpaque())
Jason Ekstranded15ef12016-06-08 13:54:48 -07002734 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2735 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002736 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2737 else
John Kessenich4bf71552016-09-02 11:20:21 -06002738 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002739 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002740 paramTypes.push_back(typeId);
2741 }
2742
2743 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002744 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2745 convertGlslangToSpvType(glslFunction->getType()),
2746 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002747
2748 // Track function to emit/call later
2749 functionMap[glslFunction->getName().c_str()] = function;
2750
2751 // Set the parameter id's
2752 for (int p = 0; p < (int)parameters.size(); ++p) {
2753 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2754 // give a name too
2755 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2756 }
2757 }
2758}
2759
2760// Process all the initializers, while skipping the functions and link objects
2761void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2762{
2763 builder.setBuildPoint(shaderEntry->getLastBlock());
2764 for (int i = 0; i < (int)initializers.size(); ++i) {
2765 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2766 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2767
2768 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002769 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002770 initializer->traverse(this);
2771 }
2772 }
2773}
2774
2775// Process all the functions, while skipping initializers.
2776void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2777{
2778 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2779 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002780 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002781 node->traverse(this);
2782 }
2783}
2784
2785void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2786{
qining25262b32016-05-06 17:25:16 -04002787 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002788 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002789 currentFunction = functionMap[node->getName().c_str()];
2790 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002791 builder.setBuildPoint(functionBlock);
2792}
2793
Rex Xu04db3f52015-09-16 11:44:02 +08002794void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002795{
Rex Xufc618912015-09-09 16:42:49 +08002796 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002797
2798 glslang::TSampler sampler = {};
2799 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002800 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002801 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2802 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2803 }
2804
John Kessenich140f3df2015-06-26 16:58:36 -06002805 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2806 builder.clearAccessChain();
2807 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002808
2809 // Special case l-value operands
2810 bool lvalue = false;
2811 switch (node.getOp()) {
2812 case glslang::EOpImageAtomicAdd:
2813 case glslang::EOpImageAtomicMin:
2814 case glslang::EOpImageAtomicMax:
2815 case glslang::EOpImageAtomicAnd:
2816 case glslang::EOpImageAtomicOr:
2817 case glslang::EOpImageAtomicXor:
2818 case glslang::EOpImageAtomicExchange:
2819 case glslang::EOpImageAtomicCompSwap:
2820 if (i == 0)
2821 lvalue = true;
2822 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002823 case glslang::EOpSparseImageLoad:
2824 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2825 lvalue = true;
2826 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002827 case glslang::EOpSparseTexture:
2828 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2829 lvalue = true;
2830 break;
2831 case glslang::EOpSparseTextureClamp:
2832 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2833 lvalue = true;
2834 break;
2835 case glslang::EOpSparseTextureLod:
2836 case glslang::EOpSparseTextureOffset:
2837 if (i == 3)
2838 lvalue = true;
2839 break;
2840 case glslang::EOpSparseTextureFetch:
2841 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2842 lvalue = true;
2843 break;
2844 case glslang::EOpSparseTextureFetchOffset:
2845 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2846 lvalue = true;
2847 break;
2848 case glslang::EOpSparseTextureLodOffset:
2849 case glslang::EOpSparseTextureGrad:
2850 case glslang::EOpSparseTextureOffsetClamp:
2851 if (i == 4)
2852 lvalue = true;
2853 break;
2854 case glslang::EOpSparseTextureGradOffset:
2855 case glslang::EOpSparseTextureGradClamp:
2856 if (i == 5)
2857 lvalue = true;
2858 break;
2859 case glslang::EOpSparseTextureGradOffsetClamp:
2860 if (i == 6)
2861 lvalue = true;
2862 break;
2863 case glslang::EOpSparseTextureGather:
2864 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2865 lvalue = true;
2866 break;
2867 case glslang::EOpSparseTextureGatherOffset:
2868 case glslang::EOpSparseTextureGatherOffsets:
2869 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2870 lvalue = true;
2871 break;
Rex Xufc618912015-09-09 16:42:49 +08002872 default:
2873 break;
2874 }
2875
Rex Xu6b86d492015-09-16 17:48:22 +08002876 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002877 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002878 else
John Kessenich32cfd492016-02-02 12:37:46 -07002879 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002880 }
2881}
2882
John Kessenichfc51d282015-08-19 13:34:18 -06002883void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002884{
John Kessenichfc51d282015-08-19 13:34:18 -06002885 builder.clearAccessChain();
2886 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002887 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002888}
John Kessenich140f3df2015-06-26 16:58:36 -06002889
John Kessenichfc51d282015-08-19 13:34:18 -06002890spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2891{
Rex Xufc618912015-09-09 16:42:49 +08002892 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002893 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002894 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002895 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002896
John Kessenichfc51d282015-08-19 13:34:18 -06002897 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002898 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2899 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2900 std::vector<spv::Id> arguments;
2901 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002902 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002903 else
2904 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002905 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002906
2907 spv::Builder::TextureParameters params = { };
2908 params.sampler = arguments[0];
2909
Rex Xu04db3f52015-09-16 11:44:02 +08002910 glslang::TCrackedTextureOp cracked;
2911 node->crackTexture(sampler, cracked);
2912
John Kessenichfc51d282015-08-19 13:34:18 -06002913 // Check for queries
2914 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002915 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2916 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002917 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002918
John Kessenichfc51d282015-08-19 13:34:18 -06002919 switch (node->getOp()) {
2920 case glslang::EOpImageQuerySize:
2921 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002922 if (arguments.size() > 1) {
2923 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002925 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002926 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002927 case glslang::EOpImageQuerySamples:
2928 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002929 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002930 case glslang::EOpTextureQueryLod:
2931 params.coords = arguments[1];
2932 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2933 case glslang::EOpTextureQueryLevels:
2934 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002935 case glslang::EOpSparseTexelsResident:
2936 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002937 default:
2938 assert(0);
2939 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002940 }
John Kessenich140f3df2015-06-26 16:58:36 -06002941 }
2942
Rex Xufc618912015-09-09 16:42:49 +08002943 // Check for image functions other than queries
2944 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002945 std::vector<spv::Id> operands;
2946 auto opIt = arguments.begin();
2947 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002948
2949 // Handle subpass operations
2950 // TODO: GLSL should change to have the "MS" only on the type rather than the
2951 // built-in function.
2952 if (cracked.subpass) {
2953 // add on the (0,0) coordinate
2954 spv::Id zero = builder.makeIntConstant(0);
2955 std::vector<spv::Id> comps;
2956 comps.push_back(zero);
2957 comps.push_back(zero);
2958 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2959 if (sampler.ms) {
2960 operands.push_back(spv::ImageOperandsSampleMask);
2961 operands.push_back(*(opIt++));
2962 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002963 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07002964 }
2965
John Kessenich56bab042015-09-16 10:54:31 -06002966 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002967 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002968 if (sampler.ms) {
2969 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002970 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002971 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002972 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2973 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06002974 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002975 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002976 if (sampler.ms) {
2977 operands.push_back(*(opIt + 1));
2978 operands.push_back(spv::ImageOperandsSampleMask);
2979 operands.push_back(*opIt);
2980 } else
2981 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002982 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002983 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2984 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002985 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002986 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2987 builder.addCapability(spv::CapabilitySparseResidency);
2988 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2989 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2990
2991 if (sampler.ms) {
2992 operands.push_back(spv::ImageOperandsSampleMask);
2993 operands.push_back(*opIt++);
2994 }
2995
2996 // Create the return type that was a special structure
2997 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06002998 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08002999 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3000 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3001
3002 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3003
3004 // Decode the return type
3005 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3006 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003007 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003008 // Process image atomic operations
3009
3010 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3011 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003012 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003013
John Kessenich8c8505c2016-07-26 12:50:38 -06003014 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003015 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003016
3017 std::vector<spv::Id> operands;
3018 operands.push_back(pointer);
3019 for (; opIt != arguments.end(); ++opIt)
3020 operands.push_back(*opIt);
3021
John Kessenich8c8505c2016-07-26 12:50:38 -06003022 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003023 }
3024 }
3025
3026 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003027 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003028 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3029
John Kessenichfc51d282015-08-19 13:34:18 -06003030 // check for bias argument
3031 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003032 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003033 int nonBiasArgCount = 2;
3034 if (cracked.offset)
3035 ++nonBiasArgCount;
3036 if (cracked.grad)
3037 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003038 if (cracked.lodClamp)
3039 ++nonBiasArgCount;
3040 if (sparse)
3041 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003042
3043 if ((int)arguments.size() > nonBiasArgCount)
3044 bias = true;
3045 }
3046
John Kessenicha5c33d62016-06-02 23:45:21 -06003047 // See if the sampler param should really be just the SPV image part
3048 if (cracked.fetch) {
3049 // a fetch needs to have the image extracted first
3050 if (builder.isSampledImage(params.sampler))
3051 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3052 }
3053
John Kessenichfc51d282015-08-19 13:34:18 -06003054 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003055
John Kessenichfc51d282015-08-19 13:34:18 -06003056 params.coords = arguments[1];
3057 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003058 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003059
3060 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003061 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003062 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003063 ++extraArgs;
3064 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003065 params.Dref = arguments[2];
3066 ++extraArgs;
3067 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003068 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003069 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003070 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003071 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003072 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003073 dRefComp = builder.getNumComponents(params.coords) - 1;
3074 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003075 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3076 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003077
3078 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003079 if (cracked.lod) {
3080 params.lod = arguments[2];
3081 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003082 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3083 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3084 noImplicitLod = true;
3085 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003086
3087 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003088 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003089 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003090 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003091 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003092
3093 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003094 if (cracked.grad) {
3095 params.gradX = arguments[2 + extraArgs];
3096 params.gradY = arguments[3 + extraArgs];
3097 extraArgs += 2;
3098 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003099
3100 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003101 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003102 params.offset = arguments[2 + extraArgs];
3103 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003104 } else if (cracked.offsets) {
3105 params.offsets = arguments[2 + extraArgs];
3106 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003107 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003108
3109 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003110 if (cracked.lodClamp) {
3111 params.lodClamp = arguments[2 + extraArgs];
3112 ++extraArgs;
3113 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003114
3115 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003116 if (sparse) {
3117 params.texelOut = arguments[2 + extraArgs];
3118 ++extraArgs;
3119 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003120
3121 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003122 if (bias) {
3123 params.bias = arguments[2 + extraArgs];
3124 ++extraArgs;
3125 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003126
3127 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003128 if (cracked.gather && ! sampler.shadow) {
3129 // default component is 0, if missing, otherwise an argument
3130 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003131 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003132 ++extraArgs;
3133 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003134 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003135 }
3136 }
John Kessenichfc51d282015-08-19 13:34:18 -06003137
John Kessenich65336482016-06-16 14:06:26 -06003138 // projective component (might not to move)
3139 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3140 // are divided by the last component of P."
3141 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3142 // unused components will appear after all used components."
3143 if (cracked.proj) {
3144 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3145 int projTargetComp;
3146 switch (sampler.dim) {
3147 case glslang::Esd1D: projTargetComp = 1; break;
3148 case glslang::Esd2D: projTargetComp = 2; break;
3149 case glslang::EsdRect: projTargetComp = 2; break;
3150 default: projTargetComp = projSourceComp; break;
3151 }
3152 // copy the projective coordinate if we have to
3153 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003154 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003155 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3156 projSourceComp);
3157 params.coords = builder.createCompositeInsert(projComp, params.coords,
3158 builder.getTypeId(params.coords), projTargetComp);
3159 }
3160 }
3161
John Kessenich8c8505c2016-07-26 12:50:38 -06003162 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003163}
3164
3165spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3166{
3167 // Grab the function's pointer from the previously created function
3168 spv::Function* function = functionMap[node->getName().c_str()];
3169 if (! function)
3170 return 0;
3171
3172 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3173 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3174
3175 // See comments in makeFunctions() for details about the semantics for parameter passing.
3176 //
3177 // These imply we need a four step process:
3178 // 1. Evaluate the arguments
3179 // 2. Allocate and make copies of in, out, and inout arguments
3180 // 3. Make the call
3181 // 4. Copy back the results
3182
3183 // 1. Evaluate the arguments
3184 std::vector<spv::Builder::AccessChain> lValues;
3185 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003186 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003187 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003188 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003189 // build l-value
3190 builder.clearAccessChain();
3191 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003192 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003193 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003194 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003195 // save l-value
3196 lValues.push_back(builder.getAccessChain());
3197 } else {
3198 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003199 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003200 }
3201 }
3202
3203 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3204 // copy the original into that space.
3205 //
3206 // Also, build up the list of actual arguments to pass in for the call
3207 int lValueCount = 0;
3208 int rValueCount = 0;
3209 std::vector<spv::Id> spvArgs;
3210 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003211 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003212 spv::Id arg;
John Kessenich4a57dce2017-02-24 19:15:46 -07003213 if (paramType.containsOpaque()) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003214 builder.setAccessChain(lValues[lValueCount]);
3215 arg = builder.accessChainGetLValue();
3216 ++lValueCount;
3217 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003218 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003219 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3220 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3221 // need to copy the input into output space
3222 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003223 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003224 builder.clearAccessChain();
3225 builder.setAccessChainLValue(arg);
3226 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003227 }
3228 ++lValueCount;
3229 } else {
3230 arg = rValues[rValueCount];
3231 ++rValueCount;
3232 }
3233 spvArgs.push_back(arg);
3234 }
3235
3236 // 3. Make the call.
3237 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003238 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003239
3240 // 4. Copy back out an "out" arguments.
3241 lValueCount = 0;
3242 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003243 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003244 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3245 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3246 spv::Id copy = builder.createLoad(spvArgs[a]);
3247 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003248 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 }
3250 ++lValueCount;
3251 }
3252 }
3253
3254 return result;
3255}
3256
3257// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003258spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3259 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003260 spv::Id typeId, spv::Id left, spv::Id right,
3261 glslang::TBasicType typeProxy, bool reduceComparison)
3262{
Rex Xu8ff43de2016-04-22 16:51:45 +08003263 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003264#ifdef AMD_EXTENSIONS
3265 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3266#else
John Kessenich140f3df2015-06-26 16:58:36 -06003267 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003268#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003269 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003270
3271 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003272 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003273 bool comparison = false;
3274
3275 switch (op) {
3276 case glslang::EOpAdd:
3277 case glslang::EOpAddAssign:
3278 if (isFloat)
3279 binOp = spv::OpFAdd;
3280 else
3281 binOp = spv::OpIAdd;
3282 break;
3283 case glslang::EOpSub:
3284 case glslang::EOpSubAssign:
3285 if (isFloat)
3286 binOp = spv::OpFSub;
3287 else
3288 binOp = spv::OpISub;
3289 break;
3290 case glslang::EOpMul:
3291 case glslang::EOpMulAssign:
3292 if (isFloat)
3293 binOp = spv::OpFMul;
3294 else
3295 binOp = spv::OpIMul;
3296 break;
3297 case glslang::EOpVectorTimesScalar:
3298 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003299 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003300 if (builder.isVector(right))
3301 std::swap(left, right);
3302 assert(builder.isScalar(right));
3303 needMatchingVectors = false;
3304 binOp = spv::OpVectorTimesScalar;
3305 } else
3306 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003307 break;
3308 case glslang::EOpVectorTimesMatrix:
3309 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003310 binOp = spv::OpVectorTimesMatrix;
3311 break;
3312 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003313 binOp = spv::OpMatrixTimesVector;
3314 break;
3315 case glslang::EOpMatrixTimesScalar:
3316 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003317 binOp = spv::OpMatrixTimesScalar;
3318 break;
3319 case glslang::EOpMatrixTimesMatrix:
3320 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003321 binOp = spv::OpMatrixTimesMatrix;
3322 break;
3323 case glslang::EOpOuterProduct:
3324 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003325 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003326 break;
3327
3328 case glslang::EOpDiv:
3329 case glslang::EOpDivAssign:
3330 if (isFloat)
3331 binOp = spv::OpFDiv;
3332 else if (isUnsigned)
3333 binOp = spv::OpUDiv;
3334 else
3335 binOp = spv::OpSDiv;
3336 break;
3337 case glslang::EOpMod:
3338 case glslang::EOpModAssign:
3339 if (isFloat)
3340 binOp = spv::OpFMod;
3341 else if (isUnsigned)
3342 binOp = spv::OpUMod;
3343 else
3344 binOp = spv::OpSMod;
3345 break;
3346 case glslang::EOpRightShift:
3347 case glslang::EOpRightShiftAssign:
3348 if (isUnsigned)
3349 binOp = spv::OpShiftRightLogical;
3350 else
3351 binOp = spv::OpShiftRightArithmetic;
3352 break;
3353 case glslang::EOpLeftShift:
3354 case glslang::EOpLeftShiftAssign:
3355 binOp = spv::OpShiftLeftLogical;
3356 break;
3357 case glslang::EOpAnd:
3358 case glslang::EOpAndAssign:
3359 binOp = spv::OpBitwiseAnd;
3360 break;
3361 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003362 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003363 binOp = spv::OpLogicalAnd;
3364 break;
3365 case glslang::EOpInclusiveOr:
3366 case glslang::EOpInclusiveOrAssign:
3367 binOp = spv::OpBitwiseOr;
3368 break;
3369 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003370 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003371 binOp = spv::OpLogicalOr;
3372 break;
3373 case glslang::EOpExclusiveOr:
3374 case glslang::EOpExclusiveOrAssign:
3375 binOp = spv::OpBitwiseXor;
3376 break;
3377 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003378 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003379 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003380 break;
3381
3382 case glslang::EOpLessThan:
3383 case glslang::EOpGreaterThan:
3384 case glslang::EOpLessThanEqual:
3385 case glslang::EOpGreaterThanEqual:
3386 case glslang::EOpEqual:
3387 case glslang::EOpNotEqual:
3388 case glslang::EOpVectorEqual:
3389 case glslang::EOpVectorNotEqual:
3390 comparison = true;
3391 break;
3392 default:
3393 break;
3394 }
3395
John Kessenich7c1aa102015-10-15 13:29:11 -06003396 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003397 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003398 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003399 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003400 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003401
3402 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003403 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003404 builder.promoteScalar(precision, left, right);
3405
qining25262b32016-05-06 17:25:16 -04003406 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3407 addDecoration(result, noContraction);
3408 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003409 }
3410
3411 if (! comparison)
3412 return 0;
3413
John Kessenich7c1aa102015-10-15 13:29:11 -06003414 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003415
John Kessenich4583b612016-08-07 19:14:22 -06003416 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3417 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003418 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003419
3420 switch (op) {
3421 case glslang::EOpLessThan:
3422 if (isFloat)
3423 binOp = spv::OpFOrdLessThan;
3424 else if (isUnsigned)
3425 binOp = spv::OpULessThan;
3426 else
3427 binOp = spv::OpSLessThan;
3428 break;
3429 case glslang::EOpGreaterThan:
3430 if (isFloat)
3431 binOp = spv::OpFOrdGreaterThan;
3432 else if (isUnsigned)
3433 binOp = spv::OpUGreaterThan;
3434 else
3435 binOp = spv::OpSGreaterThan;
3436 break;
3437 case glslang::EOpLessThanEqual:
3438 if (isFloat)
3439 binOp = spv::OpFOrdLessThanEqual;
3440 else if (isUnsigned)
3441 binOp = spv::OpULessThanEqual;
3442 else
3443 binOp = spv::OpSLessThanEqual;
3444 break;
3445 case glslang::EOpGreaterThanEqual:
3446 if (isFloat)
3447 binOp = spv::OpFOrdGreaterThanEqual;
3448 else if (isUnsigned)
3449 binOp = spv::OpUGreaterThanEqual;
3450 else
3451 binOp = spv::OpSGreaterThanEqual;
3452 break;
3453 case glslang::EOpEqual:
3454 case glslang::EOpVectorEqual:
3455 if (isFloat)
3456 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003457 else if (isBool)
3458 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003459 else
3460 binOp = spv::OpIEqual;
3461 break;
3462 case glslang::EOpNotEqual:
3463 case glslang::EOpVectorNotEqual:
3464 if (isFloat)
3465 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003466 else if (isBool)
3467 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003468 else
3469 binOp = spv::OpINotEqual;
3470 break;
3471 default:
3472 break;
3473 }
3474
qining25262b32016-05-06 17:25:16 -04003475 if (binOp != spv::OpNop) {
3476 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3477 addDecoration(result, noContraction);
3478 return builder.setPrecision(result, precision);
3479 }
John Kessenich140f3df2015-06-26 16:58:36 -06003480
3481 return 0;
3482}
3483
John Kessenich04bb8a02015-12-12 12:28:14 -07003484//
3485// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3486// These can be any of:
3487//
3488// matrix * scalar
3489// scalar * matrix
3490// matrix * matrix linear algebraic
3491// matrix * vector
3492// vector * matrix
3493// matrix * matrix componentwise
3494// matrix op matrix op in {+, -, /}
3495// matrix op scalar op in {+, -, /}
3496// scalar op matrix op in {+, -, /}
3497//
qining25262b32016-05-06 17:25:16 -04003498spv::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 -07003499{
3500 bool firstClass = true;
3501
3502 // First, handle first-class matrix operations (* and matrix/scalar)
3503 switch (op) {
3504 case spv::OpFDiv:
3505 if (builder.isMatrix(left) && builder.isScalar(right)) {
3506 // turn matrix / scalar into a multiply...
3507 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3508 op = spv::OpMatrixTimesScalar;
3509 } else
3510 firstClass = false;
3511 break;
3512 case spv::OpMatrixTimesScalar:
3513 if (builder.isMatrix(right))
3514 std::swap(left, right);
3515 assert(builder.isScalar(right));
3516 break;
3517 case spv::OpVectorTimesMatrix:
3518 assert(builder.isVector(left));
3519 assert(builder.isMatrix(right));
3520 break;
3521 case spv::OpMatrixTimesVector:
3522 assert(builder.isMatrix(left));
3523 assert(builder.isVector(right));
3524 break;
3525 case spv::OpMatrixTimesMatrix:
3526 assert(builder.isMatrix(left));
3527 assert(builder.isMatrix(right));
3528 break;
3529 default:
3530 firstClass = false;
3531 break;
3532 }
3533
qining25262b32016-05-06 17:25:16 -04003534 if (firstClass) {
3535 spv::Id result = builder.createBinOp(op, typeId, left, right);
3536 addDecoration(result, noContraction);
3537 return builder.setPrecision(result, precision);
3538 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003539
LoopDawg592860c2016-06-09 08:57:35 -06003540 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003541 // The result type of all of them is the same type as the (a) matrix operand.
3542 // The algorithm is to:
3543 // - break the matrix(es) into vectors
3544 // - smear any scalar to a vector
3545 // - do vector operations
3546 // - make a matrix out the vector results
3547 switch (op) {
3548 case spv::OpFAdd:
3549 case spv::OpFSub:
3550 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003551 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003552 case spv::OpFMul:
3553 {
3554 // one time set up...
3555 bool leftMat = builder.isMatrix(left);
3556 bool rightMat = builder.isMatrix(right);
3557 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3558 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3559 spv::Id scalarType = builder.getScalarTypeId(typeId);
3560 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3561 std::vector<spv::Id> results;
3562 spv::Id smearVec = spv::NoResult;
3563 if (builder.isScalar(left))
3564 smearVec = builder.smearScalar(precision, left, vecType);
3565 else if (builder.isScalar(right))
3566 smearVec = builder.smearScalar(precision, right, vecType);
3567
3568 // do each vector op
3569 for (unsigned int c = 0; c < numCols; ++c) {
3570 std::vector<unsigned int> indexes;
3571 indexes.push_back(c);
3572 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3573 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003574 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3575 addDecoration(result, noContraction);
3576 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003577 }
3578
3579 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003580 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003581 }
3582 default:
3583 assert(0);
3584 return spv::NoResult;
3585 }
3586}
3587
qining25262b32016-05-06 17:25:16 -04003588spv::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 -06003589{
3590 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003591 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003592 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003593 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003594#ifdef AMD_EXTENSIONS
3595 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3596#else
Rex Xu04db3f52015-09-16 11:44:02 +08003597 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003598#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003599
3600 switch (op) {
3601 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003602 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003603 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003604 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003605 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003606 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003607 unaryOp = spv::OpSNegate;
3608 break;
3609
3610 case glslang::EOpLogicalNot:
3611 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003612 unaryOp = spv::OpLogicalNot;
3613 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003614 case glslang::EOpBitwiseNot:
3615 unaryOp = spv::OpNot;
3616 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003617
John Kessenich140f3df2015-06-26 16:58:36 -06003618 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003619 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003620 break;
3621 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003622 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003623 break;
3624 case glslang::EOpTranspose:
3625 unaryOp = spv::OpTranspose;
3626 break;
3627
3628 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003630 break;
3631 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003632 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003633 break;
3634 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003635 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003636 break;
3637 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003638 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003639 break;
3640 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003641 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003642 break;
3643 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003644 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003645 break;
3646 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003647 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003648 break;
3649 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003650 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003651 break;
3652
3653 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003654 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003655 break;
3656 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003657 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003658 break;
3659 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003660 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003661 break;
3662 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003663 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003664 break;
3665 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003666 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003667 break;
3668 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003669 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003670 break;
3671
3672 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003673 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003674 break;
3675 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003677 break;
3678
3679 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003680 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003681 break;
3682 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003683 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003684 break;
3685 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003686 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003689 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003690 break;
3691 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003692 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003693 break;
3694 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003695 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003696 break;
3697
3698 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003708 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003711 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003712 break;
3713 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003714 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003715 break;
3716
3717 case glslang::EOpIsNan:
3718 unaryOp = spv::OpIsNan;
3719 break;
3720 case glslang::EOpIsInf:
3721 unaryOp = spv::OpIsInf;
3722 break;
LoopDawg592860c2016-06-09 08:57:35 -06003723 case glslang::EOpIsFinite:
3724 unaryOp = spv::OpIsFinite;
3725 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003726
Rex Xucbc426e2015-12-15 16:03:10 +08003727 case glslang::EOpFloatBitsToInt:
3728 case glslang::EOpFloatBitsToUint:
3729 case glslang::EOpIntBitsToFloat:
3730 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003731 case glslang::EOpDoubleBitsToInt64:
3732 case glslang::EOpDoubleBitsToUint64:
3733 case glslang::EOpInt64BitsToDouble:
3734 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003735 unaryOp = spv::OpBitcast;
3736 break;
3737
John Kessenich140f3df2015-06-26 16:58:36 -06003738 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003739 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003740 break;
3741 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003742 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003743 break;
3744 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003745 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 break;
3747 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003748 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003756 case glslang::EOpPackSnorm4x8:
3757 libCall = spv::GLSLstd450PackSnorm4x8;
3758 break;
3759 case glslang::EOpUnpackSnorm4x8:
3760 libCall = spv::GLSLstd450UnpackSnorm4x8;
3761 break;
3762 case glslang::EOpPackUnorm4x8:
3763 libCall = spv::GLSLstd450PackUnorm4x8;
3764 break;
3765 case glslang::EOpUnpackUnorm4x8:
3766 libCall = spv::GLSLstd450UnpackUnorm4x8;
3767 break;
3768 case glslang::EOpPackDouble2x32:
3769 libCall = spv::GLSLstd450PackDouble2x32;
3770 break;
3771 case glslang::EOpUnpackDouble2x32:
3772 libCall = spv::GLSLstd450UnpackDouble2x32;
3773 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003774
Rex Xu8ff43de2016-04-22 16:51:45 +08003775 case glslang::EOpPackInt2x32:
3776 case glslang::EOpUnpackInt2x32:
3777 case glslang::EOpPackUint2x32:
3778 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003779 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003780 break;
3781
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003782#ifdef AMD_EXTENSIONS
3783 case glslang::EOpPackFloat2x16:
3784 case glslang::EOpUnpackFloat2x16:
3785 unaryOp = spv::OpBitcast;
3786 break;
3787#endif
3788
John Kessenich140f3df2015-06-26 16:58:36 -06003789 case glslang::EOpDPdx:
3790 unaryOp = spv::OpDPdx;
3791 break;
3792 case glslang::EOpDPdy:
3793 unaryOp = spv::OpDPdy;
3794 break;
3795 case glslang::EOpFwidth:
3796 unaryOp = spv::OpFwidth;
3797 break;
3798 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003799 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003800 unaryOp = spv::OpDPdxFine;
3801 break;
3802 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003803 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003804 unaryOp = spv::OpDPdyFine;
3805 break;
3806 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003807 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003808 unaryOp = spv::OpFwidthFine;
3809 break;
3810 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003811 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003812 unaryOp = spv::OpDPdxCoarse;
3813 break;
3814 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003815 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003816 unaryOp = spv::OpDPdyCoarse;
3817 break;
3818 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003819 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003820 unaryOp = spv::OpFwidthCoarse;
3821 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003822 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003823 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003824 libCall = spv::GLSLstd450InterpolateAtCentroid;
3825 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003826 case glslang::EOpAny:
3827 unaryOp = spv::OpAny;
3828 break;
3829 case glslang::EOpAll:
3830 unaryOp = spv::OpAll;
3831 break;
3832
3833 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003834 if (isFloat)
3835 libCall = spv::GLSLstd450FAbs;
3836 else
3837 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003838 break;
3839 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003840 if (isFloat)
3841 libCall = spv::GLSLstd450FSign;
3842 else
3843 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845
John Kessenichfc51d282015-08-19 13:34:18 -06003846 case glslang::EOpAtomicCounterIncrement:
3847 case glslang::EOpAtomicCounterDecrement:
3848 case glslang::EOpAtomicCounter:
3849 {
3850 // Handle all of the atomics in one place, in createAtomicOperation()
3851 std::vector<spv::Id> operands;
3852 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003853 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003854 }
3855
John Kessenichfc51d282015-08-19 13:34:18 -06003856 case glslang::EOpBitFieldReverse:
3857 unaryOp = spv::OpBitReverse;
3858 break;
3859 case glslang::EOpBitCount:
3860 unaryOp = spv::OpBitCount;
3861 break;
3862 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003863 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003864 break;
3865 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003866 if (isUnsigned)
3867 libCall = spv::GLSLstd450FindUMsb;
3868 else
3869 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003870 break;
3871
Rex Xu574ab042016-04-14 16:53:07 +08003872 case glslang::EOpBallot:
3873 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003874 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003875 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003876 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003877#ifdef AMD_EXTENSIONS
3878 case glslang::EOpMinInvocations:
3879 case glslang::EOpMaxInvocations:
3880 case glslang::EOpAddInvocations:
3881 case glslang::EOpMinInvocationsNonUniform:
3882 case glslang::EOpMaxInvocationsNonUniform:
3883 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003884 case glslang::EOpMinInvocationsInclusiveScan:
3885 case glslang::EOpMaxInvocationsInclusiveScan:
3886 case glslang::EOpAddInvocationsInclusiveScan:
3887 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3888 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3889 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3890 case glslang::EOpMinInvocationsExclusiveScan:
3891 case glslang::EOpMaxInvocationsExclusiveScan:
3892 case glslang::EOpAddInvocationsExclusiveScan:
3893 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3894 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3895 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003896#endif
Rex Xu51596642016-09-21 18:56:12 +08003897 {
3898 std::vector<spv::Id> operands;
3899 operands.push_back(operand);
3900 return createInvocationsOperation(op, typeId, operands, typeProxy);
3901 }
Rex Xu9d93a232016-05-05 12:30:44 +08003902
3903#ifdef AMD_EXTENSIONS
3904 case glslang::EOpMbcnt:
3905 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3906 libCall = spv::MbcntAMD;
3907 break;
3908
3909 case glslang::EOpCubeFaceIndex:
3910 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3911 libCall = spv::CubeFaceIndexAMD;
3912 break;
3913
3914 case glslang::EOpCubeFaceCoord:
3915 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3916 libCall = spv::CubeFaceCoordAMD;
3917 break;
3918#endif
Rex Xu338b1852016-05-05 20:38:33 +08003919
John Kessenich140f3df2015-06-26 16:58:36 -06003920 default:
3921 return 0;
3922 }
3923
3924 spv::Id id;
3925 if (libCall >= 0) {
3926 std::vector<spv::Id> args;
3927 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003928 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003929 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003930 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003931 }
John Kessenich140f3df2015-06-26 16:58:36 -06003932
qining25262b32016-05-06 17:25:16 -04003933 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003934 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003935}
3936
John Kessenich7a53f762016-01-20 11:19:27 -07003937// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003938spv::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 -07003939{
3940 // Handle unary operations vector by vector.
3941 // The result type is the same type as the original type.
3942 // The algorithm is to:
3943 // - break the matrix into vectors
3944 // - apply the operation to each vector
3945 // - make a matrix out the vector results
3946
3947 // get the types sorted out
3948 int numCols = builder.getNumColumns(operand);
3949 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08003950 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
3951 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07003952 std::vector<spv::Id> results;
3953
3954 // do each vector op
3955 for (int c = 0; c < numCols; ++c) {
3956 std::vector<unsigned int> indexes;
3957 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08003958 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
3959 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
3960 addDecoration(destVec, noContraction);
3961 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07003962 }
3963
3964 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003965 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003966}
3967
Rex Xu73e3ce72016-04-27 18:48:17 +08003968spv::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 -06003969{
3970 spv::Op convOp = spv::OpNop;
3971 spv::Id zero = 0;
3972 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003973 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003974
3975 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3976
3977 switch (op) {
3978 case glslang::EOpConvIntToBool:
3979 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003980 case glslang::EOpConvInt64ToBool:
3981 case glslang::EOpConvUint64ToBool:
3982 zero = (op == glslang::EOpConvInt64ToBool ||
3983 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003984 zero = makeSmearedConstant(zero, vectorSize);
3985 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3986
3987 case glslang::EOpConvFloatToBool:
3988 zero = builder.makeFloatConstant(0.0F);
3989 zero = makeSmearedConstant(zero, vectorSize);
3990 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3991
3992 case glslang::EOpConvDoubleToBool:
3993 zero = builder.makeDoubleConstant(0.0);
3994 zero = makeSmearedConstant(zero, vectorSize);
3995 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3996
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003997#ifdef AMD_EXTENSIONS
3998 case glslang::EOpConvFloat16ToBool:
3999 zero = builder.makeFloat16Constant(0.0F);
4000 zero = makeSmearedConstant(zero, vectorSize);
4001 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4002#endif
4003
John Kessenich140f3df2015-06-26 16:58:36 -06004004 case glslang::EOpConvBoolToFloat:
4005 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004006 zero = builder.makeFloatConstant(0.0F);
4007 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004008 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004009
John Kessenich140f3df2015-06-26 16:58:36 -06004010 case glslang::EOpConvBoolToDouble:
4011 convOp = spv::OpSelect;
4012 zero = builder.makeDoubleConstant(0.0);
4013 one = builder.makeDoubleConstant(1.0);
4014 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004015
4016#ifdef AMD_EXTENSIONS
4017 case glslang::EOpConvBoolToFloat16:
4018 convOp = spv::OpSelect;
4019 zero = builder.makeFloat16Constant(0.0F);
4020 one = builder.makeFloat16Constant(1.0F);
4021 break;
4022#endif
4023
John Kessenich140f3df2015-06-26 16:58:36 -06004024 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004025 case glslang::EOpConvBoolToInt64:
4026 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4027 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004028 convOp = spv::OpSelect;
4029 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004030
John Kessenich140f3df2015-06-26 16:58:36 -06004031 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004032 case glslang::EOpConvBoolToUint64:
4033 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4034 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004035 convOp = spv::OpSelect;
4036 break;
4037
4038 case glslang::EOpConvIntToFloat:
4039 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004040 case glslang::EOpConvInt64ToFloat:
4041 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004042#ifdef AMD_EXTENSIONS
4043 case glslang::EOpConvIntToFloat16:
4044 case glslang::EOpConvInt64ToFloat16:
4045#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004046 convOp = spv::OpConvertSToF;
4047 break;
4048
4049 case glslang::EOpConvUintToFloat:
4050 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004051 case glslang::EOpConvUint64ToFloat:
4052 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004053#ifdef AMD_EXTENSIONS
4054 case glslang::EOpConvUintToFloat16:
4055 case glslang::EOpConvUint64ToFloat16:
4056#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004057 convOp = spv::OpConvertUToF;
4058 break;
4059
4060 case glslang::EOpConvDoubleToFloat:
4061 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004062#ifdef AMD_EXTENSIONS
4063 case glslang::EOpConvDoubleToFloat16:
4064 case glslang::EOpConvFloat16ToDouble:
4065 case glslang::EOpConvFloatToFloat16:
4066 case glslang::EOpConvFloat16ToFloat:
4067#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004068 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004069 if (builder.isMatrixType(destType))
4070 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004071 break;
4072
4073 case glslang::EOpConvFloatToInt:
4074 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004075 case glslang::EOpConvFloatToInt64:
4076 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004077#ifdef AMD_EXTENSIONS
4078 case glslang::EOpConvFloat16ToInt:
4079 case glslang::EOpConvFloat16ToInt64:
4080#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004081 convOp = spv::OpConvertFToS;
4082 break;
4083
4084 case glslang::EOpConvUintToInt:
4085 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004086 case glslang::EOpConvUint64ToInt64:
4087 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004088 if (builder.isInSpecConstCodeGenMode()) {
4089 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004090 zero = (op == glslang::EOpConvUint64ToInt64 ||
4091 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004092 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004093 // Use OpIAdd, instead of OpBitcast to do the conversion when
4094 // generating for OpSpecConstantOp instruction.
4095 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4096 }
4097 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004098 convOp = spv::OpBitcast;
4099 break;
4100
4101 case glslang::EOpConvFloatToUint:
4102 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004103 case glslang::EOpConvFloatToUint64:
4104 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004105#ifdef AMD_EXTENSIONS
4106 case glslang::EOpConvFloat16ToUint:
4107 case glslang::EOpConvFloat16ToUint64:
4108#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004109 convOp = spv::OpConvertFToU;
4110 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004111
4112 case glslang::EOpConvIntToInt64:
4113 case glslang::EOpConvInt64ToInt:
4114 convOp = spv::OpSConvert;
4115 break;
4116
4117 case glslang::EOpConvUintToUint64:
4118 case glslang::EOpConvUint64ToUint:
4119 convOp = spv::OpUConvert;
4120 break;
4121
4122 case glslang::EOpConvIntToUint64:
4123 case glslang::EOpConvInt64ToUint:
4124 case glslang::EOpConvUint64ToInt:
4125 case glslang::EOpConvUintToInt64:
4126 // OpSConvert/OpUConvert + OpBitCast
4127 switch (op) {
4128 case glslang::EOpConvIntToUint64:
4129 convOp = spv::OpSConvert;
4130 type = builder.makeIntType(64);
4131 break;
4132 case glslang::EOpConvInt64ToUint:
4133 convOp = spv::OpSConvert;
4134 type = builder.makeIntType(32);
4135 break;
4136 case glslang::EOpConvUint64ToInt:
4137 convOp = spv::OpUConvert;
4138 type = builder.makeUintType(32);
4139 break;
4140 case glslang::EOpConvUintToInt64:
4141 convOp = spv::OpUConvert;
4142 type = builder.makeUintType(64);
4143 break;
4144 default:
4145 assert(0);
4146 break;
4147 }
4148
4149 if (vectorSize > 0)
4150 type = builder.makeVectorType(type, vectorSize);
4151
4152 operand = builder.createUnaryOp(convOp, type, operand);
4153
4154 if (builder.isInSpecConstCodeGenMode()) {
4155 // Build zero scalar or vector for OpIAdd.
4156 zero = (op == glslang::EOpConvIntToUint64 ||
4157 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4158 zero = makeSmearedConstant(zero, vectorSize);
4159 // Use OpIAdd, instead of OpBitcast to do the conversion when
4160 // generating for OpSpecConstantOp instruction.
4161 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4162 }
4163 // For normal run-time conversion instruction, use OpBitcast.
4164 convOp = spv::OpBitcast;
4165 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004166 default:
4167 break;
4168 }
4169
4170 spv::Id result = 0;
4171 if (convOp == spv::OpNop)
4172 return result;
4173
4174 if (convOp == spv::OpSelect) {
4175 zero = makeSmearedConstant(zero, vectorSize);
4176 one = makeSmearedConstant(one, vectorSize);
4177 result = builder.createTriOp(convOp, destType, operand, one, zero);
4178 } else
4179 result = builder.createUnaryOp(convOp, destType, operand);
4180
John Kessenich32cfd492016-02-02 12:37:46 -07004181 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004182}
4183
4184spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4185{
4186 if (vectorSize == 0)
4187 return constant;
4188
4189 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4190 std::vector<spv::Id> components;
4191 for (int c = 0; c < vectorSize; ++c)
4192 components.push_back(constant);
4193 return builder.makeCompositeConstant(vectorTypeId, components);
4194}
4195
John Kessenich426394d2015-07-23 10:22:48 -06004196// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004197spv::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 -06004198{
4199 spv::Op opCode = spv::OpNop;
4200
4201 switch (op) {
4202 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004203 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004204 opCode = spv::OpAtomicIAdd;
4205 break;
4206 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004207 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004208 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004209 break;
4210 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004211 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004212 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004213 break;
4214 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004215 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004216 opCode = spv::OpAtomicAnd;
4217 break;
4218 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004219 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004220 opCode = spv::OpAtomicOr;
4221 break;
4222 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004223 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004224 opCode = spv::OpAtomicXor;
4225 break;
4226 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004227 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004228 opCode = spv::OpAtomicExchange;
4229 break;
4230 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004231 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004232 opCode = spv::OpAtomicCompareExchange;
4233 break;
4234 case glslang::EOpAtomicCounterIncrement:
4235 opCode = spv::OpAtomicIIncrement;
4236 break;
4237 case glslang::EOpAtomicCounterDecrement:
4238 opCode = spv::OpAtomicIDecrement;
4239 break;
4240 case glslang::EOpAtomicCounter:
4241 opCode = spv::OpAtomicLoad;
4242 break;
4243 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004244 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004245 break;
4246 }
4247
4248 // Sort out the operands
4249 // - mapping from glslang -> SPV
4250 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004251 // - compare-exchange swaps the value and comparator
4252 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004253 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4254 auto opIt = operands.begin(); // walk the glslang operands
4255 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004256 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4257 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4258 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004259 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4260 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004261 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004262 spvAtomicOperands.push_back(*(opIt + 1));
4263 spvAtomicOperands.push_back(*opIt);
4264 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004265 }
John Kessenich426394d2015-07-23 10:22:48 -06004266
John Kessenich3e60a6f2015-09-14 22:45:16 -06004267 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004268 for (; opIt != operands.end(); ++opIt)
4269 spvAtomicOperands.push_back(*opIt);
4270
4271 return builder.createOp(opCode, typeId, spvAtomicOperands);
4272}
4273
John Kessenich91cef522016-05-05 16:45:40 -06004274// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004275spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004276{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004277#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004278 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004279 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004280#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004281
Rex Xu51596642016-09-21 18:56:12 +08004282 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004283 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004284 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4285
chaocf200da82016-12-20 12:44:35 -08004286 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4287 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004288 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4289 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004290 } else if (op == glslang::EOpAnyInvocation ||
4291 op == glslang::EOpAllInvocations ||
4292 op == glslang::EOpAllInvocationsEqual) {
4293 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4294 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004295 } else {
4296 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004297#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004298 if (op == glslang::EOpMinInvocationsNonUniform ||
4299 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004300 op == glslang::EOpAddInvocationsNonUniform ||
4301 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4302 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4303 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4304 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4305 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4306 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004307 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004308#endif
Rex Xu51596642016-09-21 18:56:12 +08004309
4310 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004311#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004312 switch (op) {
4313 case glslang::EOpMinInvocations:
4314 case glslang::EOpMaxInvocations:
4315 case glslang::EOpAddInvocations:
4316 case glslang::EOpMinInvocationsNonUniform:
4317 case glslang::EOpMaxInvocationsNonUniform:
4318 case glslang::EOpAddInvocationsNonUniform:
4319 groupOperation = spv::GroupOperationReduce;
4320 spvGroupOperands.push_back(groupOperation);
4321 break;
4322 case glslang::EOpMinInvocationsInclusiveScan:
4323 case glslang::EOpMaxInvocationsInclusiveScan:
4324 case glslang::EOpAddInvocationsInclusiveScan:
4325 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4326 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4327 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4328 groupOperation = spv::GroupOperationInclusiveScan;
4329 spvGroupOperands.push_back(groupOperation);
4330 break;
4331 case glslang::EOpMinInvocationsExclusiveScan:
4332 case glslang::EOpMaxInvocationsExclusiveScan:
4333 case glslang::EOpAddInvocationsExclusiveScan:
4334 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4335 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4336 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4337 groupOperation = spv::GroupOperationExclusiveScan;
4338 spvGroupOperands.push_back(groupOperation);
4339 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004340 default:
4341 break;
Rex Xu430ef402016-10-14 17:22:23 +08004342 }
Rex Xu9d93a232016-05-05 12:30:44 +08004343#endif
Rex Xu51596642016-09-21 18:56:12 +08004344 }
4345
4346 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4347 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004348
4349 switch (op) {
4350 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004351 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004352 break;
John Kessenich91cef522016-05-05 16:45:40 -06004353 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004354 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004355 break;
John Kessenich91cef522016-05-05 16:45:40 -06004356 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004357 opCode = spv::OpSubgroupAllEqualKHR;
4358 break;
Rex Xu51596642016-09-21 18:56:12 +08004359 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004360 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004361 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004362 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004363 break;
4364 case glslang::EOpReadFirstInvocation:
4365 opCode = spv::OpSubgroupFirstInvocationKHR;
4366 break;
4367 case glslang::EOpBallot:
4368 {
4369 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4370 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4371 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4372 //
4373 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4374 //
4375 spv::Id uintType = builder.makeUintType(32);
4376 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4377 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4378
4379 std::vector<spv::Id> components;
4380 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4381 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4382
4383 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4384 return builder.createUnaryOp(spv::OpBitcast, typeId,
4385 builder.createCompositeConstruct(uvec2Type, components));
4386 }
4387
Rex Xu9d93a232016-05-05 12:30:44 +08004388#ifdef AMD_EXTENSIONS
4389 case glslang::EOpMinInvocations:
4390 case glslang::EOpMaxInvocations:
4391 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004392 case glslang::EOpMinInvocationsInclusiveScan:
4393 case glslang::EOpMaxInvocationsInclusiveScan:
4394 case glslang::EOpAddInvocationsInclusiveScan:
4395 case glslang::EOpMinInvocationsExclusiveScan:
4396 case glslang::EOpMaxInvocationsExclusiveScan:
4397 case glslang::EOpAddInvocationsExclusiveScan:
4398 if (op == glslang::EOpMinInvocations ||
4399 op == glslang::EOpMinInvocationsInclusiveScan ||
4400 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004401 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004402 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004403 else {
4404 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004405 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004406 else
Rex Xu51596642016-09-21 18:56:12 +08004407 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004408 }
Rex Xu430ef402016-10-14 17:22:23 +08004409 } else if (op == glslang::EOpMaxInvocations ||
4410 op == glslang::EOpMaxInvocationsInclusiveScan ||
4411 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004412 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004413 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004414 else {
4415 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004416 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004417 else
Rex Xu51596642016-09-21 18:56:12 +08004418 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004419 }
4420 } else {
4421 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004422 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004423 else
Rex Xu51596642016-09-21 18:56:12 +08004424 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004425 }
4426
Rex Xu2bbbe062016-08-23 15:41:05 +08004427 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004428 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004429
4430 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004431 case glslang::EOpMinInvocationsNonUniform:
4432 case glslang::EOpMaxInvocationsNonUniform:
4433 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004434 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4435 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4436 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4437 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4438 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4439 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4440 if (op == glslang::EOpMinInvocationsNonUniform ||
4441 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4442 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004443 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004444 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004445 else {
4446 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004447 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004448 else
Rex Xu51596642016-09-21 18:56:12 +08004449 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004450 }
4451 }
Rex Xu430ef402016-10-14 17:22:23 +08004452 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4453 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4454 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004455 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004456 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004457 else {
4458 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004459 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004460 else
Rex Xu51596642016-09-21 18:56:12 +08004461 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004462 }
4463 }
4464 else {
4465 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004466 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004467 else
Rex Xu51596642016-09-21 18:56:12 +08004468 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004469 }
4470
Rex Xu2bbbe062016-08-23 15:41:05 +08004471 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004472 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004473
4474 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004475#endif
John Kessenich91cef522016-05-05 16:45:40 -06004476 default:
4477 logger->missingFunctionality("invocation operation");
4478 return spv::NoResult;
4479 }
Rex Xu51596642016-09-21 18:56:12 +08004480
4481 assert(opCode != spv::OpNop);
4482 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004483}
4484
Rex Xu2bbbe062016-08-23 15:41:05 +08004485// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004486spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004487{
Rex Xub7072052016-09-26 15:53:40 +08004488#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004489 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4490 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004491 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004492 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004493 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4494 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4495 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004496#else
4497 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4498 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004499 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4500 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004501#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004502
4503 // Handle group invocation operations scalar by scalar.
4504 // The result type is the same type as the original type.
4505 // The algorithm is to:
4506 // - break the vector into scalars
4507 // - apply the operation to each scalar
4508 // - make a vector out the scalar results
4509
4510 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004511 int numComponents = builder.getNumComponents(operands[0]);
4512 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004513 std::vector<spv::Id> results;
4514
4515 // do each scalar op
4516 for (int comp = 0; comp < numComponents; ++comp) {
4517 std::vector<unsigned int> indexes;
4518 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004519 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004520 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004521 if (op == spv::OpSubgroupReadInvocationKHR) {
4522 spvGroupOperands.push_back(scalar);
4523 spvGroupOperands.push_back(operands[1]);
4524 } else if (op == spv::OpGroupBroadcast) {
4525 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004526 spvGroupOperands.push_back(scalar);
4527 spvGroupOperands.push_back(operands[1]);
4528 } else {
chaocf200da82016-12-20 12:44:35 -08004529 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004530 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004531 spvGroupOperands.push_back(scalar);
4532 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004533
Rex Xub7072052016-09-26 15:53:40 +08004534 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004535 }
4536
4537 // put the pieces together
4538 return builder.createCompositeConstruct(typeId, results);
4539}
Rex Xu2bbbe062016-08-23 15:41:05 +08004540
John Kessenich5e4b1242015-08-06 22:53:06 -06004541spv::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 -06004542{
Rex Xu8ff43de2016-04-22 16:51:45 +08004543 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004544#ifdef AMD_EXTENSIONS
4545 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4546#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004547 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004548#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004549
John Kessenich140f3df2015-06-26 16:58:36 -06004550 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004551 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004552 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004553 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004554 spv::Id typeId0 = 0;
4555 if (consumedOperands > 0)
4556 typeId0 = builder.getTypeId(operands[0]);
4557 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004558
4559 switch (op) {
4560 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004561 if (isFloat)
4562 libCall = spv::GLSLstd450FMin;
4563 else if (isUnsigned)
4564 libCall = spv::GLSLstd450UMin;
4565 else
4566 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004567 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004568 break;
4569 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004570 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004571 break;
4572 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004573 if (isFloat)
4574 libCall = spv::GLSLstd450FMax;
4575 else if (isUnsigned)
4576 libCall = spv::GLSLstd450UMax;
4577 else
4578 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004579 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004580 break;
4581 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004582 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004583 break;
4584 case glslang::EOpDot:
4585 opCode = spv::OpDot;
4586 break;
4587 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004588 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004589 break;
4590
4591 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004592 if (isFloat)
4593 libCall = spv::GLSLstd450FClamp;
4594 else if (isUnsigned)
4595 libCall = spv::GLSLstd450UClamp;
4596 else
4597 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004598 builder.promoteScalar(precision, operands.front(), operands[1]);
4599 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004600 break;
4601 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004602 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4603 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004604 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004605 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004606 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004607 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004608 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004609 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004610 break;
4611 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004612 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004613 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004614 break;
4615 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004616 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004617 builder.promoteScalar(precision, operands[0], operands[2]);
4618 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004619 break;
4620
4621 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004622 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004623 break;
4624 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004625 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004626 break;
4627 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004628 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004629 break;
4630 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004631 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004632 break;
4633 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004634 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004635 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004636 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004637 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004638 libCall = spv::GLSLstd450InterpolateAtSample;
4639 break;
4640 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004641 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004642 libCall = spv::GLSLstd450InterpolateAtOffset;
4643 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004644 case glslang::EOpAddCarry:
4645 opCode = spv::OpIAddCarry;
4646 typeId = builder.makeStructResultType(typeId0, typeId0);
4647 consumedOperands = 2;
4648 break;
4649 case glslang::EOpSubBorrow:
4650 opCode = spv::OpISubBorrow;
4651 typeId = builder.makeStructResultType(typeId0, typeId0);
4652 consumedOperands = 2;
4653 break;
4654 case glslang::EOpUMulExtended:
4655 opCode = spv::OpUMulExtended;
4656 typeId = builder.makeStructResultType(typeId0, typeId0);
4657 consumedOperands = 2;
4658 break;
4659 case glslang::EOpIMulExtended:
4660 opCode = spv::OpSMulExtended;
4661 typeId = builder.makeStructResultType(typeId0, typeId0);
4662 consumedOperands = 2;
4663 break;
4664 case glslang::EOpBitfieldExtract:
4665 if (isUnsigned)
4666 opCode = spv::OpBitFieldUExtract;
4667 else
4668 opCode = spv::OpBitFieldSExtract;
4669 break;
4670 case glslang::EOpBitfieldInsert:
4671 opCode = spv::OpBitFieldInsert;
4672 break;
4673
4674 case glslang::EOpFma:
4675 libCall = spv::GLSLstd450Fma;
4676 break;
4677 case glslang::EOpFrexp:
4678 libCall = spv::GLSLstd450FrexpStruct;
4679 if (builder.getNumComponents(operands[0]) == 1)
4680 frexpIntType = builder.makeIntegerType(32, true);
4681 else
4682 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
4683 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4684 consumedOperands = 1;
4685 break;
4686 case glslang::EOpLdexp:
4687 libCall = spv::GLSLstd450Ldexp;
4688 break;
4689
Rex Xu574ab042016-04-14 16:53:07 +08004690 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004691 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004692
Rex Xu9d93a232016-05-05 12:30:44 +08004693#ifdef AMD_EXTENSIONS
4694 case glslang::EOpSwizzleInvocations:
4695 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4696 libCall = spv::SwizzleInvocationsAMD;
4697 break;
4698 case glslang::EOpSwizzleInvocationsMasked:
4699 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4700 libCall = spv::SwizzleInvocationsMaskedAMD;
4701 break;
4702 case glslang::EOpWriteInvocation:
4703 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4704 libCall = spv::WriteInvocationAMD;
4705 break;
4706
4707 case glslang::EOpMin3:
4708 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4709 if (isFloat)
4710 libCall = spv::FMin3AMD;
4711 else {
4712 if (isUnsigned)
4713 libCall = spv::UMin3AMD;
4714 else
4715 libCall = spv::SMin3AMD;
4716 }
4717 break;
4718 case glslang::EOpMax3:
4719 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4720 if (isFloat)
4721 libCall = spv::FMax3AMD;
4722 else {
4723 if (isUnsigned)
4724 libCall = spv::UMax3AMD;
4725 else
4726 libCall = spv::SMax3AMD;
4727 }
4728 break;
4729 case glslang::EOpMid3:
4730 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4731 if (isFloat)
4732 libCall = spv::FMid3AMD;
4733 else {
4734 if (isUnsigned)
4735 libCall = spv::UMid3AMD;
4736 else
4737 libCall = spv::SMid3AMD;
4738 }
4739 break;
4740
4741 case glslang::EOpInterpolateAtVertex:
4742 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4743 libCall = spv::InterpolateAtVertexAMD;
4744 break;
4745#endif
4746
John Kessenich140f3df2015-06-26 16:58:36 -06004747 default:
4748 return 0;
4749 }
4750
4751 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004752 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004753 // Use an extended instruction from the standard library.
4754 // Construct the call arguments, without modifying the original operands vector.
4755 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4756 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004757 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004758 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004759 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004760 case 0:
4761 // should all be handled by visitAggregate and createNoArgOperation
4762 assert(0);
4763 return 0;
4764 case 1:
4765 // should all be handled by createUnaryOperation
4766 assert(0);
4767 return 0;
4768 case 2:
4769 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4770 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004771 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004772 // anything 3 or over doesn't have l-value operands, so all should be consumed
4773 assert(consumedOperands == operands.size());
4774 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004775 break;
4776 }
4777 }
4778
John Kessenich55e7d112015-11-15 21:33:39 -07004779 // Decode the return types that were structures
4780 switch (op) {
4781 case glslang::EOpAddCarry:
4782 case glslang::EOpSubBorrow:
4783 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4784 id = builder.createCompositeExtract(id, typeId0, 0);
4785 break;
4786 case glslang::EOpUMulExtended:
4787 case glslang::EOpIMulExtended:
4788 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4789 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4790 break;
4791 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05004792 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07004793 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4794 id = builder.createCompositeExtract(id, typeId0, 0);
4795 break;
4796 default:
4797 break;
4798 }
4799
John Kessenich32cfd492016-02-02 12:37:46 -07004800 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004801}
4802
Rex Xu9d93a232016-05-05 12:30:44 +08004803// Intrinsics with no arguments (or no return value, and no precision).
4804spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004805{
4806 // TODO: get the barrier operands correct
4807
4808 switch (op) {
4809 case glslang::EOpEmitVertex:
4810 builder.createNoResultOp(spv::OpEmitVertex);
4811 return 0;
4812 case glslang::EOpEndPrimitive:
4813 builder.createNoResultOp(spv::OpEndPrimitive);
4814 return 0;
4815 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004816 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004817 return 0;
4818 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004819 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004820 return 0;
4821 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004822 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004823 return 0;
4824 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004825 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004826 return 0;
4827 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004828 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004829 return 0;
4830 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004831 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004832 return 0;
4833 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004834 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004835 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004836 case glslang::EOpAllMemoryBarrierWithGroupSync:
4837 // Control barrier with non-"None" semantic is also a memory barrier.
4838 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4839 return 0;
4840 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4841 // Control barrier with non-"None" semantic is also a memory barrier.
4842 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4843 return 0;
4844 case glslang::EOpWorkgroupMemoryBarrier:
4845 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4846 return 0;
4847 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4848 // Control barrier with non-"None" semantic is also a memory barrier.
4849 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4850 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004851#ifdef AMD_EXTENSIONS
4852 case glslang::EOpTime:
4853 {
4854 std::vector<spv::Id> args; // Dummy arguments
4855 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4856 return builder.setPrecision(id, precision);
4857 }
4858#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004859 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004860 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004861 return 0;
4862 }
4863}
4864
4865spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4866{
John Kessenich2f273362015-07-18 22:34:27 -06004867 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004868 spv::Id id;
4869 if (symbolValues.end() != iter) {
4870 id = iter->second;
4871 return id;
4872 }
4873
4874 // it was not found, create it
4875 id = createSpvVariable(symbol);
4876 symbolValues[symbol->getId()] = id;
4877
Rex Xuc884b4a2016-06-29 15:03:44 +08004878 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004879 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004880 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004881 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004882 if (symbol->getType().getQualifier().hasSpecConstantId())
4883 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004884 if (symbol->getQualifier().hasIndex())
4885 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4886 if (symbol->getQualifier().hasComponent())
4887 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4888 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004889 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004890 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004891 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004892 if (symbol->getQualifier().hasXfbBuffer())
4893 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4894 if (symbol->getQualifier().hasXfbOffset())
4895 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4896 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004897 // atomic counters use this:
4898 if (symbol->getQualifier().hasOffset())
4899 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004900 }
4901
scygan2c864272016-05-18 18:09:17 +02004902 if (symbol->getQualifier().hasLocation())
4903 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004904 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004905 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004906 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004907 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004908 }
John Kessenich140f3df2015-06-26 16:58:36 -06004909 if (symbol->getQualifier().hasSet())
4910 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004911 else if (IsDescriptorResource(symbol->getType())) {
4912 // default to 0
4913 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4914 }
John Kessenich140f3df2015-06-26 16:58:36 -06004915 if (symbol->getQualifier().hasBinding())
4916 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004917 if (symbol->getQualifier().hasAttachment())
4918 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004919 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004920 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004921 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004922 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004923 if (symbol->getQualifier().hasXfbBuffer())
4924 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4925 }
4926
Rex Xu1da878f2016-02-21 20:59:01 +08004927 if (symbol->getType().isImage()) {
4928 std::vector<spv::Decoration> memory;
4929 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
4930 for (unsigned int i = 0; i < memory.size(); ++i)
4931 addDecoration(id, memory[i]);
4932 }
4933
John Kessenich140f3df2015-06-26 16:58:36 -06004934 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06004935 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06004936 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07004937 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06004938
John Kessenichecba76f2017-01-06 00:34:48 -07004939#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08004940 if (builtIn == spv::BuiltInSampleMask) {
4941 spv::Decoration decoration;
4942 // GL_NV_sample_mask_override_coverage extension
4943 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08004944 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08004945 else
4946 decoration = (spv::Decoration)spv::DecorationMax;
4947 addDecoration(id, decoration);
4948 if (decoration != spv::DecorationMax) {
4949 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
4950 }
4951 }
chaoc771d89f2017-01-13 01:10:53 -08004952 else if (builtIn == spv::BuiltInLayer) {
4953 // SPV_NV_viewport_array2 extension
4954 if (symbol->getQualifier().layoutViewportRelative)
4955 {
4956 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
4957 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4958 builder.addExtension(spv::E_SPV_NV_viewport_array2);
4959 }
4960 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
4961 {
4962 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
4963 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4964 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
4965 }
4966 }
4967
chaoc6e5acae2016-12-20 13:28:52 -08004968 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08004969 addDecoration(id, spv::DecorationPassthroughNV);
4970 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08004971 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4972 }
chaoc0ad6a4e2016-12-19 16:29:34 -08004973#endif
4974
John Kessenich140f3df2015-06-26 16:58:36 -06004975 return id;
4976}
4977
John Kessenich55e7d112015-11-15 21:33:39 -07004978// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06004979void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
4980{
John Kessenich4016e382016-07-15 11:53:56 -06004981 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004982 builder.addDecoration(id, dec);
4983}
4984
John Kessenich55e7d112015-11-15 21:33:39 -07004985// If 'dec' is valid, add a one-operand decoration to an object
4986void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
4987{
John Kessenich4016e382016-07-15 11:53:56 -06004988 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07004989 builder.addDecoration(id, dec, value);
4990}
4991
4992// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06004993void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
4994{
John Kessenich4016e382016-07-15 11:53:56 -06004995 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06004996 builder.addMemberDecoration(id, (unsigned)member, dec);
4997}
4998
John Kessenich92187592016-02-01 13:45:25 -07004999// If 'dec' is valid, add a one-operand decoration to a struct member
5000void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5001{
John Kessenich4016e382016-07-15 11:53:56 -06005002 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005003 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5004}
5005
John Kessenich55e7d112015-11-15 21:33:39 -07005006// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005007// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005008//
5009// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5010//
5011// Recursively walk the nodes. The nodes form a tree whose leaves are
5012// regular constants, which themselves are trees that createSpvConstant()
5013// recursively walks. So, this function walks the "top" of the tree:
5014// - emit specialization constant-building instructions for specConstant
5015// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005016spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005017{
John Kessenich7cc0e282016-03-20 00:46:02 -06005018 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005019
qining4f4bb812016-04-03 23:55:17 -04005020 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005021 if (! node.getQualifier().specConstant) {
5022 // hand off to the non-spec-constant path
5023 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5024 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005025 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005026 nextConst, false);
5027 }
5028
5029 // We now know we have a specialization constant to build
5030
John Kessenichd94c0032016-05-30 19:29:40 -06005031 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005032 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5033 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5034 std::vector<spv::Id> dimConstId;
5035 for (int dim = 0; dim < 3; ++dim) {
5036 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5037 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5038 if (specConst)
5039 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5040 }
5041 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5042 }
5043
5044 // An AST node labelled as specialization constant should be a symbol node.
5045 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5046 if (auto* sn = node.getAsSymbolNode()) {
5047 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005048 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5049 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5050 // will set the builder into spec constant op instruction generating mode.
5051 sub_tree->traverse(this);
5052 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005053 } else if (auto* const_union_array = &sn->getConstArray()){
5054 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005055 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5056 builder.addName(id, sn->getName().c_str());
5057 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005058 }
5059 }
qining4f4bb812016-04-03 23:55:17 -04005060
5061 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5062 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005063 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005064 exit(1);
5065 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005066}
5067
John Kessenich140f3df2015-06-26 16:58:36 -06005068// Use 'consts' as the flattened glslang source of scalar constants to recursively
5069// build the aggregate SPIR-V constant.
5070//
5071// If there are not enough elements present in 'consts', 0 will be substituted;
5072// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5073//
qining08408382016-03-21 09:51:37 -04005074spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005075{
5076 // vector of constants for SPIR-V
5077 std::vector<spv::Id> spvConsts;
5078
5079 // Type is used for struct and array constants
5080 spv::Id typeId = convertGlslangToSpvType(glslangType);
5081
5082 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005083 glslang::TType elementType(glslangType, 0);
5084 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005085 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005086 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005087 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005088 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005089 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005090 } else if (glslangType.getStruct()) {
5091 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5092 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005093 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005094 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005095 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5096 bool zero = nextConst >= consts.size();
5097 switch (glslangType.getBasicType()) {
5098 case glslang::EbtInt:
5099 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5100 break;
5101 case glslang::EbtUint:
5102 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5103 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005104 case glslang::EbtInt64:
5105 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5106 break;
5107 case glslang::EbtUint64:
5108 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5109 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005110 case glslang::EbtFloat:
5111 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5112 break;
5113 case glslang::EbtDouble:
5114 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5115 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005116#ifdef AMD_EXTENSIONS
5117 case glslang::EbtFloat16:
5118 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5119 break;
5120#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005121 case glslang::EbtBool:
5122 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5123 break;
5124 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005125 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005126 break;
5127 }
5128 ++nextConst;
5129 }
5130 } else {
5131 // we have a non-aggregate (scalar) constant
5132 bool zero = nextConst >= consts.size();
5133 spv::Id scalar = 0;
5134 switch (glslangType.getBasicType()) {
5135 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005136 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005137 break;
5138 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005139 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005140 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005141 case glslang::EbtInt64:
5142 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5143 break;
5144 case glslang::EbtUint64:
5145 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005147 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005148 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005149 break;
5150 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005151 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005152 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005153#ifdef AMD_EXTENSIONS
5154 case glslang::EbtFloat16:
5155 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5156 break;
5157#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005158 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005159 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005160 break;
5161 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005162 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005163 break;
5164 }
5165 ++nextConst;
5166 return scalar;
5167 }
5168
5169 return builder.makeCompositeConstant(typeId, spvConsts);
5170}
5171
John Kessenich7c1aa102015-10-15 13:29:11 -06005172// Return true if the node is a constant or symbol whose reading has no
5173// non-trivial observable cost or effect.
5174bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5175{
5176 // don't know what this is
5177 if (node == nullptr)
5178 return false;
5179
5180 // a constant is safe
5181 if (node->getAsConstantUnion() != nullptr)
5182 return true;
5183
5184 // not a symbol means non-trivial
5185 if (node->getAsSymbolNode() == nullptr)
5186 return false;
5187
5188 // a symbol, depends on what's being read
5189 switch (node->getType().getQualifier().storage) {
5190 case glslang::EvqTemporary:
5191 case glslang::EvqGlobal:
5192 case glslang::EvqIn:
5193 case glslang::EvqInOut:
5194 case glslang::EvqConst:
5195 case glslang::EvqConstReadOnly:
5196 case glslang::EvqUniform:
5197 return true;
5198 default:
5199 return false;
5200 }
qining25262b32016-05-06 17:25:16 -04005201}
John Kessenich7c1aa102015-10-15 13:29:11 -06005202
5203// A node is trivial if it is a single operation with no side effects.
5204// Error on the side of saying non-trivial.
5205// Return true if trivial.
5206bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5207{
5208 if (node == nullptr)
5209 return false;
5210
5211 // symbols and constants are trivial
5212 if (isTrivialLeaf(node))
5213 return true;
5214
5215 // otherwise, it needs to be a simple operation or one or two leaf nodes
5216
5217 // not a simple operation
5218 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5219 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5220 if (binaryNode == nullptr && unaryNode == nullptr)
5221 return false;
5222
5223 // not on leaf nodes
5224 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5225 return false;
5226
5227 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5228 return false;
5229 }
5230
5231 switch (node->getAsOperator()->getOp()) {
5232 case glslang::EOpLogicalNot:
5233 case glslang::EOpConvIntToBool:
5234 case glslang::EOpConvUintToBool:
5235 case glslang::EOpConvFloatToBool:
5236 case glslang::EOpConvDoubleToBool:
5237 case glslang::EOpEqual:
5238 case glslang::EOpNotEqual:
5239 case glslang::EOpLessThan:
5240 case glslang::EOpGreaterThan:
5241 case glslang::EOpLessThanEqual:
5242 case glslang::EOpGreaterThanEqual:
5243 case glslang::EOpIndexDirect:
5244 case glslang::EOpIndexDirectStruct:
5245 case glslang::EOpLogicalXor:
5246 case glslang::EOpAny:
5247 case glslang::EOpAll:
5248 return true;
5249 default:
5250 return false;
5251 }
5252}
5253
5254// Emit short-circuiting code, where 'right' is never evaluated unless
5255// the left side is true (for &&) or false (for ||).
5256spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5257{
5258 spv::Id boolTypeId = builder.makeBoolType();
5259
5260 // emit left operand
5261 builder.clearAccessChain();
5262 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005263 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005264
5265 // Operands to accumulate OpPhi operands
5266 std::vector<spv::Id> phiOperands;
5267 // accumulate left operand's phi information
5268 phiOperands.push_back(leftId);
5269 phiOperands.push_back(builder.getBuildPoint()->getId());
5270
5271 // Make the two kinds of operation symmetric with a "!"
5272 // || => emit "if (! left) result = right"
5273 // && => emit "if ( left) result = right"
5274 //
5275 // TODO: this runtime "not" for || could be avoided by adding functionality
5276 // to 'builder' to have an "else" without an "then"
5277 if (op == glslang::EOpLogicalOr)
5278 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5279
5280 // make an "if" based on the left value
5281 spv::Builder::If ifBuilder(leftId, builder);
5282
5283 // emit right operand as the "then" part of the "if"
5284 builder.clearAccessChain();
5285 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005286 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005287
5288 // accumulate left operand's phi information
5289 phiOperands.push_back(rightId);
5290 phiOperands.push_back(builder.getBuildPoint()->getId());
5291
5292 // finish the "if"
5293 ifBuilder.makeEndIf();
5294
5295 // phi together the two results
5296 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5297}
5298
Rex Xu9d93a232016-05-05 12:30:44 +08005299// Return type Id of the imported set of extended instructions corresponds to the name.
5300// Import this set if it has not been imported yet.
5301spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5302{
5303 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5304 return extBuiltinMap[name];
5305 else {
Rex Xu51596642016-09-21 18:56:12 +08005306 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005307 spv::Id extBuiltins = builder.import(name);
5308 extBuiltinMap[name] = extBuiltins;
5309 return extBuiltins;
5310 }
5311}
5312
John Kessenich140f3df2015-06-26 16:58:36 -06005313}; // end anonymous namespace
5314
5315namespace glslang {
5316
John Kessenich68d78fd2015-07-12 19:28:10 -06005317void GetSpirvVersion(std::string& version)
5318{
John Kessenich9e55f632015-07-15 10:03:39 -06005319 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005320 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005321 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005322 version = buf;
5323}
5324
John Kessenich140f3df2015-06-26 16:58:36 -06005325// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005326void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005327{
5328 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005329 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005330 if (out.fail())
5331 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005332 for (int i = 0; i < (int)spirv.size(); ++i) {
5333 unsigned int word = spirv[i];
5334 out.write((const char*)&word, 4);
5335 }
5336 out.close();
5337}
5338
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005339// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005340void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005341{
5342 std::ofstream out;
5343 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005344 if (out.fail())
5345 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005346 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005347 if (varName != nullptr) {
5348 out << "\t #pragma once" << std::endl;
5349 out << "const uint32_t " << varName << "[] = {" << std::endl;
5350 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005351 const int WORDS_PER_LINE = 8;
5352 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5353 out << "\t";
5354 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5355 const unsigned int word = spirv[i + j];
5356 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5357 if (i + j + 1 < (int)spirv.size()) {
5358 out << ",";
5359 }
5360 }
5361 out << std::endl;
5362 }
Flavio15017db2017-02-15 14:29:33 -08005363 if (varName != nullptr) {
5364 out << "};";
5365 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005366 out.close();
5367}
5368
John Kessenich140f3df2015-06-26 16:58:36 -06005369//
5370// Set up the glslang traversal
5371//
5372void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5373{
Lei Zhang17535f72016-05-04 15:55:59 -04005374 spv::SpvBuildLogger logger;
5375 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005376}
5377
Lei Zhang17535f72016-05-04 15:55:59 -04005378void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005379{
John Kessenich140f3df2015-06-26 16:58:36 -06005380 TIntermNode* root = intermediate.getTreeRoot();
5381
5382 if (root == 0)
5383 return;
5384
5385 glslang::GetThreadPoolAllocator().push();
5386
Lei Zhang17535f72016-05-04 15:55:59 -04005387 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005388 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005389 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005390 it.dumpSpv(spirv);
5391
5392 glslang::GetThreadPoolAllocator().pop();
5393}
5394
5395}; // end namespace glslang