blob: cffeb2017c2930fb97c0acd38fb10d61368eff5e [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 Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
57// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020058#include "../glslang/MachineIndependent/localintermediate.h"
59#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060060#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
94 spv::Decoration precision;
95 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060096 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060097};
98
99} // namespace
qining4c912612016-04-01 10:35:16 -0400100
John Kessenich140f3df2015-06-26 16:58:36 -0600101//
102// The main holder of information for translating glslang to SPIR-V.
103//
104// Derives from the AST walking base class.
105//
106class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
107public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700108 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
109 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700126 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
127 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
128
Rex Xu17ff3432016-10-14 17:41:45 +0800129 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800130 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600131 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100132 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700133 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700134 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
135 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700136 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600137 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600138 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600139 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
140 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600141 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
142 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
143 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600144 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600145 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
146 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600147 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600148 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
149 glslang::TLayoutPacking, const glslang::TQualifier&);
150 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
151 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700152 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700153 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800154 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600155 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700156 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700157 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
158 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700159 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
160 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100161 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600162
John Kessenich6fccb3c2016-09-19 16:01:41 -0600163 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600164 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600165 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 void makeFunctions(const glslang::TIntermSequence&);
167 void makeGlobalInitializers(const glslang::TIntermSequence&);
168 void visitFunctions(const glslang::TIntermSequence&);
169 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800170 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600171 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
172 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
174
John Kessenichead86222018-03-28 18:01:20 -0600175 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
176 glslang::TBasicType typeProxy, bool reduceComparison = true);
177 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
178 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
179 glslang::TBasicType typeProxy);
180 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600184 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600185 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800186 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 +0800187 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800188 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700189 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600190 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 +0800191 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600192 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400193 spv::Id createSpvConstant(const glslang::TIntermTyped&);
194 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600195 bool isTrivialLeaf(const glslang::TIntermTyped* node);
196 bool isTrivial(const glslang::TIntermTyped* node);
197 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500198#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800199 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500200#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700201 void addPre13Extension(const char* ext)
202 {
203 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
204 builder.addExtension(ext);
205 }
John Kessenich140f3df2015-06-26 16:58:36 -0600206
John Kessenich121853f2017-05-31 17:11:16 -0600207 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600208 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600209 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700210 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600211 int sequenceDepth;
212
Lei Zhang17535f72016-05-04 15:55:59 -0400213 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400214
John Kessenich140f3df2015-06-26 16:58:36 -0600215 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
216 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700217 bool inEntryPoint;
218 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700219 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 -0700220 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600221 const glslang::TIntermediate* glslangIntermediate;
222 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800223 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600224
John Kessenich2f273362015-07-18 22:34:27 -0600225 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600226 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600227 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700228 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700229 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
230 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600231 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700232 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600233};
234
235//
236// Helper functions for translating glslang representations to SPIR-V enumerants.
237//
238
239// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700240spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600241{
John Kessenich66e2faf2016-03-12 18:34:36 -0700242 switch (source) {
243 case glslang::EShSourceGlsl:
244 switch (profile) {
245 case ENoProfile:
246 case ECoreProfile:
247 case ECompatibilityProfile:
248 return spv::SourceLanguageGLSL;
249 case EEsProfile:
250 return spv::SourceLanguageESSL;
251 default:
252 return spv::SourceLanguageUnknown;
253 }
254 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600255 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600256 default:
257 return spv::SourceLanguageUnknown;
258 }
259}
260
261// Translate glslang language (stage) to SPIR-V execution model.
262spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
263{
264 switch (stage) {
265 case EShLangVertex: return spv::ExecutionModelVertex;
266 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
267 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
268 case EShLangGeometry: return spv::ExecutionModelGeometry;
269 case EShLangFragment: return spv::ExecutionModelFragment;
270 case EShLangCompute: return spv::ExecutionModelGLCompute;
271 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600273 return spv::ExecutionModelFragment;
274 }
275}
276
John Kessenich140f3df2015-06-26 16:58:36 -0600277// Translate glslang sampler type to SPIR-V dimensionality.
278spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
279{
280 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700281 case glslang::Esd1D: return spv::Dim1D;
282 case glslang::Esd2D: return spv::Dim2D;
283 case glslang::Esd3D: return spv::Dim3D;
284 case glslang::EsdCube: return spv::DimCube;
285 case glslang::EsdRect: return spv::DimRect;
286 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700287 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::Dim2D;
291 }
292}
293
John Kessenichf6640762016-08-01 19:44:00 -0600294// Translate glslang precision to SPIR-V precision decorations.
295spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600296{
John Kessenichf6640762016-08-01 19:44:00 -0600297 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700298 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600299 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600300 default:
301 return spv::NoPrecision;
302 }
303}
304
John Kessenichf6640762016-08-01 19:44:00 -0600305// Translate glslang type to SPIR-V precision decorations.
306spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
307{
308 return TranslatePrecisionDecoration(type.getQualifier().precision);
309}
310
John Kessenich140f3df2015-06-26 16:58:36 -0600311// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600312spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
314 if (type.getBasicType() == glslang::EbtBlock) {
315 switch (type.getQualifier().storage) {
316 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600317 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600318 case glslang::EvqVaryingIn: return spv::DecorationBlock;
319 case glslang::EvqVaryingOut: return spv::DecorationBlock;
320 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700321 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600322 break;
323 }
324 }
325
John Kessenich4016e382016-07-15 11:53:56 -0600326 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600327}
328
Rex Xu1da878f2016-02-21 20:59:01 +0800329// Translate glslang type to SPIR-V memory decorations.
330void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
331{
332 if (qualifier.coherent)
333 memory.push_back(spv::DecorationCoherent);
John Kessenich14b85d32018-06-04 15:36:03 -0600334 if (qualifier.volatil) {
Rex Xu1da878f2016-02-21 20:59:01 +0800335 memory.push_back(spv::DecorationVolatile);
John Kessenich14b85d32018-06-04 15:36:03 -0600336 memory.push_back(spv::DecorationCoherent);
337 }
Rex Xu1da878f2016-02-21 20:59:01 +0800338 if (qualifier.restrict)
339 memory.push_back(spv::DecorationRestrict);
340 if (qualifier.readonly)
341 memory.push_back(spv::DecorationNonWritable);
342 if (qualifier.writeonly)
343 memory.push_back(spv::DecorationNonReadable);
344}
345
John Kessenich140f3df2015-06-26 16:58:36 -0600346// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700347spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600348{
349 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElmRowMajor:
352 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700353 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 default:
356 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 }
359 } else {
360 switch (type.getBasicType()) {
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 break;
364 case glslang::EbtBlock:
365 switch (type.getQualifier().storage) {
366 case glslang::EvqUniform:
367 case glslang::EvqBuffer:
368 switch (type.getQualifier().layoutPacking) {
369 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
371 default:
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 }
374 case glslang::EvqVaryingIn:
375 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 }
383 }
384}
385
386// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600387// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700388// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800389spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
Rex Xubbceed72016-05-21 09:40:44 +0800391 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700395 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600397 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800399 else if (qualifier.explicitInterp) {
400 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800401 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800402 }
Rex Xu9d93a232016-05-05 12:30:44 +0800403#endif
Rex Xubbceed72016-05-21 09:40:44 +0800404 else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800406}
407
408// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600409// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800410// should be applied.
411spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
412{
413 if (qualifier.patch)
414 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700417 else if (qualifier.sample) {
418 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600419 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700420 } else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422}
423
John Kessenich92187592016-02-01 13:45:25 -0700424// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700425spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600426{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationInvariant;
429 else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
qining9220dbb2016-05-04 17:34:38 -0400433// If glslang type is noContraction, return SPIR-V NoContraction decoration.
434spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
435{
436 if (qualifier.noContraction)
437 return spv::DecorationNoContraction;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400440}
441
John Kessenich5611c6d2018-04-05 11:25:02 -0600442// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
443spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
444{
445 if (qualifier.isNonUniform()) {
446 builder.addExtension("SPV_EXT_descriptor_indexing");
447 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
448 return spv::DecorationNonUniformEXT;
449 } else
450 return spv::DecorationMax;
451}
452
David Netoa901ffe2016-06-08 14:11:40 +0100453// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
454// associated capabilities when required. For some built-in variables, a capability
455// is generated only when using the variable in an executable instruction, but not when
456// just declaring a struct member variable with it. This is true for PointSize,
457// ClipDistance, and CullDistance.
458spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600459{
460 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700461 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600462 // Defer adding the capability until the built-in is actually used.
463 if (! memberDeclaration) {
464 switch (glslangIntermediate->getStage()) {
465 case EShLangGeometry:
466 builder.addCapability(spv::CapabilityGeometryPointSize);
467 break;
468 case EShLangTessControl:
469 case EShLangTessEvaluation:
470 builder.addCapability(spv::CapabilityTessellationPointSize);
471 break;
472 default:
473 break;
474 }
John Kessenich92187592016-02-01 13:45:25 -0700475 }
476 return spv::BuiltInPointSize;
477
John Kessenichebb50532016-05-16 19:22:05 -0600478 // These *Distance capabilities logically belong here, but if the member is declared and
479 // then never used, consumers of SPIR-V prefer the capability not be declared.
480 // They are now generated when used, rather than here when declared.
481 // Potentially, the specification should be more clear what the minimum
482 // use needed is to trigger the capability.
483 //
John Kessenich92187592016-02-01 13:45:25 -0700484 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100485 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800486 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700487 return spv::BuiltInClipDistance;
488
489 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100490 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800491 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700492 return spv::BuiltInCullDistance;
493
494 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600495 builder.addCapability(spv::CapabilityMultiViewport);
496 if (glslangIntermediate->getStage() == EShLangVertex ||
497 glslangIntermediate->getStage() == EShLangTessControl ||
498 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800499
John Kessenichba6a3c22017-09-13 13:22:50 -0600500 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
501 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800502 }
John Kessenich92187592016-02-01 13:45:25 -0700503 return spv::BuiltInViewportIndex;
504
John Kessenich5e801132016-02-15 11:09:46 -0700505 case glslang::EbvSampleId:
506 builder.addCapability(spv::CapabilitySampleRateShading);
507 return spv::BuiltInSampleId;
508
509 case glslang::EbvSamplePosition:
510 builder.addCapability(spv::CapabilitySampleRateShading);
511 return spv::BuiltInSamplePosition;
512
513 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700514 return spv::BuiltInSampleMask;
515
John Kessenich78a45572016-07-08 14:05:15 -0600516 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600517 builder.addCapability(spv::CapabilityGeometry);
518 if (glslangIntermediate->getStage() == EShLangVertex ||
519 glslangIntermediate->getStage() == EShLangTessControl ||
520 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800521
John Kessenichba6a3c22017-09-13 13:22:50 -0600522 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
523 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800524 }
John Kessenich78a45572016-07-08 14:05:15 -0600525 return spv::BuiltInLayer;
526
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvVertexId: return spv::BuiltInVertexId;
529 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700530 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
531 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800532
John Kessenichda581a22015-10-14 14:10:30 -0600533 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700534 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800535 builder.addCapability(spv::CapabilityDrawParameters);
536 return spv::BuiltInBaseVertex;
537
John Kessenichda581a22015-10-14 14:10:30 -0600538 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700539 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800540 builder.addCapability(spv::CapabilityDrawParameters);
541 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200542
John Kessenichda581a22015-10-14 14:10:30 -0600543 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700544 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800545 builder.addCapability(spv::CapabilityDrawParameters);
546 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200547
548 case glslang::EbvPrimitiveId:
549 if (glslangIntermediate->getStage() == EShLangFragment)
550 builder.addCapability(spv::CapabilityGeometry);
551 return spv::BuiltInPrimitiveId;
552
Rex Xu37cdcee2017-06-29 17:46:34 +0800553 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800554 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
555 builder.addCapability(spv::CapabilityStencilExportEXT);
556 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800557
John Kessenich140f3df2015-06-26 16:58:36 -0600558 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600559 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
560 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
561 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
562 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
563 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
564 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
565 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600566 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
567 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
568 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
569 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
570 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
571 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
572 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
573 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800574
Rex Xu574ab042016-04-14 16:53:07 +0800575 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800576 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
578 return spv::BuiltInSubgroupSize;
579
Rex Xu574ab042016-04-14 16:53:07 +0800580 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800581 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800582 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
583 return spv::BuiltInSubgroupLocalInvocationId;
584
Rex Xu574ab042016-04-14 16:53:07 +0800585 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800586 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
587 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
588 return spv::BuiltInSubgroupEqMaskKHR;
589
Rex Xu574ab042016-04-14 16:53:07 +0800590 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800591 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
592 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
593 return spv::BuiltInSubgroupGeMaskKHR;
594
Rex Xu574ab042016-04-14 16:53:07 +0800595 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800596 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
597 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
598 return spv::BuiltInSubgroupGtMaskKHR;
599
Rex Xu574ab042016-04-14 16:53:07 +0800600 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800601 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
602 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
603 return spv::BuiltInSubgroupLeMaskKHR;
604
Rex Xu574ab042016-04-14 16:53:07 +0800605 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800606 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
607 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
608 return spv::BuiltInSubgroupLtMaskKHR;
609
John Kessenich66011cb2018-03-06 16:12:04 -0700610 case glslang::EbvNumSubgroups:
611 builder.addCapability(spv::CapabilityGroupNonUniform);
612 return spv::BuiltInNumSubgroups;
613
614 case glslang::EbvSubgroupID:
615 builder.addCapability(spv::CapabilityGroupNonUniform);
616 return spv::BuiltInSubgroupId;
617
618 case glslang::EbvSubgroupSize2:
619 builder.addCapability(spv::CapabilityGroupNonUniform);
620 return spv::BuiltInSubgroupSize;
621
622 case glslang::EbvSubgroupInvocation2:
623 builder.addCapability(spv::CapabilityGroupNonUniform);
624 return spv::BuiltInSubgroupLocalInvocationId;
625
626 case glslang::EbvSubgroupEqMask2:
627 builder.addCapability(spv::CapabilityGroupNonUniform);
628 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
629 return spv::BuiltInSubgroupEqMask;
630
631 case glslang::EbvSubgroupGeMask2:
632 builder.addCapability(spv::CapabilityGroupNonUniform);
633 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
634 return spv::BuiltInSubgroupGeMask;
635
636 case glslang::EbvSubgroupGtMask2:
637 builder.addCapability(spv::CapabilityGroupNonUniform);
638 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
639 return spv::BuiltInSubgroupGtMask;
640
641 case glslang::EbvSubgroupLeMask2:
642 builder.addCapability(spv::CapabilityGroupNonUniform);
643 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
644 return spv::BuiltInSubgroupLeMask;
645
646 case glslang::EbvSubgroupLtMask2:
647 builder.addCapability(spv::CapabilityGroupNonUniform);
648 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
649 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800650#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800651 case glslang::EbvBaryCoordNoPersp:
652 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
653 return spv::BuiltInBaryCoordNoPerspAMD;
654
655 case glslang::EbvBaryCoordNoPerspCentroid:
656 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
657 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
658
659 case glslang::EbvBaryCoordNoPerspSample:
660 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
661 return spv::BuiltInBaryCoordNoPerspSampleAMD;
662
663 case glslang::EbvBaryCoordSmooth:
664 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
665 return spv::BuiltInBaryCoordSmoothAMD;
666
667 case glslang::EbvBaryCoordSmoothCentroid:
668 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
669 return spv::BuiltInBaryCoordSmoothCentroidAMD;
670
671 case glslang::EbvBaryCoordSmoothSample:
672 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
673 return spv::BuiltInBaryCoordSmoothSampleAMD;
674
675 case glslang::EbvBaryCoordPullModel:
676 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
677 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800678#endif
chaoc771d89f2017-01-13 01:10:53 -0800679
John Kessenich6c8aaac2017-02-27 01:20:51 -0700680 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700682 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700683 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700684
685 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700687 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700688 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700689
chaoc771d89f2017-01-13 01:10:53 -0800690#ifdef NV_EXTENSIONS
691 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800692 if (!memberDeclaration) {
693 builder.addExtension(spv::E_SPV_NV_viewport_array2);
694 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
695 }
chaoc771d89f2017-01-13 01:10:53 -0800696 return spv::BuiltInViewportMaskNV;
697 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800698 if (!memberDeclaration) {
699 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
700 builder.addCapability(spv::CapabilityShaderStereoViewNV);
701 }
chaoc771d89f2017-01-13 01:10:53 -0800702 return spv::BuiltInSecondaryPositionNV;
703 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800704 if (!memberDeclaration) {
705 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
706 builder.addCapability(spv::CapabilityShaderStereoViewNV);
707 }
chaoc771d89f2017-01-13 01:10:53 -0800708 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800709 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800710 if (!memberDeclaration) {
711 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
712 builder.addCapability(spv::CapabilityPerViewAttributesNV);
713 }
chaocdf3956c2017-02-14 14:52:34 -0800714 return spv::BuiltInPositionPerViewNV;
715 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800716 if (!memberDeclaration) {
717 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
718 builder.addCapability(spv::CapabilityPerViewAttributesNV);
719 }
chaocdf3956c2017-02-14 14:52:34 -0800720 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700721 case glslang::EbvFragFullyCoveredNV:
722 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
723 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
724 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800725#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800726 default:
727 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600728 }
729}
730
Rex Xufc618912015-09-09 16:42:49 +0800731// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700732spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800733{
734 assert(type.getBasicType() == glslang::EbtSampler);
735
John Kessenich5d0fa972016-02-15 11:57:00 -0700736 // Check for capabilities
737 switch (type.getQualifier().layoutFormat) {
738 case glslang::ElfRg32f:
739 case glslang::ElfRg16f:
740 case glslang::ElfR11fG11fB10f:
741 case glslang::ElfR16f:
742 case glslang::ElfRgba16:
743 case glslang::ElfRgb10A2:
744 case glslang::ElfRg16:
745 case glslang::ElfRg8:
746 case glslang::ElfR16:
747 case glslang::ElfR8:
748 case glslang::ElfRgba16Snorm:
749 case glslang::ElfRg16Snorm:
750 case glslang::ElfRg8Snorm:
751 case glslang::ElfR16Snorm:
752 case glslang::ElfR8Snorm:
753
754 case glslang::ElfRg32i:
755 case glslang::ElfRg16i:
756 case glslang::ElfRg8i:
757 case glslang::ElfR16i:
758 case glslang::ElfR8i:
759
760 case glslang::ElfRgb10a2ui:
761 case glslang::ElfRg32ui:
762 case glslang::ElfRg16ui:
763 case glslang::ElfRg8ui:
764 case glslang::ElfR16ui:
765 case glslang::ElfR8ui:
766 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
767 break;
768
769 default:
770 break;
771 }
772
773 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800774 switch (type.getQualifier().layoutFormat) {
775 case glslang::ElfNone: return spv::ImageFormatUnknown;
776 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
777 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
778 case glslang::ElfR32f: return spv::ImageFormatR32f;
779 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
780 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
781 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
782 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
783 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
784 case glslang::ElfR16f: return spv::ImageFormatR16f;
785 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
786 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
787 case glslang::ElfRg16: return spv::ImageFormatRg16;
788 case glslang::ElfRg8: return spv::ImageFormatRg8;
789 case glslang::ElfR16: return spv::ImageFormatR16;
790 case glslang::ElfR8: return spv::ImageFormatR8;
791 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
792 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
793 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
794 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
795 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
796 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
797 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
798 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
799 case glslang::ElfR32i: return spv::ImageFormatR32i;
800 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
801 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
802 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
803 case glslang::ElfR16i: return spv::ImageFormatR16i;
804 case glslang::ElfR8i: return spv::ImageFormatR8i;
805 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
806 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
807 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
808 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
809 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
810 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
811 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
812 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
813 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
814 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600815 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800816 }
817}
818
John Kesseniche18fd202018-01-30 11:01:39 -0700819spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800820{
John Kesseniche18fd202018-01-30 11:01:39 -0700821 if (selectionNode.getFlatten())
822 return spv::SelectionControlFlattenMask;
823 if (selectionNode.getDontFlatten())
824 return spv::SelectionControlDontFlattenMask;
825 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800826}
827
John Kesseniche18fd202018-01-30 11:01:39 -0700828spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600829{
John Kesseniche18fd202018-01-30 11:01:39 -0700830 if (switchNode.getFlatten())
831 return spv::SelectionControlFlattenMask;
832 if (switchNode.getDontFlatten())
833 return spv::SelectionControlDontFlattenMask;
834 return spv::SelectionControlMaskNone;
835}
836
John Kessenicha2858d92018-01-31 08:11:18 -0700837// return a non-0 dependency if the dependency argument must be set
838spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
839 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700840{
841 spv::LoopControlMask control = spv::LoopControlMaskNone;
842
843 if (loopNode.getDontUnroll())
844 control = control | spv::LoopControlDontUnrollMask;
845 if (loopNode.getUnroll())
846 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700847 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700848 control = control | spv::LoopControlDependencyInfiniteMask;
849 else if (loopNode.getLoopDependency() > 0) {
850 control = control | spv::LoopControlDependencyLengthMask;
851 dependencyLength = loopNode.getLoopDependency();
852 }
John Kesseniche18fd202018-01-30 11:01:39 -0700853
854 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600855}
856
John Kessenicha5c5fb62017-05-05 05:09:58 -0600857// Translate glslang type to SPIR-V storage class.
858spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
859{
860 if (type.getQualifier().isPipeInput())
861 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600862 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600863 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600864
865 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
866 type.getQualifier().storage == glslang::EvqUniform) {
867 if (type.getBasicType() == glslang::EbtAtomicUint)
868 return spv::StorageClassAtomicCounter;
869 if (type.containsOpaque())
870 return spv::StorageClassUniformConstant;
871 }
872
873 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700874 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600875 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600876 }
877
878 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600879 if (type.getQualifier().layoutPushConstant)
880 return spv::StorageClassPushConstant;
881 if (type.getBasicType() == glslang::EbtBlock)
882 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600883 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600884 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600885
886 switch (type.getQualifier().storage) {
887 case glslang::EvqShared: return spv::StorageClassWorkgroup;
888 case glslang::EvqGlobal: return spv::StorageClassPrivate;
889 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
890 case glslang::EvqTemporary: return spv::StorageClassFunction;
891 default:
892 assert(0);
893 break;
894 }
895
896 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600897}
898
John Kessenich5611c6d2018-04-05 11:25:02 -0600899// Add capabilities pertaining to how an array is indexed.
900void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
901 const glslang::TType& indexType)
902{
903 if (indexType.getQualifier().isNonUniform()) {
904 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -0500905 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -0600906 if (baseType.getBasicType() == glslang::EbtSampler) {
907 if (baseType.getQualifier().hasAttachment())
908 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
909 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
910 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
911 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
912 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
913 else if (baseType.isImage())
914 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
915 else if (baseType.isTexture())
916 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
917 } else if (baseType.getBasicType() == glslang::EbtBlock) {
918 if (baseType.getQualifier().storage == glslang::EvqBuffer)
919 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
920 else if (baseType.getQualifier().storage == glslang::EvqUniform)
921 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
922 }
923 } else {
924 // assume a dynamically uniform index
925 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -0500926 if (baseType.getQualifier().hasAttachment()) {
927 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600928 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500929 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
930 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600931 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500932 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
933 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600934 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500935 }
John Kessenich5611c6d2018-04-05 11:25:02 -0600936 }
937 }
938}
939
qining25262b32016-05-06 17:25:16 -0400940// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700941// descriptor set.
942bool IsDescriptorResource(const glslang::TType& type)
943{
John Kessenichf7497e22016-03-08 21:36:22 -0700944 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700945 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700946 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700947
948 // non block...
949 // basically samplerXXX/subpass/sampler/texture are all included
950 // if they are the global-scope-class, not the function parameter
951 // (or local, if they ever exist) class.
952 if (type.getBasicType() == glslang::EbtSampler)
953 return type.getQualifier().isUniformOrBuffer();
954
955 // None of the above.
956 return false;
957}
958
John Kesseniche0b6cad2015-12-24 10:30:13 -0700959void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
960{
961 if (child.layoutMatrix == glslang::ElmNone)
962 child.layoutMatrix = parent.layoutMatrix;
963
964 if (parent.invariant)
965 child.invariant = true;
966 if (parent.nopersp)
967 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800968#ifdef AMD_EXTENSIONS
969 if (parent.explicitInterp)
970 child.explicitInterp = true;
971#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700972 if (parent.flat)
973 child.flat = true;
974 if (parent.centroid)
975 child.centroid = true;
976 if (parent.patch)
977 child.patch = true;
978 if (parent.sample)
979 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800980 if (parent.coherent)
981 child.coherent = true;
982 if (parent.volatil)
983 child.volatil = true;
984 if (parent.restrict)
985 child.restrict = true;
986 if (parent.readonly)
987 child.readonly = true;
988 if (parent.writeonly)
989 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700990}
991
John Kessenichf2b7f332016-09-01 17:05:23 -0600992bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700993{
John Kessenich7b9fa252016-01-21 18:56:57 -0700994 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600995 // - struct members might inherit from a struct declaration
996 // (note that non-block structs don't explicitly inherit,
997 // only implicitly, meaning no decoration involved)
998 // - affect decorations on the struct members
999 // (note smooth does not, and expecting something like volatile
1000 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001001 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001002 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001003}
1004
John Kessenich140f3df2015-06-26 16:58:36 -06001005//
1006// Implement the TGlslangToSpvTraverser class.
1007//
1008
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001009TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001010 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1011 : TIntermTraverser(true, false, true),
1012 options(options),
1013 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001014 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001015 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001016 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001017 glslangIntermediate(glslangIntermediate)
1018{
1019 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1020
1021 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001022 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1023 glslangIntermediate->getVersion());
1024
John Kessenich121853f2017-05-31 17:11:16 -06001025 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001026 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001027 builder.setSourceFile(glslangIntermediate->getSourceFile());
1028
1029 // Set the source shader's text. If for SPV version 1.0, include
1030 // a preamble in comments stating the OpModuleProcessed instructions.
1031 // Otherwise, emit those as actual instructions.
1032 std::string text;
1033 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1034 for (int p = 0; p < (int)processes.size(); ++p) {
1035 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1036 text.append("// OpModuleProcessed ");
1037 text.append(processes[p]);
1038 text.append("\n");
1039 } else
1040 builder.addModuleProcessed(processes[p]);
1041 }
1042 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1043 text.append("#line 1\n");
1044 text.append(glslangIntermediate->getSourceText());
1045 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001046 }
John Kessenich140f3df2015-06-26 16:58:36 -06001047 stdBuiltins = builder.import("GLSL.std.450");
1048 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001049 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1050 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001051
1052 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001053 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1054 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001055 builder.addSourceExtension(it->c_str());
1056
1057 // Add the top-level modes for this shader.
1058
John Kessenich92187592016-02-01 13:45:25 -07001059 if (glslangIntermediate->getXfbMode()) {
1060 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001061 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001062 }
John Kessenich140f3df2015-06-26 16:58:36 -06001063
1064 unsigned int mode;
1065 switch (glslangIntermediate->getStage()) {
1066 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001067 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001068 break;
1069
steve-lunarge7412492017-03-23 11:56:07 -06001070 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001071 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001072 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001073
steve-lunarge7412492017-03-23 11:56:07 -06001074 glslang::TLayoutGeometry primitive;
1075
1076 if (glslangIntermediate->getStage() == EShLangTessControl) {
1077 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1078 primitive = glslangIntermediate->getOutputPrimitive();
1079 } else {
1080 primitive = glslangIntermediate->getInputPrimitive();
1081 }
1082
1083 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001084 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1085 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1086 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001087 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001088 }
John Kessenich4016e382016-07-15 11:53:56 -06001089 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001090 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1091
John Kesseniche6903322015-10-13 16:29:02 -06001092 switch (glslangIntermediate->getVertexSpacing()) {
1093 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1094 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1095 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001096 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001097 }
John Kessenich4016e382016-07-15 11:53:56 -06001098 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001099 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1100
1101 switch (glslangIntermediate->getVertexOrder()) {
1102 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1103 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001104 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001105 }
John Kessenich4016e382016-07-15 11:53:56 -06001106 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001107 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1108
1109 if (glslangIntermediate->getPointMode())
1110 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001111 break;
1112
1113 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001114 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001115 switch (glslangIntermediate->getInputPrimitive()) {
1116 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1117 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1118 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001119 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001120 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001121 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001122 }
John Kessenich4016e382016-07-15 11:53:56 -06001123 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001124 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001125
John Kessenich140f3df2015-06-26 16:58:36 -06001126 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1127
1128 switch (glslangIntermediate->getOutputPrimitive()) {
1129 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1130 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1131 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001132 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001133 }
John Kessenich4016e382016-07-15 11:53:56 -06001134 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001135 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1136 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1137 break;
1138
1139 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001140 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001141 if (glslangIntermediate->getPixelCenterInteger())
1142 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001143
John Kessenich140f3df2015-06-26 16:58:36 -06001144 if (glslangIntermediate->getOriginUpperLeft())
1145 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001146 else
1147 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001148
1149 if (glslangIntermediate->getEarlyFragmentTests())
1150 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1151
chaocc1204522017-06-30 17:14:30 -07001152 if (glslangIntermediate->getPostDepthCoverage()) {
1153 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1154 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1155 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1156 }
1157
John Kesseniche6903322015-10-13 16:29:02 -06001158 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001159 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1160 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001161 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001162 }
John Kessenich4016e382016-07-15 11:53:56 -06001163 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001164 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1165
1166 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1167 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001168 break;
1169
1170 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001171 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001172 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1173 glslangIntermediate->getLocalSize(1),
1174 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001175 break;
1176
1177 default:
1178 break;
1179 }
John Kessenich140f3df2015-06-26 16:58:36 -06001180}
1181
John Kessenichfca82622016-11-26 13:23:20 -07001182// Finish creating SPV, after the traversal is complete.
1183void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001184{
John Kessenichf04c51b2018-08-03 15:56:12 -06001185 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001186 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001187 builder.setBuildPoint(shaderEntry->getLastBlock());
1188 builder.leaveFunction();
1189 }
1190
John Kessenich7ba63412015-12-20 17:37:07 -07001191 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001192 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1193 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001194
John Kessenichf04c51b2018-08-03 15:56:12 -06001195 // Add capabilities, extensions, remove unneeded decorations, etc.,
1196 // based on the resulting SPIR-V.
1197 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001198}
1199
John Kessenichfca82622016-11-26 13:23:20 -07001200// Write the SPV into 'out'.
1201void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001202{
John Kessenichfca82622016-11-26 13:23:20 -07001203 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001204}
1205
1206//
1207// Implement the traversal functions.
1208//
1209// Return true from interior nodes to have the external traversal
1210// continue on to children. Return false if children were
1211// already processed.
1212//
1213
1214//
qining25262b32016-05-06 17:25:16 -04001215// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001216// - uniform/input reads
1217// - output writes
1218// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1219// - something simple that degenerates into the last bullet
1220//
1221void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1222{
qining75d1d802016-04-06 14:42:01 -04001223 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1224 if (symbol->getType().getQualifier().isSpecConstant())
1225 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1226
John Kessenich140f3df2015-06-26 16:58:36 -06001227 // getSymbolId() will set up all the IO decorations on the first call.
1228 // Formal function parameters were mapped during makeFunctions().
1229 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001230
1231 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1232 if (builder.isPointer(id)) {
1233 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001234 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1235 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1236 iOSet.insert(id);
1237 }
John Kessenich7ba63412015-12-20 17:37:07 -07001238 }
1239
1240 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001241 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001242 // Prepare to generate code for the access
1243
1244 // L-value chains will be computed left to right. We're on the symbol now,
1245 // which is the left-most part of the access chain, so now is "clear" time,
1246 // followed by setting the base.
1247 builder.clearAccessChain();
1248
1249 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001250 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001251 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001252 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001253 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001254 // These are also pure R-values.
1255 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001256 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001257 builder.setAccessChainRValue(id);
1258 else
1259 builder.setAccessChainLValue(id);
1260 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001261
1262 // Process linkage-only nodes for any special additional interface work.
1263 if (linkageOnly) {
1264 if (glslangIntermediate->getHlslFunctionality1()) {
1265 // Map implicit counter buffers to their originating buffers, which should have been
1266 // seen by now, given earlier pruning of unused counters, and preservation of order
1267 // of declaration.
1268 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1269 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1270 // Save possible originating buffers for counter buffers, keyed by
1271 // making the potential counter-buffer name.
1272 std::string keyName = symbol->getName().c_str();
1273 keyName = glslangIntermediate->addCounterBufferName(keyName);
1274 counterOriginator[keyName] = symbol;
1275 } else {
1276 // Handle a counter buffer, by finding the saved originating buffer.
1277 std::string keyName = symbol->getName().c_str();
1278 auto it = counterOriginator.find(keyName);
1279 if (it != counterOriginator.end()) {
1280 id = getSymbolId(it->second);
1281 if (id != spv::NoResult) {
1282 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001283 if (counterId != spv::NoResult) {
1284 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001285 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001286 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001287 }
1288 }
1289 }
1290 }
1291 }
1292 }
John Kessenich140f3df2015-06-26 16:58:36 -06001293}
1294
1295bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1296{
John Kesseniche485c7a2017-05-31 18:50:53 -06001297 builder.setLine(node->getLoc().line);
1298
qining40887662016-04-03 22:20:42 -04001299 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1300 if (node->getType().getQualifier().isSpecConstant())
1301 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1302
John Kessenich140f3df2015-06-26 16:58:36 -06001303 // First, handle special cases
1304 switch (node->getOp()) {
1305 case glslang::EOpAssign:
1306 case glslang::EOpAddAssign:
1307 case glslang::EOpSubAssign:
1308 case glslang::EOpMulAssign:
1309 case glslang::EOpVectorTimesMatrixAssign:
1310 case glslang::EOpVectorTimesScalarAssign:
1311 case glslang::EOpMatrixTimesScalarAssign:
1312 case glslang::EOpMatrixTimesMatrixAssign:
1313 case glslang::EOpDivAssign:
1314 case glslang::EOpModAssign:
1315 case glslang::EOpAndAssign:
1316 case glslang::EOpInclusiveOrAssign:
1317 case glslang::EOpExclusiveOrAssign:
1318 case glslang::EOpLeftShiftAssign:
1319 case glslang::EOpRightShiftAssign:
1320 // A bin-op assign "a += b" means the same thing as "a = a + b"
1321 // where a is evaluated before b. For a simple assignment, GLSL
1322 // says to evaluate the left before the right. So, always, left
1323 // node then right node.
1324 {
1325 // get the left l-value, save it away
1326 builder.clearAccessChain();
1327 node->getLeft()->traverse(this);
1328 spv::Builder::AccessChain lValue = builder.getAccessChain();
1329
1330 // evaluate the right
1331 builder.clearAccessChain();
1332 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001333 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001334
1335 if (node->getOp() != glslang::EOpAssign) {
1336 // the left is also an r-value
1337 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001338 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001339
1340 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001341 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001342 TranslateNoContractionDecoration(node->getType().getQualifier()),
1343 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001344 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001345 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1346 node->getType().getBasicType());
1347
1348 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001349 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001350 }
1351
1352 // store the result
1353 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001354 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 // assignments are expressions having an rValue after they are evaluated...
1357 builder.clearAccessChain();
1358 builder.setAccessChainRValue(rValue);
1359 }
1360 return false;
1361 case glslang::EOpIndexDirect:
1362 case glslang::EOpIndexDirectStruct:
1363 {
1364 // Get the left part of the access chain.
1365 node->getLeft()->traverse(this);
1366
1367 // Add the next element in the chain
1368
David Netoa901ffe2016-06-08 14:11:40 +01001369 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001370 if (! node->getLeft()->getType().isArray() &&
1371 node->getLeft()->getType().isVector() &&
1372 node->getOp() == glslang::EOpIndexDirect) {
1373 // This is essentially a hard-coded vector swizzle of size 1,
1374 // so short circuit the access-chain stuff with a swizzle.
1375 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001376 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001377 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001378 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001379 int spvIndex = glslangIndex;
1380 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1381 node->getOp() == glslang::EOpIndexDirectStruct)
1382 {
1383 // This may be, e.g., an anonymous block-member selection, which generally need
1384 // index remapping due to hidden members in anonymous blocks.
1385 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1386 assert(remapper.size() > 0);
1387 spvIndex = remapper[glslangIndex];
1388 }
John Kessenichebb50532016-05-16 19:22:05 -06001389
David Netoa901ffe2016-06-08 14:11:40 +01001390 // normal case for indexing array or structure or block
1391 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1392
1393 // Add capabilities here for accessing PointSize and clip/cull distance.
1394 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001395 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001396 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001397 }
1398 }
1399 return false;
1400 case glslang::EOpIndexIndirect:
1401 {
1402 // Structure or array or vector indirection.
1403 // Will use native SPIR-V access-chain for struct and array indirection;
1404 // matrices are arrays of vectors, so will also work for a matrix.
1405 // Will use the access chain's 'component' for variable index into a vector.
1406
1407 // This adapter is building access chains left to right.
1408 // Set up the access chain to the left.
1409 node->getLeft()->traverse(this);
1410
1411 // save it so that computing the right side doesn't trash it
1412 spv::Builder::AccessChain partial = builder.getAccessChain();
1413
1414 // compute the next index in the chain
1415 builder.clearAccessChain();
1416 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001417 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001418
John Kessenich5611c6d2018-04-05 11:25:02 -06001419 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1420
John Kessenich140f3df2015-06-26 16:58:36 -06001421 // restore the saved access chain
1422 builder.setAccessChain(partial);
1423
1424 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001425 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001426 else
John Kessenichfa668da2015-09-13 14:46:30 -06001427 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001428 }
1429 return false;
1430 case glslang::EOpVectorSwizzle:
1431 {
1432 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001433 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001434 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001435 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001436 }
1437 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001438 case glslang::EOpMatrixSwizzle:
1439 logger->missingFunctionality("matrix swizzle");
1440 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001441 case glslang::EOpLogicalOr:
1442 case glslang::EOpLogicalAnd:
1443 {
1444
1445 // These may require short circuiting, but can sometimes be done as straight
1446 // binary operations. The right operand must be short circuited if it has
1447 // side effects, and should probably be if it is complex.
1448 if (isTrivial(node->getRight()->getAsTyped()))
1449 break; // handle below as a normal binary operation
1450 // otherwise, we need to do dynamic short circuiting on the right operand
1451 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1452 builder.clearAccessChain();
1453 builder.setAccessChainRValue(result);
1454 }
1455 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001456 default:
1457 break;
1458 }
1459
1460 // Assume generic binary op...
1461
John Kessenich32cfd492016-02-02 12:37:46 -07001462 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001463 builder.clearAccessChain();
1464 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001465 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001466
John Kessenich32cfd492016-02-02 12:37:46 -07001467 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001468 builder.clearAccessChain();
1469 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001470 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001471
John Kessenich32cfd492016-02-02 12:37:46 -07001472 // get result
John Kessenichead86222018-03-28 18:01:20 -06001473 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001474 TranslateNoContractionDecoration(node->getType().getQualifier()),
1475 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001476 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001477 convertGlslangToSpvType(node->getType()), left, right,
1478 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001479
John Kessenich50e57562015-12-21 21:21:11 -07001480 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001481 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001482 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001483 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001484 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001485 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001486 return false;
1487 }
John Kessenich140f3df2015-06-26 16:58:36 -06001488}
1489
1490bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1491{
John Kesseniche485c7a2017-05-31 18:50:53 -06001492 builder.setLine(node->getLoc().line);
1493
qining40887662016-04-03 22:20:42 -04001494 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1495 if (node->getType().getQualifier().isSpecConstant())
1496 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1497
John Kessenichfc51d282015-08-19 13:34:18 -06001498 spv::Id result = spv::NoResult;
1499
1500 // try texturing first
1501 result = createImageTextureFunctionCall(node);
1502 if (result != spv::NoResult) {
1503 builder.clearAccessChain();
1504 builder.setAccessChainRValue(result);
1505
1506 return false; // done with this node
1507 }
1508
1509 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001510
1511 if (node->getOp() == glslang::EOpArrayLength) {
1512 // Quite special; won't want to evaluate the operand.
1513
John Kessenich5611c6d2018-04-05 11:25:02 -06001514 // Currently, the front-end does not allow .length() on an array until it is sized,
1515 // except for the last block membeor of an SSBO.
1516 // TODO: If this changes, link-time sized arrays might show up here, and need their
1517 // size extracted.
1518
John Kessenichc9a80832015-09-12 12:17:44 -06001519 // Normal .length() would have been constant folded by the front-end.
1520 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001521 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001522
John Kessenichc9a80832015-09-12 12:17:44 -06001523 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1524 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001525 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1526 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001527
1528 builder.clearAccessChain();
1529 builder.setAccessChainRValue(length);
1530
1531 return false;
1532 }
1533
John Kessenichfc51d282015-08-19 13:34:18 -06001534 // Start by evaluating the operand
1535
John Kessenich8c8505c2016-07-26 12:50:38 -06001536 // Does it need a swizzle inversion? If so, evaluation is inverted;
1537 // operate first on the swizzle base, then apply the swizzle.
1538 spv::Id invertedType = spv::NoType;
1539 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1540 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1541 invertedType = getInvertedSwizzleType(*node->getOperand());
1542
John Kessenich140f3df2015-06-26 16:58:36 -06001543 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001544 if (invertedType != spv::NoType)
1545 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1546 else
1547 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001548
Rex Xufc618912015-09-09 16:42:49 +08001549 spv::Id operand = spv::NoResult;
1550
1551 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1552 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001553 node->getOp() == glslang::EOpAtomicCounter ||
1554 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001555 operand = builder.accessChainGetLValue(); // Special case l-value operands
1556 else
John Kessenich32cfd492016-02-02 12:37:46 -07001557 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001558
John Kessenichead86222018-03-28 18:01:20 -06001559 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001560 TranslateNoContractionDecoration(node->getType().getQualifier()),
1561 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001562
1563 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001564 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001565 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001566
1567 // if not, then possibly an operation
1568 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001569 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001570
1571 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001572 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001573 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001574 builder.addDecoration(result, decorations.nonUniform);
1575 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001576
John Kessenich140f3df2015-06-26 16:58:36 -06001577 builder.clearAccessChain();
1578 builder.setAccessChainRValue(result);
1579
1580 return false; // done with this node
1581 }
1582
1583 // it must be a special case, check...
1584 switch (node->getOp()) {
1585 case glslang::EOpPostIncrement:
1586 case glslang::EOpPostDecrement:
1587 case glslang::EOpPreIncrement:
1588 case glslang::EOpPreDecrement:
1589 {
1590 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001591 spv::Id one = 0;
1592 if (node->getBasicType() == glslang::EbtFloat)
1593 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001594 else if (node->getBasicType() == glslang::EbtDouble)
1595 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001596 else if (node->getBasicType() == glslang::EbtFloat16)
1597 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001598 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1599 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001600 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1601 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001602 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1603 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001604 else
1605 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001606 glslang::TOperator op;
1607 if (node->getOp() == glslang::EOpPreIncrement ||
1608 node->getOp() == glslang::EOpPostIncrement)
1609 op = glslang::EOpAdd;
1610 else
1611 op = glslang::EOpSub;
1612
John Kessenichead86222018-03-28 18:01:20 -06001613 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001614 convertGlslangToSpvType(node->getType()), operand, one,
1615 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001616 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001617
1618 // The result of operation is always stored, but conditionally the
1619 // consumed result. The consumed result is always an r-value.
1620 builder.accessChainStore(result);
1621 builder.clearAccessChain();
1622 if (node->getOp() == glslang::EOpPreIncrement ||
1623 node->getOp() == glslang::EOpPreDecrement)
1624 builder.setAccessChainRValue(result);
1625 else
1626 builder.setAccessChainRValue(operand);
1627 }
1628
1629 return false;
1630
1631 case glslang::EOpEmitStreamVertex:
1632 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1633 return false;
1634 case glslang::EOpEndStreamPrimitive:
1635 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1636 return false;
1637
1638 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001639 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001640 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001641 }
John Kessenich140f3df2015-06-26 16:58:36 -06001642}
1643
1644bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1645{
qining27e04a02016-04-14 16:40:20 -04001646 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1647 if (node->getType().getQualifier().isSpecConstant())
1648 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1649
John Kessenichfc51d282015-08-19 13:34:18 -06001650 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001651 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1652 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001653
1654 // try texturing
1655 result = createImageTextureFunctionCall(node);
1656 if (result != spv::NoResult) {
1657 builder.clearAccessChain();
1658 builder.setAccessChainRValue(result);
1659
1660 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001661#ifdef AMD_EXTENSIONS
1662 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1663#else
John Kessenich56bab042015-09-16 10:54:31 -06001664 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001665#endif
Rex Xufc618912015-09-09 16:42:49 +08001666 // "imageStore" is a special case, which has no result
1667 return false;
1668 }
John Kessenichfc51d282015-08-19 13:34:18 -06001669
John Kessenich140f3df2015-06-26 16:58:36 -06001670 glslang::TOperator binOp = glslang::EOpNull;
1671 bool reduceComparison = true;
1672 bool isMatrix = false;
1673 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001674 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001675
1676 assert(node->getOp());
1677
John Kessenichf6640762016-08-01 19:44:00 -06001678 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001679
1680 switch (node->getOp()) {
1681 case glslang::EOpSequence:
1682 {
1683 if (preVisit)
1684 ++sequenceDepth;
1685 else
1686 --sequenceDepth;
1687
1688 if (sequenceDepth == 1) {
1689 // If this is the parent node of all the functions, we want to see them
1690 // early, so all call points have actual SPIR-V functions to reference.
1691 // In all cases, still let the traverser visit the children for us.
1692 makeFunctions(node->getAsAggregate()->getSequence());
1693
John Kessenich6fccb3c2016-09-19 16:01:41 -06001694 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001695 // anything else gets there, so visit out of order, doing them all now.
1696 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1697
John Kessenich6a60c2f2016-12-08 21:01:59 -07001698 // 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 -06001699 // so do them manually.
1700 visitFunctions(node->getAsAggregate()->getSequence());
1701
1702 return false;
1703 }
1704
1705 return true;
1706 }
1707 case glslang::EOpLinkerObjects:
1708 {
1709 if (visit == glslang::EvPreVisit)
1710 linkageOnly = true;
1711 else
1712 linkageOnly = false;
1713
1714 return true;
1715 }
1716 case glslang::EOpComma:
1717 {
1718 // processing from left to right naturally leaves the right-most
1719 // lying around in the access chain
1720 glslang::TIntermSequence& glslangOperands = node->getSequence();
1721 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1722 glslangOperands[i]->traverse(this);
1723
1724 return false;
1725 }
1726 case glslang::EOpFunction:
1727 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001728 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001729 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001730 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001731 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001732 } else {
1733 handleFunctionEntry(node);
1734 }
1735 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001736 if (inEntryPoint)
1737 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001738 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001739 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001740 }
1741
1742 return true;
1743 case glslang::EOpParameters:
1744 // Parameters will have been consumed by EOpFunction processing, but not
1745 // the body, so we still visited the function node's children, making this
1746 // child redundant.
1747 return false;
1748 case glslang::EOpFunctionCall:
1749 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001750 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001751 if (node->isUserDefined())
1752 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001753 // 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 -07001754 if (result) {
1755 builder.clearAccessChain();
1756 builder.setAccessChainRValue(result);
1757 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001758 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001759
1760 return false;
1761 }
1762 case glslang::EOpConstructMat2x2:
1763 case glslang::EOpConstructMat2x3:
1764 case glslang::EOpConstructMat2x4:
1765 case glslang::EOpConstructMat3x2:
1766 case glslang::EOpConstructMat3x3:
1767 case glslang::EOpConstructMat3x4:
1768 case glslang::EOpConstructMat4x2:
1769 case glslang::EOpConstructMat4x3:
1770 case glslang::EOpConstructMat4x4:
1771 case glslang::EOpConstructDMat2x2:
1772 case glslang::EOpConstructDMat2x3:
1773 case glslang::EOpConstructDMat2x4:
1774 case glslang::EOpConstructDMat3x2:
1775 case glslang::EOpConstructDMat3x3:
1776 case glslang::EOpConstructDMat3x4:
1777 case glslang::EOpConstructDMat4x2:
1778 case glslang::EOpConstructDMat4x3:
1779 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001780 case glslang::EOpConstructIMat2x2:
1781 case glslang::EOpConstructIMat2x3:
1782 case glslang::EOpConstructIMat2x4:
1783 case glslang::EOpConstructIMat3x2:
1784 case glslang::EOpConstructIMat3x3:
1785 case glslang::EOpConstructIMat3x4:
1786 case glslang::EOpConstructIMat4x2:
1787 case glslang::EOpConstructIMat4x3:
1788 case glslang::EOpConstructIMat4x4:
1789 case glslang::EOpConstructUMat2x2:
1790 case glslang::EOpConstructUMat2x3:
1791 case glslang::EOpConstructUMat2x4:
1792 case glslang::EOpConstructUMat3x2:
1793 case glslang::EOpConstructUMat3x3:
1794 case glslang::EOpConstructUMat3x4:
1795 case glslang::EOpConstructUMat4x2:
1796 case glslang::EOpConstructUMat4x3:
1797 case glslang::EOpConstructUMat4x4:
1798 case glslang::EOpConstructBMat2x2:
1799 case glslang::EOpConstructBMat2x3:
1800 case glslang::EOpConstructBMat2x4:
1801 case glslang::EOpConstructBMat3x2:
1802 case glslang::EOpConstructBMat3x3:
1803 case glslang::EOpConstructBMat3x4:
1804 case glslang::EOpConstructBMat4x2:
1805 case glslang::EOpConstructBMat4x3:
1806 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001807 case glslang::EOpConstructF16Mat2x2:
1808 case glslang::EOpConstructF16Mat2x3:
1809 case glslang::EOpConstructF16Mat2x4:
1810 case glslang::EOpConstructF16Mat3x2:
1811 case glslang::EOpConstructF16Mat3x3:
1812 case glslang::EOpConstructF16Mat3x4:
1813 case glslang::EOpConstructF16Mat4x2:
1814 case glslang::EOpConstructF16Mat4x3:
1815 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001816 isMatrix = true;
1817 // fall through
1818 case glslang::EOpConstructFloat:
1819 case glslang::EOpConstructVec2:
1820 case glslang::EOpConstructVec3:
1821 case glslang::EOpConstructVec4:
1822 case glslang::EOpConstructDouble:
1823 case glslang::EOpConstructDVec2:
1824 case glslang::EOpConstructDVec3:
1825 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001826 case glslang::EOpConstructFloat16:
1827 case glslang::EOpConstructF16Vec2:
1828 case glslang::EOpConstructF16Vec3:
1829 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001830 case glslang::EOpConstructBool:
1831 case glslang::EOpConstructBVec2:
1832 case glslang::EOpConstructBVec3:
1833 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001834 case glslang::EOpConstructInt8:
1835 case glslang::EOpConstructI8Vec2:
1836 case glslang::EOpConstructI8Vec3:
1837 case glslang::EOpConstructI8Vec4:
1838 case glslang::EOpConstructUint8:
1839 case glslang::EOpConstructU8Vec2:
1840 case glslang::EOpConstructU8Vec3:
1841 case glslang::EOpConstructU8Vec4:
1842 case glslang::EOpConstructInt16:
1843 case glslang::EOpConstructI16Vec2:
1844 case glslang::EOpConstructI16Vec3:
1845 case glslang::EOpConstructI16Vec4:
1846 case glslang::EOpConstructUint16:
1847 case glslang::EOpConstructU16Vec2:
1848 case glslang::EOpConstructU16Vec3:
1849 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001850 case glslang::EOpConstructInt:
1851 case glslang::EOpConstructIVec2:
1852 case glslang::EOpConstructIVec3:
1853 case glslang::EOpConstructIVec4:
1854 case glslang::EOpConstructUint:
1855 case glslang::EOpConstructUVec2:
1856 case glslang::EOpConstructUVec3:
1857 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001858 case glslang::EOpConstructInt64:
1859 case glslang::EOpConstructI64Vec2:
1860 case glslang::EOpConstructI64Vec3:
1861 case glslang::EOpConstructI64Vec4:
1862 case glslang::EOpConstructUint64:
1863 case glslang::EOpConstructU64Vec2:
1864 case glslang::EOpConstructU64Vec3:
1865 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001866 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001867 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001868 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001869 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001870 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001871 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001872 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001873 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001874 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001875 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001876 std::vector<spv::Id> constituents;
1877 for (int c = 0; c < (int)arguments.size(); ++c)
1878 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001879 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001880 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001881 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001882 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001883 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001884
1885 builder.clearAccessChain();
1886 builder.setAccessChainRValue(constructed);
1887
1888 return false;
1889 }
1890
1891 // These six are component-wise compares with component-wise results.
1892 // Forward on to createBinaryOperation(), requesting a vector result.
1893 case glslang::EOpLessThan:
1894 case glslang::EOpGreaterThan:
1895 case glslang::EOpLessThanEqual:
1896 case glslang::EOpGreaterThanEqual:
1897 case glslang::EOpVectorEqual:
1898 case glslang::EOpVectorNotEqual:
1899 {
1900 // Map the operation to a binary
1901 binOp = node->getOp();
1902 reduceComparison = false;
1903 switch (node->getOp()) {
1904 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1905 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1906 default: binOp = node->getOp(); break;
1907 }
1908
1909 break;
1910 }
1911 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001912 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001913 binOp = glslang::EOpMul;
1914 break;
1915 case glslang::EOpOuterProduct:
1916 // two vectors multiplied to make a matrix
1917 binOp = glslang::EOpOuterProduct;
1918 break;
1919 case glslang::EOpDot:
1920 {
qining25262b32016-05-06 17:25:16 -04001921 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001922 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001923 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001924 binOp = glslang::EOpMul;
1925 break;
1926 }
1927 case glslang::EOpMod:
1928 // when an aggregate, this is the floating-point mod built-in function,
1929 // which can be emitted by the one in createBinaryOperation()
1930 binOp = glslang::EOpMod;
1931 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001932 case glslang::EOpEmitVertex:
1933 case glslang::EOpEndPrimitive:
1934 case glslang::EOpBarrier:
1935 case glslang::EOpMemoryBarrier:
1936 case glslang::EOpMemoryBarrierAtomicCounter:
1937 case glslang::EOpMemoryBarrierBuffer:
1938 case glslang::EOpMemoryBarrierImage:
1939 case glslang::EOpMemoryBarrierShared:
1940 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001941 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001942 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001943 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001944 case glslang::EOpWorkgroupMemoryBarrier:
1945 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001946 case glslang::EOpSubgroupBarrier:
1947 case glslang::EOpSubgroupMemoryBarrier:
1948 case glslang::EOpSubgroupMemoryBarrierBuffer:
1949 case glslang::EOpSubgroupMemoryBarrierImage:
1950 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001951 noReturnValue = true;
1952 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1953 break;
1954
John Kessenich426394d2015-07-23 10:22:48 -06001955 case glslang::EOpAtomicAdd:
1956 case glslang::EOpAtomicMin:
1957 case glslang::EOpAtomicMax:
1958 case glslang::EOpAtomicAnd:
1959 case glslang::EOpAtomicOr:
1960 case glslang::EOpAtomicXor:
1961 case glslang::EOpAtomicExchange:
1962 case glslang::EOpAtomicCompSwap:
1963 atomic = true;
1964 break;
1965
John Kessenich0d0c6d32017-07-23 16:08:26 -06001966 case glslang::EOpAtomicCounterAdd:
1967 case glslang::EOpAtomicCounterSubtract:
1968 case glslang::EOpAtomicCounterMin:
1969 case glslang::EOpAtomicCounterMax:
1970 case glslang::EOpAtomicCounterAnd:
1971 case glslang::EOpAtomicCounterOr:
1972 case glslang::EOpAtomicCounterXor:
1973 case glslang::EOpAtomicCounterExchange:
1974 case glslang::EOpAtomicCounterCompSwap:
1975 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1976 builder.addCapability(spv::CapabilityAtomicStorageOps);
1977 atomic = true;
1978 break;
1979
John Kessenich140f3df2015-06-26 16:58:36 -06001980 default:
1981 break;
1982 }
1983
1984 //
1985 // See if it maps to a regular operation.
1986 //
John Kessenich140f3df2015-06-26 16:58:36 -06001987 if (binOp != glslang::EOpNull) {
1988 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1989 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1990 assert(left && right);
1991
1992 builder.clearAccessChain();
1993 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001994 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001995
1996 builder.clearAccessChain();
1997 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001998 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001999
John Kesseniche485c7a2017-05-31 18:50:53 -06002000 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002001 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002002 TranslateNoContractionDecoration(node->getType().getQualifier()),
2003 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002004 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002005 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002006 left->getType().getBasicType(), reduceComparison);
2007
2008 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002009 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002010 builder.clearAccessChain();
2011 builder.setAccessChainRValue(result);
2012
2013 return false;
2014 }
2015
John Kessenich426394d2015-07-23 10:22:48 -06002016 //
2017 // Create the list of operands.
2018 //
John Kessenich140f3df2015-06-26 16:58:36 -06002019 glslang::TIntermSequence& glslangOperands = node->getSequence();
2020 std::vector<spv::Id> operands;
2021 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002022 // special case l-value operands; there are just a few
2023 bool lvalue = false;
2024 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002025 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002026 case glslang::EOpModf:
2027 if (arg == 1)
2028 lvalue = true;
2029 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002030 case glslang::EOpInterpolateAtSample:
2031 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002032#ifdef AMD_EXTENSIONS
2033 case glslang::EOpInterpolateAtVertex:
2034#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002035 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002036 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002037
2038 // Does it need a swizzle inversion? If so, evaluation is inverted;
2039 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002040 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002041 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2042 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2043 }
Rex Xu7a26c172015-12-08 17:12:09 +08002044 break;
Rex Xud4782c12015-09-06 16:30:11 +08002045 case glslang::EOpAtomicAdd:
2046 case glslang::EOpAtomicMin:
2047 case glslang::EOpAtomicMax:
2048 case glslang::EOpAtomicAnd:
2049 case glslang::EOpAtomicOr:
2050 case glslang::EOpAtomicXor:
2051 case glslang::EOpAtomicExchange:
2052 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002053 case glslang::EOpAtomicCounterAdd:
2054 case glslang::EOpAtomicCounterSubtract:
2055 case glslang::EOpAtomicCounterMin:
2056 case glslang::EOpAtomicCounterMax:
2057 case glslang::EOpAtomicCounterAnd:
2058 case glslang::EOpAtomicCounterOr:
2059 case glslang::EOpAtomicCounterXor:
2060 case glslang::EOpAtomicCounterExchange:
2061 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002062 if (arg == 0)
2063 lvalue = true;
2064 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002065 case glslang::EOpAddCarry:
2066 case glslang::EOpSubBorrow:
2067 if (arg == 2)
2068 lvalue = true;
2069 break;
2070 case glslang::EOpUMulExtended:
2071 case glslang::EOpIMulExtended:
2072 if (arg >= 2)
2073 lvalue = true;
2074 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002075 default:
2076 break;
2077 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002078 builder.clearAccessChain();
2079 if (invertedType != spv::NoType && arg == 0)
2080 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2081 else
2082 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002083 if (lvalue)
2084 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002085 else {
2086 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002087 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002088 }
John Kessenich140f3df2015-06-26 16:58:36 -06002089 }
John Kessenich426394d2015-07-23 10:22:48 -06002090
John Kesseniche485c7a2017-05-31 18:50:53 -06002091 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002092 if (atomic) {
2093 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002094 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002095 } else {
2096 // Pass through to generic operations.
2097 switch (glslangOperands.size()) {
2098 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002099 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002100 break;
2101 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002102 {
2103 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002104 TranslateNoContractionDecoration(node->getType().getQualifier()),
2105 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002106 result = createUnaryOperation(
2107 node->getOp(), decorations,
2108 resultType(), operands.front(),
2109 glslangOperands[0]->getAsTyped()->getBasicType());
2110 }
John Kessenich426394d2015-07-23 10:22:48 -06002111 break;
2112 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002113 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002114 break;
2115 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002116 if (invertedType)
2117 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002118 }
2119
2120 if (noReturnValue)
2121 return false;
2122
2123 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002124 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002125 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002126 } else {
2127 builder.clearAccessChain();
2128 builder.setAccessChainRValue(result);
2129 return false;
2130 }
2131}
2132
John Kessenich433e9ff2017-01-26 20:31:11 -07002133// This path handles both if-then-else and ?:
2134// The if-then-else has a node type of void, while
2135// ?: has either a void or a non-void node type
2136//
2137// Leaving the result, when not void:
2138// GLSL only has r-values as the result of a :?, but
2139// if we have an l-value, that can be more efficient if it will
2140// become the base of a complex r-value expression, because the
2141// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002142bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2143{
John Kessenich4bee5312018-02-20 21:29:05 -07002144 // See if it simple and safe, or required, to execute both sides.
2145 // Crucially, side effects must be either semantically required or avoided,
2146 // and there are performance trade-offs.
2147 // Return true if required or a good idea (and safe) to execute both sides,
2148 // false otherwise.
2149 const auto bothSidesPolicy = [&]() -> bool {
2150 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002151 if (node->getTrueBlock() == nullptr ||
2152 node->getFalseBlock() == nullptr)
2153 return false;
2154
John Kessenich4bee5312018-02-20 21:29:05 -07002155 // required? (unless we write additional code to look for side effects
2156 // and make performance trade-offs if none are present)
2157 if (!node->getShortCircuit())
2158 return true;
2159
2160 // if not required to execute both, decide based on performance/practicality...
2161
2162 // see if OpSelect can handle it
2163 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2164 node->getBasicType() == glslang::EbtVoid)
2165 return false;
2166
John Kessenich433e9ff2017-01-26 20:31:11 -07002167 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2168 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2169
2170 // return true if a single operand to ? : is okay for OpSelect
2171 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002172 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002173 };
2174
2175 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2176 operandOkay(node->getFalseBlock()->getAsTyped());
2177 };
2178
John Kessenich4bee5312018-02-20 21:29:05 -07002179 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2180 // emit the condition before doing anything with selection
2181 node->getCondition()->traverse(this);
2182 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2183
2184 // Find a way of executing both sides and selecting the right result.
2185 const auto executeBothSides = [&]() -> void {
2186 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002187 node->getTrueBlock()->traverse(this);
2188 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2189 node->getFalseBlock()->traverse(this);
2190 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2191
John Kesseniche485c7a2017-05-31 18:50:53 -06002192 builder.setLine(node->getLoc().line);
2193
John Kessenich4bee5312018-02-20 21:29:05 -07002194 // done if void
2195 if (node->getBasicType() == glslang::EbtVoid)
2196 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002197
John Kessenich4bee5312018-02-20 21:29:05 -07002198 // emit code to select between trueValue and falseValue
2199
2200 // see if OpSelect can handle it
2201 if (node->getType().isScalar() || node->getType().isVector()) {
2202 // Emit OpSelect for this selection.
2203
2204 // smear condition to vector, if necessary (AST is always scalar)
2205 if (builder.isVector(trueValue))
2206 condition = builder.smearScalar(spv::NoPrecision, condition,
2207 builder.makeVectorType(builder.makeBoolType(),
2208 builder.getNumComponents(trueValue)));
2209
2210 // OpSelect
2211 result = builder.createTriOp(spv::OpSelect,
2212 convertGlslangToSpvType(node->getType()), condition,
2213 trueValue, falseValue);
2214
2215 builder.clearAccessChain();
2216 builder.setAccessChainRValue(result);
2217 } else {
2218 // We need control flow to select the result.
2219 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2220 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2221
2222 // Selection control:
2223 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2224
2225 // make an "if" based on the value created by the condition
2226 spv::Builder::If ifBuilder(condition, control, builder);
2227
2228 // emit the "then" statement
2229 builder.createStore(trueValue, result);
2230 ifBuilder.makeBeginElse();
2231 // emit the "else" statement
2232 builder.createStore(falseValue, result);
2233
2234 // finish off the control flow
2235 ifBuilder.makeEndIf();
2236
2237 builder.clearAccessChain();
2238 builder.setAccessChainLValue(result);
2239 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002240 };
2241
John Kessenich4bee5312018-02-20 21:29:05 -07002242 // Execute the one side needed, as per the condition
2243 const auto executeOneSide = [&]() {
2244 // Always emit control flow.
2245 if (node->getBasicType() != glslang::EbtVoid)
2246 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002247
John Kessenich4bee5312018-02-20 21:29:05 -07002248 // Selection control:
2249 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2250
2251 // make an "if" based on the value created by the condition
2252 spv::Builder::If ifBuilder(condition, control, builder);
2253
2254 // emit the "then" statement
2255 if (node->getTrueBlock() != nullptr) {
2256 node->getTrueBlock()->traverse(this);
2257 if (result != spv::NoResult)
2258 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2259 }
2260
2261 if (node->getFalseBlock() != nullptr) {
2262 ifBuilder.makeBeginElse();
2263 // emit the "else" statement
2264 node->getFalseBlock()->traverse(this);
2265 if (result != spv::NoResult)
2266 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2267 }
2268
2269 // finish off the control flow
2270 ifBuilder.makeEndIf();
2271
2272 if (result != spv::NoResult) {
2273 builder.clearAccessChain();
2274 builder.setAccessChainLValue(result);
2275 }
2276 };
2277
2278 // Try for OpSelect (or a requirement to execute both sides)
2279 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002280 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2281 if (node->getType().getQualifier().isSpecConstant())
2282 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002283 executeBothSides();
2284 } else
2285 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002286
2287 return false;
2288}
2289
2290bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2291{
2292 // emit and get the condition before doing anything with switch
2293 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002294 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002295
Rex Xu57e65922017-07-04 23:23:40 +08002296 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002297 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002298
John Kessenich140f3df2015-06-26 16:58:36 -06002299 // browse the children to sort out code segments
2300 int defaultSegment = -1;
2301 std::vector<TIntermNode*> codeSegments;
2302 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2303 std::vector<int> caseValues;
2304 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2305 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2306 TIntermNode* child = *c;
2307 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002308 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002309 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002310 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002311 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2312 } else
2313 codeSegments.push_back(child);
2314 }
2315
qining25262b32016-05-06 17:25:16 -04002316 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002317 // statements between the last case and the end of the switch statement
2318 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2319 (int)codeSegments.size() == defaultSegment)
2320 codeSegments.push_back(nullptr);
2321
2322 // make the switch statement
2323 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002324 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002325
2326 // emit all the code in the segments
2327 breakForLoop.push(false);
2328 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2329 builder.nextSwitchSegment(segmentBlocks, s);
2330 if (codeSegments[s])
2331 codeSegments[s]->traverse(this);
2332 else
2333 builder.addSwitchBreak();
2334 }
2335 breakForLoop.pop();
2336
2337 builder.endSwitch(segmentBlocks);
2338
2339 return false;
2340}
2341
2342void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2343{
2344 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002345 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002346
2347 builder.clearAccessChain();
2348 builder.setAccessChainRValue(constant);
2349}
2350
2351bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2352{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002353 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002354 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002355
2356 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002357 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2358 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002359
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002360 // Spec requires back edges to target header blocks, and every header block
2361 // must dominate its merge block. Make a header block first to ensure these
2362 // conditions are met. By definition, it will contain OpLoopMerge, followed
2363 // by a block-ending branch. But we don't want to put any other body/test
2364 // instructions in it, since the body/test may have arbitrary instructions,
2365 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002366 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002367 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002368 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002369 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002370 spv::Block& test = builder.makeNewBlock();
2371 builder.createBranch(&test);
2372
2373 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002374 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002375 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002376 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2377
2378 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002379 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002380 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002381 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002382 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002383 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002384
2385 builder.setBuildPoint(&blocks.continue_target);
2386 if (node->getTerminal())
2387 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002388 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002389 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002390 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002391 builder.createBranch(&blocks.body);
2392
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002393 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002394 builder.setBuildPoint(&blocks.body);
2395 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002396 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002397 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002398 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002399
2400 builder.setBuildPoint(&blocks.continue_target);
2401 if (node->getTerminal())
2402 node->getTerminal()->traverse(this);
2403 if (node->getTest()) {
2404 node->getTest()->traverse(this);
2405 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002406 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002407 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002408 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002409 // TODO: unless there was a break/return/discard instruction
2410 // somewhere in the body, this is an infinite loop, so we should
2411 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002412 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002413 }
John Kessenich140f3df2015-06-26 16:58:36 -06002414 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002415 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002416 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002417 return false;
2418}
2419
2420bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2421{
2422 if (node->getExpression())
2423 node->getExpression()->traverse(this);
2424
John Kesseniche485c7a2017-05-31 18:50:53 -06002425 builder.setLine(node->getLoc().line);
2426
John Kessenich140f3df2015-06-26 16:58:36 -06002427 switch (node->getFlowOp()) {
2428 case glslang::EOpKill:
2429 builder.makeDiscard();
2430 break;
2431 case glslang::EOpBreak:
2432 if (breakForLoop.top())
2433 builder.createLoopExit();
2434 else
2435 builder.addSwitchBreak();
2436 break;
2437 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002438 builder.createLoopContinue();
2439 break;
2440 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002441 if (node->getExpression()) {
2442 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2443 spv::Id returnId = accessChainLoad(glslangReturnType);
2444 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2445 builder.clearAccessChain();
2446 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2447 builder.setAccessChainLValue(copyId);
2448 multiTypeStore(glslangReturnType, returnId);
2449 returnId = builder.createLoad(copyId);
2450 }
2451 builder.makeReturn(false, returnId);
2452 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002453 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002454
2455 builder.clearAccessChain();
2456 break;
2457
2458 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002459 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002460 break;
2461 }
2462
2463 return false;
2464}
2465
2466spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2467{
qining25262b32016-05-06 17:25:16 -04002468 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002469 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002470 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002471 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002472 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002473 }
2474
2475 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002476 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002477 spv::Id spvType = convertGlslangToSpvType(node->getType());
2478
Rex Xucabbb782017-03-24 13:41:14 +08002479 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2480 node->getType().containsBasicType(glslang::EbtInt16) ||
2481 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002482 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002483 switch (storageClass) {
2484 case spv::StorageClassInput:
2485 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002486 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002487 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002488 break;
2489 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002490 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002491 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002492 break;
2493 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002494 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002495 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2496 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002497 else
2498 builder.addCapability(spv::CapabilityStorageUniform16);
2499 break;
2500 case spv::StorageClassStorageBuffer:
2501 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2502 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2503 break;
2504 default:
2505 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002506 }
2507 }
Rex Xuf89ad982017-04-07 23:22:33 +08002508
John Kessenich312dcfb2018-07-03 13:19:51 -06002509 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2510 node->getType().containsBasicType(glslang::EbtUint8);
2511 if (contains8BitType) {
2512 if (storageClass == spv::StorageClassPushConstant) {
2513 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2514 builder.addCapability(spv::CapabilityStoragePushConstant8);
2515 } else if (storageClass == spv::StorageClassUniform) {
2516 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2517 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2518 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2519 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2520 }
2521 }
2522
John Kessenich140f3df2015-06-26 16:58:36 -06002523 const char* name = node->getName().c_str();
2524 if (glslang::IsAnonymous(name))
2525 name = "";
2526
2527 return builder.createVariable(storageClass, spvType, name);
2528}
2529
2530// Return type Id of the sampled type.
2531spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2532{
2533 switch (sampler.type) {
2534 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002535#ifdef AMD_EXTENSIONS
2536 case glslang::EbtFloat16:
2537 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2538 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2539 return builder.makeFloatType(16);
2540#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002541 case glslang::EbtInt: return builder.makeIntType(32);
2542 case glslang::EbtUint: return builder.makeUintType(32);
2543 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002544 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002545 return builder.makeFloatType(32);
2546 }
2547}
2548
John Kessenich8c8505c2016-07-26 12:50:38 -06002549// If node is a swizzle operation, return the type that should be used if
2550// the swizzle base is first consumed by another operation, before the swizzle
2551// is applied.
2552spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2553{
John Kessenichecba76f2017-01-06 00:34:48 -07002554 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002555 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2556 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2557 else
2558 return spv::NoType;
2559}
2560
2561// When inverting a swizzle with a parent op, this function
2562// will apply the swizzle operation to a completed parent operation.
2563spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2564{
2565 std::vector<unsigned> swizzle;
2566 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2567 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2568}
2569
John Kessenich8c8505c2016-07-26 12:50:38 -06002570// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2571void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2572{
2573 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2574 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2575 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2576}
2577
John Kessenich3ac051e2015-12-20 11:29:16 -07002578// Convert from a glslang type to an SPV type, by calling into a
2579// recursive version of this function. This establishes the inherited
2580// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002581spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2582{
John Kessenichead86222018-03-28 18:01:20 -06002583 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002584}
2585
2586// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002587// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002588// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002589spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2590 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002591{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002592 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002593
2594 switch (type.getBasicType()) {
2595 case glslang::EbtVoid:
2596 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002597 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002598 break;
2599 case glslang::EbtFloat:
2600 spvType = builder.makeFloatType(32);
2601 break;
2602 case glslang::EbtDouble:
2603 spvType = builder.makeFloatType(64);
2604 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002605 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002606#if AMD_EXTENSIONS
2607 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2608 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2609#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002610 spvType = builder.makeFloatType(16);
2611 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002612 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002613 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2614 // a 32-bit int where non-0 means true.
2615 if (explicitLayout != glslang::ElpNone)
2616 spvType = builder.makeUintType(32);
2617 else
2618 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002619 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002620 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002621 spvType = builder.makeIntType(8);
2622 break;
2623 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002624 spvType = builder.makeUintType(8);
2625 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002626 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002627#ifdef AMD_EXTENSIONS
2628 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2629 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2630#endif
2631 spvType = builder.makeIntType(16);
2632 break;
2633 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002634#ifdef AMD_EXTENSIONS
2635 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2636 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2637#endif
2638 spvType = builder.makeUintType(16);
2639 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002640 case glslang::EbtInt:
2641 spvType = builder.makeIntType(32);
2642 break;
2643 case glslang::EbtUint:
2644 spvType = builder.makeUintType(32);
2645 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002646 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002647 spvType = builder.makeIntType(64);
2648 break;
2649 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002650 spvType = builder.makeUintType(64);
2651 break;
John Kessenich426394d2015-07-23 10:22:48 -06002652 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002653 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002654 spvType = builder.makeUintType(32);
2655 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002656 case glslang::EbtSampler:
2657 {
2658 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002659 if (sampler.sampler) {
2660 // pure sampler
2661 spvType = builder.makeSamplerType();
2662 } else {
2663 // an image is present, make its type
2664 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2665 sampler.image ? 2 : 1, TranslateImageFormat(type));
2666 if (sampler.combined) {
2667 // already has both image and sampler, make the combined type
2668 spvType = builder.makeSampledImageType(spvType);
2669 }
John Kessenich55e7d112015-11-15 21:33:39 -07002670 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002671 }
John Kessenich140f3df2015-06-26 16:58:36 -06002672 break;
2673 case glslang::EbtStruct:
2674 case glslang::EbtBlock:
2675 {
2676 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002677 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002678
2679 // Try to share structs for different layouts, but not yet for other
2680 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002681 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002682 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002683 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002684 break;
2685
2686 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002687 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002688 memberRemapper[glslangMembers].resize(glslangMembers->size());
2689 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002690 }
2691 break;
2692 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002693 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002694 break;
2695 }
2696
2697 if (type.isMatrix())
2698 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2699 else {
2700 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2701 if (type.getVectorSize() > 1)
2702 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2703 }
2704
2705 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002706 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2707
John Kessenichc9a80832015-09-12 12:17:44 -06002708 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002709 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002710 // We need to decorate array strides for types needing explicit layout, except blocks.
2711 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002712 // Use a dummy glslang type for querying internal strides of
2713 // arrays of arrays, but using just a one-dimensional array.
2714 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002715 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2716 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002717
2718 // Will compute the higher-order strides here, rather than making a whole
2719 // pile of types and doing repetitive recursion on their contents.
2720 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2721 }
John Kessenichf8842e52016-01-04 19:22:56 -07002722
2723 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002724 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002725 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002726 if (stride > 0)
2727 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002728 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002729 }
2730 } else {
2731 // single-dimensional array, and don't yet have stride
2732
John Kessenichf8842e52016-01-04 19:22:56 -07002733 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002734 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2735 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002736 }
John Kessenich31ed4832015-09-09 17:51:38 -06002737
John Kessenichead86222018-03-28 18:01:20 -06002738 // Do the outer dimension, which might not be known for a runtime-sized array.
2739 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2740 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002741 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002742 else {
2743 if (!lastBufferBlockMember) {
2744 builder.addExtension("SPV_EXT_descriptor_indexing");
2745 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2746 }
John Kessenichead86222018-03-28 18:01:20 -06002747 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002748 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002749 if (stride > 0)
2750 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002751 }
2752
2753 return spvType;
2754}
2755
John Kessenich0e737842017-03-24 18:38:16 -06002756// TODO: this functionality should exist at a higher level, in creating the AST
2757//
2758// Identify interface members that don't have their required extension turned on.
2759//
2760bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2761{
2762 auto& extensions = glslangIntermediate->getRequestedExtensions();
2763
Rex Xubcf291a2017-03-29 23:01:36 +08002764 if (member.getFieldName() == "gl_ViewportMask" &&
2765 extensions.find("GL_NV_viewport_array2") == extensions.end())
2766 return true;
2767 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2768 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2769 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002770 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2771 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2772 return true;
2773 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2774 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2775 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002776 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2777 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2778 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002779
2780 return false;
2781};
2782
John Kessenich6090df02016-06-30 21:18:02 -06002783// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2784// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2785// Mutually recursive with convertGlslangToSpvType().
2786spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2787 const glslang::TTypeList* glslangMembers,
2788 glslang::TLayoutPacking explicitLayout,
2789 const glslang::TQualifier& qualifier)
2790{
2791 // Create a vector of struct types for SPIR-V to consume
2792 std::vector<spv::Id> spvMembers;
2793 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06002794 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2795 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2796 if (glslangMember.hiddenMember()) {
2797 ++memberDelta;
2798 if (type.getBasicType() == glslang::EbtBlock)
2799 memberRemapper[glslangMembers][i] = -1;
2800 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002801 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002802 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002803 if (filterMember(glslangMember))
2804 continue;
2805 }
John Kessenich6090df02016-06-30 21:18:02 -06002806 // modify just this child's view of the qualifier
2807 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2808 InheritQualifiers(memberQualifier, qualifier);
2809
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002810 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002811 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002812 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002813
2814 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002815 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2816 i == (int)glslangMembers->size() - 1;
2817 spvMembers.push_back(
2818 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002819 }
2820 }
2821
2822 // Make the SPIR-V type
2823 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002824 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002825 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2826
2827 // Decorate it
2828 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2829
2830 return spvType;
2831}
2832
2833void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2834 const glslang::TTypeList* glslangMembers,
2835 glslang::TLayoutPacking explicitLayout,
2836 const glslang::TQualifier& qualifier,
2837 spv::Id spvType)
2838{
2839 // Name and decorate the non-hidden members
2840 int offset = -1;
2841 int locationOffset = 0; // for use within the members of this struct
2842 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2843 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2844 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002845 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002846 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002847 if (filterMember(glslangMember))
2848 continue;
2849 }
John Kessenich6090df02016-06-30 21:18:02 -06002850
2851 // modify just this child's view of the qualifier
2852 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2853 InheritQualifiers(memberQualifier, qualifier);
2854
2855 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002856 if (member < 0)
2857 continue;
2858
2859 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2860 builder.addMemberDecoration(spvType, member,
2861 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2862 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2863 // Add interpolation and auxiliary storage decorations only to
2864 // top-level members of Input and Output storage classes
2865 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2866 type.getQualifier().storage == glslang::EvqVaryingOut) {
2867 if (type.getBasicType() == glslang::EbtBlock ||
2868 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2869 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2870 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002871 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002872 }
2873 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002874
John Kessenich5d610ee2018-03-07 18:05:55 -07002875 if (type.getBasicType() == glslang::EbtBlock &&
2876 qualifier.storage == glslang::EvqBuffer) {
2877 // Add memory decorations only to top-level members of shader storage block
2878 std::vector<spv::Decoration> memory;
2879 TranslateMemoryDecoration(memberQualifier, memory);
2880 for (unsigned int i = 0; i < memory.size(); ++i)
2881 builder.addMemberDecoration(spvType, member, memory[i]);
2882 }
John Kessenich6090df02016-06-30 21:18:02 -06002883
John Kessenich5d610ee2018-03-07 18:05:55 -07002884 // Location assignment was already completed correctly by the front end,
2885 // just track whether a member needs to be decorated.
2886 // Ignore member locations if the container is an array, as that's
2887 // ill-specified and decisions have been made to not allow this.
2888 if (! type.isArray() && memberQualifier.hasLocation())
2889 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002890
John Kessenich5d610ee2018-03-07 18:05:55 -07002891 if (qualifier.hasLocation()) // track for upcoming inheritance
2892 locationOffset += glslangIntermediate->computeTypeLocationSize(
2893 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002894
John Kessenich5d610ee2018-03-07 18:05:55 -07002895 // component, XFB, others
2896 if (glslangMember.getQualifier().hasComponent())
2897 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2898 glslangMember.getQualifier().layoutComponent);
2899 if (glslangMember.getQualifier().hasXfbOffset())
2900 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2901 glslangMember.getQualifier().layoutXfbOffset);
2902 else if (explicitLayout != glslang::ElpNone) {
2903 // figure out what to do with offset, which is accumulating
2904 int nextOffset;
2905 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2906 if (offset >= 0)
2907 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2908 offset = nextOffset;
2909 }
John Kessenich6090df02016-06-30 21:18:02 -06002910
John Kessenich5d610ee2018-03-07 18:05:55 -07002911 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2912 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2913 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002914
John Kessenich5d610ee2018-03-07 18:05:55 -07002915 // built-in variable decorations
2916 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2917 if (builtIn != spv::BuiltInMax)
2918 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002919
John Kessenich5611c6d2018-04-05 11:25:02 -06002920 // nonuniform
2921 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2922
John Kessenichead86222018-03-28 18:01:20 -06002923 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2924 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2925 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2926 memberQualifier.semanticName);
2927 }
2928
chaoc771d89f2017-01-13 01:10:53 -08002929#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002930 if (builtIn == spv::BuiltInLayer) {
2931 // SPV_NV_viewport_array2 extension
2932 if (glslangMember.getQualifier().layoutViewportRelative){
2933 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2934 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2935 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002936 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002937 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2938 builder.addMemberDecoration(spvType, member,
2939 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2940 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2941 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2942 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002943 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002944 }
2945 if (glslangMember.getQualifier().layoutPassthrough) {
2946 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2947 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2948 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2949 }
chaoc771d89f2017-01-13 01:10:53 -08002950#endif
John Kessenich6090df02016-06-30 21:18:02 -06002951 }
2952
2953 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002954 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2955 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002956 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2957 builder.addCapability(spv::CapabilityGeometryStreams);
2958 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2959 }
John Kessenich6090df02016-06-30 21:18:02 -06002960}
2961
John Kessenich6c292d32016-02-15 20:58:50 -07002962// Turn the expression forming the array size into an id.
2963// This is not quite trivial, because of specialization constants.
2964// Sometimes, a raw constant is turned into an Id, and sometimes
2965// a specialization constant expression is.
2966spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2967{
2968 // First, see if this is sized with a node, meaning a specialization constant:
2969 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2970 if (specNode != nullptr) {
2971 builder.clearAccessChain();
2972 specNode->traverse(this);
2973 return accessChainLoad(specNode->getAsTyped()->getType());
2974 }
qining25262b32016-05-06 17:25:16 -04002975
John Kessenich6c292d32016-02-15 20:58:50 -07002976 // Otherwise, need a compile-time (front end) size, get it:
2977 int size = arraySizes.getDimSize(dim);
2978 assert(size > 0);
2979 return builder.makeUintConstant(size);
2980}
2981
John Kessenich103bef92016-02-08 21:38:15 -07002982// Wrap the builder's accessChainLoad to:
2983// - localize handling of RelaxedPrecision
2984// - use the SPIR-V inferred type instead of another conversion of the glslang type
2985// (avoids unnecessary work and possible type punning for structures)
2986// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002987spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2988{
John Kessenich103bef92016-02-08 21:38:15 -07002989 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06002990 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
2991 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07002992
2993 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002994 if (type.getBasicType() == glslang::EbtBool) {
2995 if (builder.isScalarType(nominalTypeId)) {
2996 // Conversion for bool
2997 spv::Id boolType = builder.makeBoolType();
2998 if (nominalTypeId != boolType)
2999 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3000 } else if (builder.isVectorType(nominalTypeId)) {
3001 // Conversion for bvec
3002 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3003 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3004 if (nominalTypeId != bvecType)
3005 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3006 }
3007 }
John Kessenich103bef92016-02-08 21:38:15 -07003008
3009 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003010}
3011
Rex Xu27253232016-02-23 17:51:09 +08003012// Wrap the builder's accessChainStore to:
3013// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003014//
3015// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003016void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3017{
3018 // Need to convert to abstract types when necessary
3019 if (type.getBasicType() == glslang::EbtBool) {
3020 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3021
3022 if (builder.isScalarType(nominalTypeId)) {
3023 // Conversion for bool
3024 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003025 if (nominalTypeId != boolType) {
3026 // keep these outside arguments, for determinant order-of-evaluation
3027 spv::Id one = builder.makeUintConstant(1);
3028 spv::Id zero = builder.makeUintConstant(0);
3029 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3030 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003031 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003032 } else if (builder.isVectorType(nominalTypeId)) {
3033 // Conversion for bvec
3034 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3035 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003036 if (nominalTypeId != bvecType) {
3037 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003038 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3039 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3040 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003041 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003042 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3043 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003044 }
3045 }
3046
3047 builder.accessChainStore(rvalue);
3048}
3049
John Kessenich4bf71552016-09-02 11:20:21 -06003050// For storing when types match at the glslang level, but not might match at the
3051// SPIR-V level.
3052//
3053// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003054// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003055// as in a member-decorated way.
3056//
3057// NOTE: This function can handle any store request; if it's not special it
3058// simplifies to a simple OpStore.
3059//
3060// Implicitly uses the existing builder.accessChain as the storage target.
3061void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3062{
John Kessenichb3e24e42016-09-11 12:33:43 -06003063 // we only do the complex path here if it's an aggregate
3064 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003065 accessChainStore(type, rValue);
3066 return;
3067 }
3068
John Kessenichb3e24e42016-09-11 12:33:43 -06003069 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003070 spv::Id rType = builder.getTypeId(rValue);
3071 spv::Id lValue = builder.accessChainGetLValue();
3072 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3073 if (lType == rType) {
3074 accessChainStore(type, rValue);
3075 return;
3076 }
3077
John Kessenichb3e24e42016-09-11 12:33:43 -06003078 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003079 // where the two types were the same type in GLSL. This requires member
3080 // by member copy, recursively.
3081
John Kessenichb3e24e42016-09-11 12:33:43 -06003082 // If an array, copy element by element.
3083 if (type.isArray()) {
3084 glslang::TType glslangElementType(type, 0);
3085 spv::Id elementRType = builder.getContainedTypeId(rType);
3086 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3087 // get the source member
3088 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003089
John Kessenichb3e24e42016-09-11 12:33:43 -06003090 // set up the target storage
3091 builder.clearAccessChain();
3092 builder.setAccessChainLValue(lValue);
3093 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003094
John Kessenichb3e24e42016-09-11 12:33:43 -06003095 // store the member
3096 multiTypeStore(glslangElementType, elementRValue);
3097 }
3098 } else {
3099 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003100
John Kessenichb3e24e42016-09-11 12:33:43 -06003101 // loop over structure members
3102 const glslang::TTypeList& members = *type.getStruct();
3103 for (int m = 0; m < (int)members.size(); ++m) {
3104 const glslang::TType& glslangMemberType = *members[m].type;
3105
3106 // get the source member
3107 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3108 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3109
3110 // set up the target storage
3111 builder.clearAccessChain();
3112 builder.setAccessChainLValue(lValue);
3113 builder.accessChainPush(builder.makeIntConstant(m));
3114
3115 // store the member
3116 multiTypeStore(glslangMemberType, memberRValue);
3117 }
John Kessenich4bf71552016-09-02 11:20:21 -06003118 }
3119}
3120
John Kessenichf85e8062015-12-19 13:57:10 -07003121// Decide whether or not this type should be
3122// decorated with offsets and strides, and if so
3123// whether std140 or std430 rules should be applied.
3124glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003125{
John Kessenichf85e8062015-12-19 13:57:10 -07003126 // has to be a block
3127 if (type.getBasicType() != glslang::EbtBlock)
3128 return glslang::ElpNone;
3129
3130 // has to be a uniform or buffer block
3131 if (type.getQualifier().storage != glslang::EvqUniform &&
3132 type.getQualifier().storage != glslang::EvqBuffer)
3133 return glslang::ElpNone;
3134
3135 // return the layout to use
3136 switch (type.getQualifier().layoutPacking) {
3137 case glslang::ElpStd140:
3138 case glslang::ElpStd430:
3139 return type.getQualifier().layoutPacking;
3140 default:
3141 return glslang::ElpNone;
3142 }
John Kessenich31ed4832015-09-09 17:51:38 -06003143}
3144
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003145// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003146int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003147{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003148 int size;
John Kessenich49987892015-12-29 17:11:44 -07003149 int stride;
3150 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003151
3152 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003153}
3154
John Kessenich49987892015-12-29 17:11:44 -07003155// 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 -07003156// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003157int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003158{
John Kessenich49987892015-12-29 17:11:44 -07003159 glslang::TType elementType;
3160 elementType.shallowCopy(matrixType);
3161 elementType.clearArraySizes();
3162
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003163 int size;
John Kessenich49987892015-12-29 17:11:44 -07003164 int stride;
3165 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3166
3167 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003168}
3169
John Kessenich5e4b1242015-08-06 22:53:06 -06003170// Given a member type of a struct, realign the current offset for it, and compute
3171// the next (not yet aligned) offset for the next member, which will get aligned
3172// on the next call.
3173// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3174// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3175// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003176void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003177 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003178{
3179 // this will get a positive value when deemed necessary
3180 nextOffset = -1;
3181
John Kessenich5e4b1242015-08-06 22:53:06 -06003182 // override anything in currentOffset with user-set offset
3183 if (memberType.getQualifier().hasOffset())
3184 currentOffset = memberType.getQualifier().layoutOffset;
3185
3186 // It could be that current linker usage in glslang updated all the layoutOffset,
3187 // in which case the following code does not matter. But, that's not quite right
3188 // once cross-compilation unit GLSL validation is done, as the original user
3189 // settings are needed in layoutOffset, and then the following will come into play.
3190
John Kessenichf85e8062015-12-19 13:57:10 -07003191 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003192 if (! memberType.getQualifier().hasOffset())
3193 currentOffset = -1;
3194
3195 return;
3196 }
3197
John Kessenichf85e8062015-12-19 13:57:10 -07003198 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 if (currentOffset < 0)
3200 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003201
John Kessenich5e4b1242015-08-06 22:53:06 -06003202 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3203 // but possibly not yet correctly aligned.
3204
3205 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003206 int dummyStride;
3207 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003208
3209 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003210 // TODO: make this consistent in early phases of code:
3211 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3212 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3213 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003214 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003215 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003216 int dummySize;
3217 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3218 if (componentAlignment <= 4)
3219 memberAlignment = componentAlignment;
3220 }
3221
3222 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003223 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003224
3225 // Bump up to vec4 if there is a bad straddle
3226 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3227 glslang::RoundToPow2(currentOffset, 16);
3228
John Kessenich5e4b1242015-08-06 22:53:06 -06003229 nextOffset = currentOffset + memberSize;
3230}
3231
David Netoa901ffe2016-06-08 14:11:40 +01003232void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003233{
David Netoa901ffe2016-06-08 14:11:40 +01003234 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3235 switch (glslangBuiltIn)
3236 {
3237 case glslang::EbvClipDistance:
3238 case glslang::EbvCullDistance:
3239 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003240#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003241 case glslang::EbvViewportMaskNV:
3242 case glslang::EbvSecondaryPositionNV:
3243 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003244 case glslang::EbvPositionPerViewNV:
3245 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003246#endif
David Netoa901ffe2016-06-08 14:11:40 +01003247 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3248 // Alternately, we could just call this for any glslang built-in, since the
3249 // capability already guards against duplicates.
3250 TranslateBuiltInDecoration(glslangBuiltIn, false);
3251 break;
3252 default:
3253 // Capabilities were already generated when the struct was declared.
3254 break;
3255 }
John Kessenichebb50532016-05-16 19:22:05 -06003256}
3257
John Kessenich6fccb3c2016-09-19 16:01:41 -06003258bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003259{
John Kessenicheee9d532016-09-19 18:09:30 -06003260 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003261}
3262
John Kessenichd41993d2017-09-10 15:21:05 -06003263// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003264// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3265// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003266bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003267{
John Kessenich6a14f782017-12-04 02:48:10 -07003268 assert(qualifier == glslang::EvqIn ||
3269 qualifier == glslang::EvqOut ||
3270 qualifier == glslang::EvqInOut ||
3271 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003272 return qualifier != glslang::EvqConstReadOnly;
3273}
3274
3275// Is parameter pass-by-original?
3276bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3277 bool implicitThisParam)
3278{
3279 if (implicitThisParam) // implicit this
3280 return true;
3281 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003282 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003283 return paramType.containsOpaque() || // sampler, etc.
3284 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3285}
3286
John Kessenich140f3df2015-06-26 16:58:36 -06003287// Make all the functions, skeletally, without actually visiting their bodies.
3288void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3289{
John Kessenichfad62972017-07-18 02:35:46 -06003290 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3291 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3292 if (paramPrecision != spv::NoPrecision)
3293 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003294 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003295 };
3296
John Kessenich140f3df2015-06-26 16:58:36 -06003297 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3298 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003299 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003300 continue;
3301
3302 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003303 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003304 //
qining25262b32016-05-06 17:25:16 -04003305 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003306 // function. What it is an address of varies:
3307 //
John Kessenich4bf71552016-09-02 11:20:21 -06003308 // - "in" parameters not marked as "const" can be written to without modifying the calling
3309 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003310 //
3311 // - "const in" parameters can just be the r-value, as no writes need occur.
3312 //
John Kessenich4bf71552016-09-02 11:20:21 -06003313 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3314 // 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 -06003315
3316 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003317 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003318 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3319
John Kessenichfad62972017-07-18 02:35:46 -06003320 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3321 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003322
John Kessenichfad62972017-07-18 02:35:46 -06003323 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003324 for (int p = 0; p < (int)parameters.size(); ++p) {
3325 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3326 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003327 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003328 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003329 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003330 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3331 else
John Kessenich4bf71552016-09-02 11:20:21 -06003332 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003333 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003334 paramTypes.push_back(typeId);
3335 }
3336
3337 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003338 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3339 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003340 glslFunction->getName().c_str(), paramTypes,
3341 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003342 if (implicitThis)
3343 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003344
3345 // Track function to emit/call later
3346 functionMap[glslFunction->getName().c_str()] = function;
3347
3348 // Set the parameter id's
3349 for (int p = 0; p < (int)parameters.size(); ++p) {
3350 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3351 // give a name too
3352 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3353 }
3354 }
3355}
3356
3357// Process all the initializers, while skipping the functions and link objects
3358void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3359{
3360 builder.setBuildPoint(shaderEntry->getLastBlock());
3361 for (int i = 0; i < (int)initializers.size(); ++i) {
3362 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3363 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3364
3365 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003366 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003367 initializer->traverse(this);
3368 }
3369 }
3370}
3371
3372// Process all the functions, while skipping initializers.
3373void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3374{
3375 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3376 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003377 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003378 node->traverse(this);
3379 }
3380}
3381
3382void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3383{
qining25262b32016-05-06 17:25:16 -04003384 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003385 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003386 currentFunction = functionMap[node->getName().c_str()];
3387 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003388 builder.setBuildPoint(functionBlock);
3389}
3390
Rex Xu04db3f52015-09-16 11:44:02 +08003391void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003392{
Rex Xufc618912015-09-09 16:42:49 +08003393 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003394
3395 glslang::TSampler sampler = {};
3396 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003397#ifdef AMD_EXTENSIONS
3398 bool f16ShadowCompare = false;
3399#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003400 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003401 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3402 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003403#ifdef AMD_EXTENSIONS
3404 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3405#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003406 }
3407
John Kessenich140f3df2015-06-26 16:58:36 -06003408 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3409 builder.clearAccessChain();
3410 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003411
3412 // Special case l-value operands
3413 bool lvalue = false;
3414 switch (node.getOp()) {
3415 case glslang::EOpImageAtomicAdd:
3416 case glslang::EOpImageAtomicMin:
3417 case glslang::EOpImageAtomicMax:
3418 case glslang::EOpImageAtomicAnd:
3419 case glslang::EOpImageAtomicOr:
3420 case glslang::EOpImageAtomicXor:
3421 case glslang::EOpImageAtomicExchange:
3422 case glslang::EOpImageAtomicCompSwap:
3423 if (i == 0)
3424 lvalue = true;
3425 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003426 case glslang::EOpSparseImageLoad:
3427 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3428 lvalue = true;
3429 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003430#ifdef AMD_EXTENSIONS
3431 case glslang::EOpSparseTexture:
3432 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3433 lvalue = true;
3434 break;
3435 case glslang::EOpSparseTextureClamp:
3436 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3437 lvalue = true;
3438 break;
3439 case glslang::EOpSparseTextureLod:
3440 case glslang::EOpSparseTextureOffset:
3441 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3442 lvalue = true;
3443 break;
3444#else
Rex Xu48edadf2015-12-31 16:11:41 +08003445 case glslang::EOpSparseTexture:
3446 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3447 lvalue = true;
3448 break;
3449 case glslang::EOpSparseTextureClamp:
3450 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3451 lvalue = true;
3452 break;
3453 case glslang::EOpSparseTextureLod:
3454 case glslang::EOpSparseTextureOffset:
3455 if (i == 3)
3456 lvalue = true;
3457 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003458#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003459 case glslang::EOpSparseTextureFetch:
3460 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3461 lvalue = true;
3462 break;
3463 case glslang::EOpSparseTextureFetchOffset:
3464 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3465 lvalue = true;
3466 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003467#ifdef AMD_EXTENSIONS
3468 case glslang::EOpSparseTextureLodOffset:
3469 case glslang::EOpSparseTextureGrad:
3470 case glslang::EOpSparseTextureOffsetClamp:
3471 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3472 lvalue = true;
3473 break;
3474 case glslang::EOpSparseTextureGradOffset:
3475 case glslang::EOpSparseTextureGradClamp:
3476 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3477 lvalue = true;
3478 break;
3479 case glslang::EOpSparseTextureGradOffsetClamp:
3480 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3481 lvalue = true;
3482 break;
3483#else
Rex Xu48edadf2015-12-31 16:11:41 +08003484 case glslang::EOpSparseTextureLodOffset:
3485 case glslang::EOpSparseTextureGrad:
3486 case glslang::EOpSparseTextureOffsetClamp:
3487 if (i == 4)
3488 lvalue = true;
3489 break;
3490 case glslang::EOpSparseTextureGradOffset:
3491 case glslang::EOpSparseTextureGradClamp:
3492 if (i == 5)
3493 lvalue = true;
3494 break;
3495 case glslang::EOpSparseTextureGradOffsetClamp:
3496 if (i == 6)
3497 lvalue = true;
3498 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003499#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003500 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003501 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3502 lvalue = true;
3503 break;
3504 case glslang::EOpSparseTextureGatherOffset:
3505 case glslang::EOpSparseTextureGatherOffsets:
3506 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3507 lvalue = true;
3508 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003509#ifdef AMD_EXTENSIONS
3510 case glslang::EOpSparseTextureGatherLod:
3511 if (i == 3)
3512 lvalue = true;
3513 break;
3514 case glslang::EOpSparseTextureGatherLodOffset:
3515 case glslang::EOpSparseTextureGatherLodOffsets:
3516 if (i == 4)
3517 lvalue = true;
3518 break;
Rex Xu129799a2017-07-05 17:23:28 +08003519 case glslang::EOpSparseImageLoadLod:
3520 if (i == 3)
3521 lvalue = true;
3522 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003523#endif
Rex Xufc618912015-09-09 16:42:49 +08003524 default:
3525 break;
3526 }
3527
Rex Xu6b86d492015-09-16 17:48:22 +08003528 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003529 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003530 else
John Kessenich32cfd492016-02-02 12:37:46 -07003531 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003532 }
3533}
3534
John Kessenichfc51d282015-08-19 13:34:18 -06003535void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003536{
John Kessenichfc51d282015-08-19 13:34:18 -06003537 builder.clearAccessChain();
3538 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003539 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003540}
John Kessenich140f3df2015-06-26 16:58:36 -06003541
John Kessenichfc51d282015-08-19 13:34:18 -06003542spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3543{
John Kesseniche485c7a2017-05-31 18:50:53 -06003544 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003545 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003546
3547 builder.setLine(node->getLoc().line);
3548
John Kessenichfc51d282015-08-19 13:34:18 -06003549 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003550 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3551 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003552#ifdef AMD_EXTENSIONS
3553 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3554 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3555 : false;
3556#endif
3557
John Kessenichfc51d282015-08-19 13:34:18 -06003558 std::vector<spv::Id> arguments;
3559 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003560 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003561 else
3562 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003563 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003564
3565 spv::Builder::TextureParameters params = { };
3566 params.sampler = arguments[0];
3567
Rex Xu04db3f52015-09-16 11:44:02 +08003568 glslang::TCrackedTextureOp cracked;
3569 node->crackTexture(sampler, cracked);
3570
amhagan05506bb2017-06-13 16:53:02 -04003571 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003572
John Kessenichfc51d282015-08-19 13:34:18 -06003573 // Check for queries
3574 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003575 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3576 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003577 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003578
John Kessenichfc51d282015-08-19 13:34:18 -06003579 switch (node->getOp()) {
3580 case glslang::EOpImageQuerySize:
3581 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003582 if (arguments.size() > 1) {
3583 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003584 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003585 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003586 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003587 case glslang::EOpImageQuerySamples:
3588 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003589 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003590 case glslang::EOpTextureQueryLod:
3591 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003592 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003593 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003594 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003595 case glslang::EOpSparseTexelsResident:
3596 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003597 default:
3598 assert(0);
3599 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003600 }
John Kessenich140f3df2015-06-26 16:58:36 -06003601 }
3602
LoopDawg4425f242018-02-18 11:40:01 -07003603 int components = node->getType().getVectorSize();
3604
3605 if (node->getOp() == glslang::EOpTextureFetch) {
3606 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3607 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3608 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3609 // here around e.g. which ones return scalars or other types.
3610 components = 4;
3611 }
3612
3613 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3614
3615 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3616
Rex Xufc618912015-09-09 16:42:49 +08003617 // Check for image functions other than queries
3618 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003619 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003620 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003621 spv::IdImmediate image = { true, *(opIt++) };
3622 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003623
3624 // Handle subpass operations
3625 // TODO: GLSL should change to have the "MS" only on the type rather than the
3626 // built-in function.
3627 if (cracked.subpass) {
3628 // add on the (0,0) coordinate
3629 spv::Id zero = builder.makeIntConstant(0);
3630 std::vector<spv::Id> comps;
3631 comps.push_back(zero);
3632 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003633 spv::IdImmediate coord = { true,
3634 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3635 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003636 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003637 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3638 operands.push_back(imageOperands);
3639 spv::IdImmediate imageOperand = { true, *(opIt++) };
3640 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003641 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003642 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3643 builder.setPrecision(result, precision);
3644 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003645 }
3646
John Kessenich149afc32018-08-14 13:31:43 -06003647 spv::IdImmediate coord = { true, *(opIt++) };
3648 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003649#ifdef AMD_EXTENSIONS
3650 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3651#else
John Kessenich56bab042015-09-16 10:54:31 -06003652 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003653#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003654 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003655 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3656 operands.push_back(imageOperands);
3657 spv::IdImmediate imageOperand = { true, *opIt };
3658 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003659#ifdef AMD_EXTENSIONS
3660 } else if (cracked.lod) {
3661 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3662 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3663
John Kessenich149afc32018-08-14 13:31:43 -06003664 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3665 operands.push_back(imageOperands);
3666 spv::IdImmediate imageOperand = { true, *opIt };
3667 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003668#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003669 }
John Kessenich149afc32018-08-14 13:31:43 -06003670 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003671 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003672
John Kessenich149afc32018-08-14 13:31:43 -06003673 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003674 builder.setPrecision(result[0], precision);
3675
3676 // If needed, add a conversion constructor to the proper size.
3677 if (components != node->getType().getVectorSize())
3678 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3679
3680 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003681#ifdef AMD_EXTENSIONS
3682 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3683#else
John Kessenich56bab042015-09-16 10:54:31 -06003684 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003685#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003686 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003687 spv::IdImmediate texel = { true, *(opIt + 1) };
3688 operands.push_back(texel);
3689 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3690 operands.push_back(imageOperands);
3691 spv::IdImmediate imageOperand = { true, *opIt };
3692 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003693#ifdef AMD_EXTENSIONS
3694 } else if (cracked.lod) {
3695 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3696 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3697
John Kessenich149afc32018-08-14 13:31:43 -06003698 spv::IdImmediate texel = { true, *(opIt + 1) };
3699 operands.push_back(texel);
3700 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3701 operands.push_back(imageOperands);
3702 spv::IdImmediate imageOperand = { true, *opIt };
3703 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003704#endif
John Kessenich149afc32018-08-14 13:31:43 -06003705 } else {
3706 spv::IdImmediate texel = { true, *opIt };
3707 operands.push_back(texel);
3708 }
John Kessenich56bab042015-09-16 10:54:31 -06003709 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003710 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003711 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003712 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003713#ifdef AMD_EXTENSIONS
3714 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3715#else
Rex Xu5eafa472016-02-19 22:24:03 +08003716 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003717#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003718 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003719 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003720 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3721
3722 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003723 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3724 operands.push_back(imageOperands);
3725 spv::IdImmediate imageOperand = { true, *opIt++ };
3726 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003727#ifdef AMD_EXTENSIONS
3728 } else if (cracked.lod) {
3729 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3730 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3731
John Kessenich149afc32018-08-14 13:31:43 -06003732 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3733 operands.push_back(imageOperands);
3734 spv::IdImmediate imageOperand = { true, *opIt++ };
3735 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003736#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003737 }
3738
3739 // Create the return type that was a special structure
3740 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003741 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003742 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3743 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3744
3745 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3746
3747 // Decode the return type
3748 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3749 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003750 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003751 // Process image atomic operations
3752
3753 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3754 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003755 // For non-MS, the sample value should be 0
3756 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3757 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003758
John Kessenich8c8505c2016-07-26 12:50:38 -06003759 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003760 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003761
3762 std::vector<spv::Id> operands;
3763 operands.push_back(pointer);
3764 for (; opIt != arguments.end(); ++opIt)
3765 operands.push_back(*opIt);
3766
John Kessenich8c8505c2016-07-26 12:50:38 -06003767 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003768 }
3769 }
3770
amhagan05506bb2017-06-13 16:53:02 -04003771#ifdef AMD_EXTENSIONS
3772 // Check for fragment mask functions other than queries
3773 if (cracked.fragMask) {
3774 assert(sampler.ms);
3775
3776 auto opIt = arguments.begin();
3777 std::vector<spv::Id> operands;
3778
3779 // Extract the image if necessary
3780 if (builder.isSampledImage(params.sampler))
3781 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3782
3783 operands.push_back(params.sampler);
3784 ++opIt;
3785
3786 if (sampler.isSubpass()) {
3787 // add on the (0,0) coordinate
3788 spv::Id zero = builder.makeIntConstant(0);
3789 std::vector<spv::Id> comps;
3790 comps.push_back(zero);
3791 comps.push_back(zero);
3792 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3793 }
3794
3795 for (; opIt != arguments.end(); ++opIt)
3796 operands.push_back(*opIt);
3797
3798 spv::Op fragMaskOp = spv::OpNop;
3799 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3800 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3801 else if (node->getOp() == glslang::EOpFragmentFetch)
3802 fragMaskOp = spv::OpFragmentFetchAMD;
3803
3804 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3805 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3806 return builder.createOp(fragMaskOp, resultType(), operands);
3807 }
3808#endif
3809
Rex Xufc618912015-09-09 16:42:49 +08003810 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003811 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003812 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3813
John Kessenichfc51d282015-08-19 13:34:18 -06003814 // check for bias argument
3815 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003816#ifdef AMD_EXTENSIONS
3817 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3818#else
Rex Xu71519fe2015-11-11 15:35:47 +08003819 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003820#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003821 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003822#ifdef AMD_EXTENSIONS
3823 if (cracked.gather)
3824 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003825
3826 if (f16ShadowCompare)
3827 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003828#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003829 if (cracked.offset)
3830 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003831#ifdef AMD_EXTENSIONS
3832 else if (cracked.offsets)
3833 ++nonBiasArgCount;
3834#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003835 if (cracked.grad)
3836 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003837 if (cracked.lodClamp)
3838 ++nonBiasArgCount;
3839 if (sparse)
3840 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003841
3842 if ((int)arguments.size() > nonBiasArgCount)
3843 bias = true;
3844 }
3845
John Kessenicha5c33d62016-06-02 23:45:21 -06003846 // See if the sampler param should really be just the SPV image part
3847 if (cracked.fetch) {
3848 // a fetch needs to have the image extracted first
3849 if (builder.isSampledImage(params.sampler))
3850 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3851 }
3852
Rex Xu225e0fc2016-11-17 17:47:59 +08003853#ifdef AMD_EXTENSIONS
3854 if (cracked.gather) {
3855 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3856 if (bias || cracked.lod ||
3857 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3858 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003859 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003860 }
3861 }
3862#endif
3863
John Kessenichfc51d282015-08-19 13:34:18 -06003864 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003865
John Kessenichfc51d282015-08-19 13:34:18 -06003866 params.coords = arguments[1];
3867 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003868 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003869
3870 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003871#ifdef AMD_EXTENSIONS
3872 if (cubeCompare || f16ShadowCompare) {
3873#else
Rex Xu48edadf2015-12-31 16:11:41 +08003874 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003875#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003876 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003877 ++extraArgs;
3878 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003879 params.Dref = arguments[2];
3880 ++extraArgs;
3881 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003882 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003883 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003884 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003885 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003886 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003887 dRefComp = builder.getNumComponents(params.coords) - 1;
3888 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003889 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3890 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003891
3892 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003893 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003894 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003895 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003896 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3897 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3898 noImplicitLod = true;
3899 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003900
3901 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003902 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003903 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003904 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003905 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003906
3907 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003908 if (cracked.grad) {
3909 params.gradX = arguments[2 + extraArgs];
3910 params.gradY = arguments[3 + extraArgs];
3911 extraArgs += 2;
3912 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003913
3914 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003915 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003916 params.offset = arguments[2 + extraArgs];
3917 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003918 } else if (cracked.offsets) {
3919 params.offsets = arguments[2 + extraArgs];
3920 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003921 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003922
3923 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003924 if (cracked.lodClamp) {
3925 params.lodClamp = arguments[2 + extraArgs];
3926 ++extraArgs;
3927 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003928
3929 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003930 if (sparse) {
3931 params.texelOut = arguments[2 + extraArgs];
3932 ++extraArgs;
3933 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003934
John Kessenich76d4dfc2016-06-16 12:43:23 -06003935 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003936 if (cracked.gather && ! sampler.shadow) {
3937 // default component is 0, if missing, otherwise an argument
3938 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003939 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003940 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003941 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003942 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003943 }
3944
3945 // bias
3946 if (bias) {
3947 params.bias = arguments[2 + extraArgs];
3948 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003949 }
John Kessenichfc51d282015-08-19 13:34:18 -06003950
John Kessenich65336482016-06-16 14:06:26 -06003951 // projective component (might not to move)
3952 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3953 // are divided by the last component of P."
3954 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3955 // unused components will appear after all used components."
3956 if (cracked.proj) {
3957 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3958 int projTargetComp;
3959 switch (sampler.dim) {
3960 case glslang::Esd1D: projTargetComp = 1; break;
3961 case glslang::Esd2D: projTargetComp = 2; break;
3962 case glslang::EsdRect: projTargetComp = 2; break;
3963 default: projTargetComp = projSourceComp; break;
3964 }
3965 // copy the projective coordinate if we have to
3966 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003967 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003968 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3969 projSourceComp);
3970 params.coords = builder.createCompositeInsert(projComp, params.coords,
3971 builder.getTypeId(params.coords), projTargetComp);
3972 }
3973 }
3974
St0fFa1184dd2018-04-09 21:08:14 +02003975 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003976 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003977 );
LoopDawg4425f242018-02-18 11:40:01 -07003978
3979 if (components != node->getType().getVectorSize())
3980 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3981
3982 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003983}
3984
3985spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3986{
3987 // Grab the function's pointer from the previously created function
3988 spv::Function* function = functionMap[node->getName().c_str()];
3989 if (! function)
3990 return 0;
3991
3992 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3993 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3994
3995 // See comments in makeFunctions() for details about the semantics for parameter passing.
3996 //
3997 // These imply we need a four step process:
3998 // 1. Evaluate the arguments
3999 // 2. Allocate and make copies of in, out, and inout arguments
4000 // 3. Make the call
4001 // 4. Copy back the results
4002
John Kessenichd3ed90b2018-05-04 11:43:03 -06004003 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004004 std::vector<spv::Builder::AccessChain> lValues;
4005 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004006 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004007 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004008 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004009 // build l-value
4010 builder.clearAccessChain();
4011 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004012 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004013 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004014 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004015 // save l-value
4016 lValues.push_back(builder.getAccessChain());
4017 } else {
4018 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004019 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004020 }
4021 }
4022
4023 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4024 // copy the original into that space.
4025 //
4026 // Also, build up the list of actual arguments to pass in for the call
4027 int lValueCount = 0;
4028 int rValueCount = 0;
4029 std::vector<spv::Id> spvArgs;
4030 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4031 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004032 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004033 builder.setAccessChain(lValues[lValueCount]);
4034 arg = builder.accessChainGetLValue();
4035 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004036 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004037 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004038 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004039 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4040 // need to copy the input into output space
4041 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004042 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004043 builder.clearAccessChain();
4044 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004045 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004046 }
4047 ++lValueCount;
4048 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004049 // process r-value, which involves a copy for a type mismatch
4050 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4051 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4052 builder.clearAccessChain();
4053 builder.setAccessChainLValue(argCopy);
4054 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4055 arg = builder.createLoad(argCopy);
4056 } else
4057 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004058 ++rValueCount;
4059 }
4060 spvArgs.push_back(arg);
4061 }
4062
4063 // 3. Make the call.
4064 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004065 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004066
4067 // 4. Copy back out an "out" arguments.
4068 lValueCount = 0;
4069 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004070 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004071 ++lValueCount;
4072 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004073 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4074 spv::Id copy = builder.createLoad(spvArgs[a]);
4075 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004076 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004077 }
4078 ++lValueCount;
4079 }
4080 }
4081
4082 return result;
4083}
4084
4085// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004086spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004087 spv::Id typeId, spv::Id left, spv::Id right,
4088 glslang::TBasicType typeProxy, bool reduceComparison)
4089{
John Kessenich66011cb2018-03-06 16:12:04 -07004090 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4091 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004092 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004093
4094 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004095 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004096 bool comparison = false;
4097
4098 switch (op) {
4099 case glslang::EOpAdd:
4100 case glslang::EOpAddAssign:
4101 if (isFloat)
4102 binOp = spv::OpFAdd;
4103 else
4104 binOp = spv::OpIAdd;
4105 break;
4106 case glslang::EOpSub:
4107 case glslang::EOpSubAssign:
4108 if (isFloat)
4109 binOp = spv::OpFSub;
4110 else
4111 binOp = spv::OpISub;
4112 break;
4113 case glslang::EOpMul:
4114 case glslang::EOpMulAssign:
4115 if (isFloat)
4116 binOp = spv::OpFMul;
4117 else
4118 binOp = spv::OpIMul;
4119 break;
4120 case glslang::EOpVectorTimesScalar:
4121 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004122 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004123 if (builder.isVector(right))
4124 std::swap(left, right);
4125 assert(builder.isScalar(right));
4126 needMatchingVectors = false;
4127 binOp = spv::OpVectorTimesScalar;
4128 } else
4129 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004130 break;
4131 case glslang::EOpVectorTimesMatrix:
4132 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004133 binOp = spv::OpVectorTimesMatrix;
4134 break;
4135 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004136 binOp = spv::OpMatrixTimesVector;
4137 break;
4138 case glslang::EOpMatrixTimesScalar:
4139 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004140 binOp = spv::OpMatrixTimesScalar;
4141 break;
4142 case glslang::EOpMatrixTimesMatrix:
4143 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004144 binOp = spv::OpMatrixTimesMatrix;
4145 break;
4146 case glslang::EOpOuterProduct:
4147 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004148 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150
4151 case glslang::EOpDiv:
4152 case glslang::EOpDivAssign:
4153 if (isFloat)
4154 binOp = spv::OpFDiv;
4155 else if (isUnsigned)
4156 binOp = spv::OpUDiv;
4157 else
4158 binOp = spv::OpSDiv;
4159 break;
4160 case glslang::EOpMod:
4161 case glslang::EOpModAssign:
4162 if (isFloat)
4163 binOp = spv::OpFMod;
4164 else if (isUnsigned)
4165 binOp = spv::OpUMod;
4166 else
4167 binOp = spv::OpSMod;
4168 break;
4169 case glslang::EOpRightShift:
4170 case glslang::EOpRightShiftAssign:
4171 if (isUnsigned)
4172 binOp = spv::OpShiftRightLogical;
4173 else
4174 binOp = spv::OpShiftRightArithmetic;
4175 break;
4176 case glslang::EOpLeftShift:
4177 case glslang::EOpLeftShiftAssign:
4178 binOp = spv::OpShiftLeftLogical;
4179 break;
4180 case glslang::EOpAnd:
4181 case glslang::EOpAndAssign:
4182 binOp = spv::OpBitwiseAnd;
4183 break;
4184 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004185 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 binOp = spv::OpLogicalAnd;
4187 break;
4188 case glslang::EOpInclusiveOr:
4189 case glslang::EOpInclusiveOrAssign:
4190 binOp = spv::OpBitwiseOr;
4191 break;
4192 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004193 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004194 binOp = spv::OpLogicalOr;
4195 break;
4196 case glslang::EOpExclusiveOr:
4197 case glslang::EOpExclusiveOrAssign:
4198 binOp = spv::OpBitwiseXor;
4199 break;
4200 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004201 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004202 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004203 break;
4204
4205 case glslang::EOpLessThan:
4206 case glslang::EOpGreaterThan:
4207 case glslang::EOpLessThanEqual:
4208 case glslang::EOpGreaterThanEqual:
4209 case glslang::EOpEqual:
4210 case glslang::EOpNotEqual:
4211 case glslang::EOpVectorEqual:
4212 case glslang::EOpVectorNotEqual:
4213 comparison = true;
4214 break;
4215 default:
4216 break;
4217 }
4218
John Kessenich7c1aa102015-10-15 13:29:11 -06004219 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004220 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004221 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004222 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004223 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004224
4225 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004226 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004227 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004228
qining25262b32016-05-06 17:25:16 -04004229 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004230 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004231 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004232 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004233 }
4234
4235 if (! comparison)
4236 return 0;
4237
John Kessenich7c1aa102015-10-15 13:29:11 -06004238 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004239
John Kessenich4583b612016-08-07 19:14:22 -06004240 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004241 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4242 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004243 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004244 return result;
4245 }
John Kessenich140f3df2015-06-26 16:58:36 -06004246
4247 switch (op) {
4248 case glslang::EOpLessThan:
4249 if (isFloat)
4250 binOp = spv::OpFOrdLessThan;
4251 else if (isUnsigned)
4252 binOp = spv::OpULessThan;
4253 else
4254 binOp = spv::OpSLessThan;
4255 break;
4256 case glslang::EOpGreaterThan:
4257 if (isFloat)
4258 binOp = spv::OpFOrdGreaterThan;
4259 else if (isUnsigned)
4260 binOp = spv::OpUGreaterThan;
4261 else
4262 binOp = spv::OpSGreaterThan;
4263 break;
4264 case glslang::EOpLessThanEqual:
4265 if (isFloat)
4266 binOp = spv::OpFOrdLessThanEqual;
4267 else if (isUnsigned)
4268 binOp = spv::OpULessThanEqual;
4269 else
4270 binOp = spv::OpSLessThanEqual;
4271 break;
4272 case glslang::EOpGreaterThanEqual:
4273 if (isFloat)
4274 binOp = spv::OpFOrdGreaterThanEqual;
4275 else if (isUnsigned)
4276 binOp = spv::OpUGreaterThanEqual;
4277 else
4278 binOp = spv::OpSGreaterThanEqual;
4279 break;
4280 case glslang::EOpEqual:
4281 case glslang::EOpVectorEqual:
4282 if (isFloat)
4283 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004284 else if (isBool)
4285 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004286 else
4287 binOp = spv::OpIEqual;
4288 break;
4289 case glslang::EOpNotEqual:
4290 case glslang::EOpVectorNotEqual:
4291 if (isFloat)
4292 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004293 else if (isBool)
4294 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004295 else
4296 binOp = spv::OpINotEqual;
4297 break;
4298 default:
4299 break;
4300 }
4301
qining25262b32016-05-06 17:25:16 -04004302 if (binOp != spv::OpNop) {
4303 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004304 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004305 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004306 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004307 }
John Kessenich140f3df2015-06-26 16:58:36 -06004308
4309 return 0;
4310}
4311
John Kessenich04bb8a02015-12-12 12:28:14 -07004312//
4313// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4314// These can be any of:
4315//
4316// matrix * scalar
4317// scalar * matrix
4318// matrix * matrix linear algebraic
4319// matrix * vector
4320// vector * matrix
4321// matrix * matrix componentwise
4322// matrix op matrix op in {+, -, /}
4323// matrix op scalar op in {+, -, /}
4324// scalar op matrix op in {+, -, /}
4325//
John Kessenichead86222018-03-28 18:01:20 -06004326spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4327 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004328{
4329 bool firstClass = true;
4330
4331 // First, handle first-class matrix operations (* and matrix/scalar)
4332 switch (op) {
4333 case spv::OpFDiv:
4334 if (builder.isMatrix(left) && builder.isScalar(right)) {
4335 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004336 spv::Id resultType = builder.getTypeId(right);
4337 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004338 op = spv::OpMatrixTimesScalar;
4339 } else
4340 firstClass = false;
4341 break;
4342 case spv::OpMatrixTimesScalar:
4343 if (builder.isMatrix(right))
4344 std::swap(left, right);
4345 assert(builder.isScalar(right));
4346 break;
4347 case spv::OpVectorTimesMatrix:
4348 assert(builder.isVector(left));
4349 assert(builder.isMatrix(right));
4350 break;
4351 case spv::OpMatrixTimesVector:
4352 assert(builder.isMatrix(left));
4353 assert(builder.isVector(right));
4354 break;
4355 case spv::OpMatrixTimesMatrix:
4356 assert(builder.isMatrix(left));
4357 assert(builder.isMatrix(right));
4358 break;
4359 default:
4360 firstClass = false;
4361 break;
4362 }
4363
qining25262b32016-05-06 17:25:16 -04004364 if (firstClass) {
4365 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004366 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004367 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004368 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004369 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004370
LoopDawg592860c2016-06-09 08:57:35 -06004371 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004372 // The result type of all of them is the same type as the (a) matrix operand.
4373 // The algorithm is to:
4374 // - break the matrix(es) into vectors
4375 // - smear any scalar to a vector
4376 // - do vector operations
4377 // - make a matrix out the vector results
4378 switch (op) {
4379 case spv::OpFAdd:
4380 case spv::OpFSub:
4381 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004382 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004383 case spv::OpFMul:
4384 {
4385 // one time set up...
4386 bool leftMat = builder.isMatrix(left);
4387 bool rightMat = builder.isMatrix(right);
4388 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4389 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4390 spv::Id scalarType = builder.getScalarTypeId(typeId);
4391 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4392 std::vector<spv::Id> results;
4393 spv::Id smearVec = spv::NoResult;
4394 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004395 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004396 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004397 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004398
4399 // do each vector op
4400 for (unsigned int c = 0; c < numCols; ++c) {
4401 std::vector<unsigned int> indexes;
4402 indexes.push_back(c);
4403 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4404 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004405 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004406 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004407 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004408 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004409 }
4410
4411 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004412 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004413 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004414 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004415 }
4416 default:
4417 assert(0);
4418 return spv::NoResult;
4419 }
4420}
4421
John Kessenichead86222018-03-28 18:01:20 -06004422spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4423 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004424{
4425 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004426 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004427 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004428 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4429 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004430
4431 switch (op) {
4432 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004433 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004434 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004435 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004436 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004437 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004438 unaryOp = spv::OpSNegate;
4439 break;
4440
4441 case glslang::EOpLogicalNot:
4442 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004443 unaryOp = spv::OpLogicalNot;
4444 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004445 case glslang::EOpBitwiseNot:
4446 unaryOp = spv::OpNot;
4447 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004448
John Kessenich140f3df2015-06-26 16:58:36 -06004449 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004450 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004451 break;
4452 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004453 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004454 break;
4455 case glslang::EOpTranspose:
4456 unaryOp = spv::OpTranspose;
4457 break;
4458
4459 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004460 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004461 break;
4462 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004463 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004464 break;
4465 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004466 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004467 break;
4468 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004469 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004470 break;
4471 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004472 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004473 break;
4474 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004476 break;
4477 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004478 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004479 break;
4480 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004481 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004482 break;
4483
4484 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004485 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004486 break;
4487 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004488 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004489 break;
4490 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004491 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004492 break;
4493 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 break;
4496 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004497 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004498 break;
4499 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004500 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004501 break;
4502
4503 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004504 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004505 break;
4506 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004507 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004508 break;
4509
4510 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004511 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004512 break;
4513 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004514 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004515 break;
4516 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004517 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004518 break;
4519 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004520 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004521 break;
4522 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004523 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004524 break;
4525 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004526 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004527 break;
4528
4529 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004530 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004531 break;
4532 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004533 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004534 break;
4535 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004536 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004537 break;
4538 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004539 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004540 break;
4541 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004542 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004543 break;
4544 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004545 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004546 break;
4547
4548 case glslang::EOpIsNan:
4549 unaryOp = spv::OpIsNan;
4550 break;
4551 case glslang::EOpIsInf:
4552 unaryOp = spv::OpIsInf;
4553 break;
LoopDawg592860c2016-06-09 08:57:35 -06004554 case glslang::EOpIsFinite:
4555 unaryOp = spv::OpIsFinite;
4556 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004557
Rex Xucbc426e2015-12-15 16:03:10 +08004558 case glslang::EOpFloatBitsToInt:
4559 case glslang::EOpFloatBitsToUint:
4560 case glslang::EOpIntBitsToFloat:
4561 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004562 case glslang::EOpDoubleBitsToInt64:
4563 case glslang::EOpDoubleBitsToUint64:
4564 case glslang::EOpInt64BitsToDouble:
4565 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004566 case glslang::EOpFloat16BitsToInt16:
4567 case glslang::EOpFloat16BitsToUint16:
4568 case glslang::EOpInt16BitsToFloat16:
4569 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004570 unaryOp = spv::OpBitcast;
4571 break;
4572
John Kessenich140f3df2015-06-26 16:58:36 -06004573 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004574 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004575 break;
4576 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004577 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004578 break;
4579 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004580 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004581 break;
4582 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004583 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004584 break;
4585 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004586 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004587 break;
4588 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004589 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004590 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004591 case glslang::EOpPackSnorm4x8:
4592 libCall = spv::GLSLstd450PackSnorm4x8;
4593 break;
4594 case glslang::EOpUnpackSnorm4x8:
4595 libCall = spv::GLSLstd450UnpackSnorm4x8;
4596 break;
4597 case glslang::EOpPackUnorm4x8:
4598 libCall = spv::GLSLstd450PackUnorm4x8;
4599 break;
4600 case glslang::EOpUnpackUnorm4x8:
4601 libCall = spv::GLSLstd450UnpackUnorm4x8;
4602 break;
4603 case glslang::EOpPackDouble2x32:
4604 libCall = spv::GLSLstd450PackDouble2x32;
4605 break;
4606 case glslang::EOpUnpackDouble2x32:
4607 libCall = spv::GLSLstd450UnpackDouble2x32;
4608 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004609
Rex Xu8ff43de2016-04-22 16:51:45 +08004610 case glslang::EOpPackInt2x32:
4611 case glslang::EOpUnpackInt2x32:
4612 case glslang::EOpPackUint2x32:
4613 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004614 case glslang::EOpPack16:
4615 case glslang::EOpPack32:
4616 case glslang::EOpPack64:
4617 case glslang::EOpUnpack32:
4618 case glslang::EOpUnpack16:
4619 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004620 case glslang::EOpPackInt2x16:
4621 case glslang::EOpUnpackInt2x16:
4622 case glslang::EOpPackUint2x16:
4623 case glslang::EOpUnpackUint2x16:
4624 case glslang::EOpPackInt4x16:
4625 case glslang::EOpUnpackInt4x16:
4626 case glslang::EOpPackUint4x16:
4627 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004628 case glslang::EOpPackFloat2x16:
4629 case glslang::EOpUnpackFloat2x16:
4630 unaryOp = spv::OpBitcast;
4631 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004632
John Kessenich140f3df2015-06-26 16:58:36 -06004633 case glslang::EOpDPdx:
4634 unaryOp = spv::OpDPdx;
4635 break;
4636 case glslang::EOpDPdy:
4637 unaryOp = spv::OpDPdy;
4638 break;
4639 case glslang::EOpFwidth:
4640 unaryOp = spv::OpFwidth;
4641 break;
4642 case glslang::EOpDPdxFine:
4643 unaryOp = spv::OpDPdxFine;
4644 break;
4645 case glslang::EOpDPdyFine:
4646 unaryOp = spv::OpDPdyFine;
4647 break;
4648 case glslang::EOpFwidthFine:
4649 unaryOp = spv::OpFwidthFine;
4650 break;
4651 case glslang::EOpDPdxCoarse:
4652 unaryOp = spv::OpDPdxCoarse;
4653 break;
4654 case glslang::EOpDPdyCoarse:
4655 unaryOp = spv::OpDPdyCoarse;
4656 break;
4657 case glslang::EOpFwidthCoarse:
4658 unaryOp = spv::OpFwidthCoarse;
4659 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004660 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004661#ifdef AMD_EXTENSIONS
4662 if (typeProxy == glslang::EbtFloat16)
4663 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4664#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004665 libCall = spv::GLSLstd450InterpolateAtCentroid;
4666 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004667 case glslang::EOpAny:
4668 unaryOp = spv::OpAny;
4669 break;
4670 case glslang::EOpAll:
4671 unaryOp = spv::OpAll;
4672 break;
4673
4674 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004675 if (isFloat)
4676 libCall = spv::GLSLstd450FAbs;
4677 else
4678 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004679 break;
4680 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004681 if (isFloat)
4682 libCall = spv::GLSLstd450FSign;
4683 else
4684 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004685 break;
4686
John Kessenichfc51d282015-08-19 13:34:18 -06004687 case glslang::EOpAtomicCounterIncrement:
4688 case glslang::EOpAtomicCounterDecrement:
4689 case glslang::EOpAtomicCounter:
4690 {
4691 // Handle all of the atomics in one place, in createAtomicOperation()
4692 std::vector<spv::Id> operands;
4693 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004694 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004695 }
4696
John Kessenichfc51d282015-08-19 13:34:18 -06004697 case glslang::EOpBitFieldReverse:
4698 unaryOp = spv::OpBitReverse;
4699 break;
4700 case glslang::EOpBitCount:
4701 unaryOp = spv::OpBitCount;
4702 break;
4703 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004704 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004705 break;
4706 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004707 if (isUnsigned)
4708 libCall = spv::GLSLstd450FindUMsb;
4709 else
4710 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004711 break;
4712
Rex Xu574ab042016-04-14 16:53:07 +08004713 case glslang::EOpBallot:
4714 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004715 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004716 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004717 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004718#ifdef AMD_EXTENSIONS
4719 case glslang::EOpMinInvocations:
4720 case glslang::EOpMaxInvocations:
4721 case glslang::EOpAddInvocations:
4722 case glslang::EOpMinInvocationsNonUniform:
4723 case glslang::EOpMaxInvocationsNonUniform:
4724 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004725 case glslang::EOpMinInvocationsInclusiveScan:
4726 case glslang::EOpMaxInvocationsInclusiveScan:
4727 case glslang::EOpAddInvocationsInclusiveScan:
4728 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4729 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4730 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4731 case glslang::EOpMinInvocationsExclusiveScan:
4732 case glslang::EOpMaxInvocationsExclusiveScan:
4733 case glslang::EOpAddInvocationsExclusiveScan:
4734 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4735 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4736 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004737#endif
Rex Xu51596642016-09-21 18:56:12 +08004738 {
4739 std::vector<spv::Id> operands;
4740 operands.push_back(operand);
4741 return createInvocationsOperation(op, typeId, operands, typeProxy);
4742 }
John Kessenich66011cb2018-03-06 16:12:04 -07004743 case glslang::EOpSubgroupAll:
4744 case glslang::EOpSubgroupAny:
4745 case glslang::EOpSubgroupAllEqual:
4746 case glslang::EOpSubgroupBroadcastFirst:
4747 case glslang::EOpSubgroupBallot:
4748 case glslang::EOpSubgroupInverseBallot:
4749 case glslang::EOpSubgroupBallotBitCount:
4750 case glslang::EOpSubgroupBallotInclusiveBitCount:
4751 case glslang::EOpSubgroupBallotExclusiveBitCount:
4752 case glslang::EOpSubgroupBallotFindLSB:
4753 case glslang::EOpSubgroupBallotFindMSB:
4754 case glslang::EOpSubgroupAdd:
4755 case glslang::EOpSubgroupMul:
4756 case glslang::EOpSubgroupMin:
4757 case glslang::EOpSubgroupMax:
4758 case glslang::EOpSubgroupAnd:
4759 case glslang::EOpSubgroupOr:
4760 case glslang::EOpSubgroupXor:
4761 case glslang::EOpSubgroupInclusiveAdd:
4762 case glslang::EOpSubgroupInclusiveMul:
4763 case glslang::EOpSubgroupInclusiveMin:
4764 case glslang::EOpSubgroupInclusiveMax:
4765 case glslang::EOpSubgroupInclusiveAnd:
4766 case glslang::EOpSubgroupInclusiveOr:
4767 case glslang::EOpSubgroupInclusiveXor:
4768 case glslang::EOpSubgroupExclusiveAdd:
4769 case glslang::EOpSubgroupExclusiveMul:
4770 case glslang::EOpSubgroupExclusiveMin:
4771 case glslang::EOpSubgroupExclusiveMax:
4772 case glslang::EOpSubgroupExclusiveAnd:
4773 case glslang::EOpSubgroupExclusiveOr:
4774 case glslang::EOpSubgroupExclusiveXor:
4775 case glslang::EOpSubgroupQuadSwapHorizontal:
4776 case glslang::EOpSubgroupQuadSwapVertical:
4777 case glslang::EOpSubgroupQuadSwapDiagonal: {
4778 std::vector<spv::Id> operands;
4779 operands.push_back(operand);
4780 return createSubgroupOperation(op, typeId, operands, typeProxy);
4781 }
Rex Xu9d93a232016-05-05 12:30:44 +08004782#ifdef AMD_EXTENSIONS
4783 case glslang::EOpMbcnt:
4784 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4785 libCall = spv::MbcntAMD;
4786 break;
4787
4788 case glslang::EOpCubeFaceIndex:
4789 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4790 libCall = spv::CubeFaceIndexAMD;
4791 break;
4792
4793 case glslang::EOpCubeFaceCoord:
4794 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4795 libCall = spv::CubeFaceCoordAMD;
4796 break;
4797#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004798#ifdef NV_EXTENSIONS
4799 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004800 unaryOp = spv::OpGroupNonUniformPartitionNV;
4801 break;
4802#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004803 default:
4804 return 0;
4805 }
4806
4807 spv::Id id;
4808 if (libCall >= 0) {
4809 std::vector<spv::Id> args;
4810 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004811 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004812 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004813 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004814 }
John Kessenich140f3df2015-06-26 16:58:36 -06004815
John Kessenichead86222018-03-28 18:01:20 -06004816 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004817 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004818 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004819}
4820
John Kessenich7a53f762016-01-20 11:19:27 -07004821// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004822spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4823 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004824{
4825 // Handle unary operations vector by vector.
4826 // The result type is the same type as the original type.
4827 // The algorithm is to:
4828 // - break the matrix into vectors
4829 // - apply the operation to each vector
4830 // - make a matrix out the vector results
4831
4832 // get the types sorted out
4833 int numCols = builder.getNumColumns(operand);
4834 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004835 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4836 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004837 std::vector<spv::Id> results;
4838
4839 // do each vector op
4840 for (int c = 0; c < numCols; ++c) {
4841 std::vector<unsigned int> indexes;
4842 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004843 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4844 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004845 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004846 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004847 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004848 }
4849
4850 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004851 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004852 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004853 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004854}
4855
John Kessenichad7645f2018-06-04 19:11:25 -06004856// For converting integers where both the bitwidth and the signedness could
4857// change, but only do the width change here. The caller is still responsible
4858// for the signedness conversion.
4859spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07004860{
John Kessenichad7645f2018-06-04 19:11:25 -06004861 // Get the result type width, based on the type to convert to.
4862 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004863 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06004864 case glslang::EOpConvInt16ToUint8:
4865 case glslang::EOpConvIntToUint8:
4866 case glslang::EOpConvInt64ToUint8:
4867 case glslang::EOpConvUint16ToInt8:
4868 case glslang::EOpConvUintToInt8:
4869 case glslang::EOpConvUint64ToInt8:
4870 width = 8;
4871 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004872 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06004873 case glslang::EOpConvIntToUint16:
4874 case glslang::EOpConvInt64ToUint16:
4875 case glslang::EOpConvUint8ToInt16:
4876 case glslang::EOpConvUintToInt16:
4877 case glslang::EOpConvUint64ToInt16:
4878 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07004879 break;
4880 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06004881 case glslang::EOpConvInt16ToUint:
4882 case glslang::EOpConvInt64ToUint:
4883 case glslang::EOpConvUint8ToInt:
4884 case glslang::EOpConvUint16ToInt:
4885 case glslang::EOpConvUint64ToInt:
4886 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004887 break;
4888 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004889 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004890 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004891 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004892 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004893 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06004894 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07004895 break;
4896
4897 default:
4898 assert(false && "Default missing");
4899 break;
4900 }
4901
John Kessenichad7645f2018-06-04 19:11:25 -06004902 // Get the conversion operation and result type,
4903 // based on the target width, but the source type.
4904 spv::Id type = spv::NoType;
4905 spv::Op convOp = spv::OpNop;
4906 switch(op) {
4907 case glslang::EOpConvInt8ToUint16:
4908 case glslang::EOpConvInt8ToUint:
4909 case glslang::EOpConvInt8ToUint64:
4910 case glslang::EOpConvInt16ToUint8:
4911 case glslang::EOpConvInt16ToUint:
4912 case glslang::EOpConvInt16ToUint64:
4913 case glslang::EOpConvIntToUint8:
4914 case glslang::EOpConvIntToUint16:
4915 case glslang::EOpConvIntToUint64:
4916 case glslang::EOpConvInt64ToUint8:
4917 case glslang::EOpConvInt64ToUint16:
4918 case glslang::EOpConvInt64ToUint:
4919 convOp = spv::OpSConvert;
4920 type = builder.makeIntType(width);
4921 break;
4922 default:
4923 convOp = spv::OpUConvert;
4924 type = builder.makeUintType(width);
4925 break;
4926 }
4927
John Kessenich66011cb2018-03-06 16:12:04 -07004928 if (vectorSize > 0)
4929 type = builder.makeVectorType(type, vectorSize);
4930
John Kessenichad7645f2018-06-04 19:11:25 -06004931 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07004932}
4933
John Kessenichead86222018-03-28 18:01:20 -06004934spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4935 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004936{
4937 spv::Op convOp = spv::OpNop;
4938 spv::Id zero = 0;
4939 spv::Id one = 0;
4940
4941 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4942
4943 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004944 case glslang::EOpConvInt8ToBool:
4945 case glslang::EOpConvUint8ToBool:
4946 zero = builder.makeUint8Constant(0);
4947 zero = makeSmearedConstant(zero, vectorSize);
4948 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004949 case glslang::EOpConvInt16ToBool:
4950 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004951 zero = builder.makeUint16Constant(0);
4952 zero = makeSmearedConstant(zero, vectorSize);
4953 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4954 case glslang::EOpConvIntToBool:
4955 case glslang::EOpConvUintToBool:
4956 zero = builder.makeUintConstant(0);
4957 zero = makeSmearedConstant(zero, vectorSize);
4958 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4959 case glslang::EOpConvInt64ToBool:
4960 case glslang::EOpConvUint64ToBool:
4961 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004962 zero = makeSmearedConstant(zero, vectorSize);
4963 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4964
4965 case glslang::EOpConvFloatToBool:
4966 zero = builder.makeFloatConstant(0.0F);
4967 zero = makeSmearedConstant(zero, vectorSize);
4968 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4969
4970 case glslang::EOpConvDoubleToBool:
4971 zero = builder.makeDoubleConstant(0.0);
4972 zero = makeSmearedConstant(zero, vectorSize);
4973 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4974
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004975 case glslang::EOpConvFloat16ToBool:
4976 zero = builder.makeFloat16Constant(0.0F);
4977 zero = makeSmearedConstant(zero, vectorSize);
4978 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004979
John Kessenich140f3df2015-06-26 16:58:36 -06004980 case glslang::EOpConvBoolToFloat:
4981 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004982 zero = builder.makeFloatConstant(0.0F);
4983 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004984 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004985
John Kessenich140f3df2015-06-26 16:58:36 -06004986 case glslang::EOpConvBoolToDouble:
4987 convOp = spv::OpSelect;
4988 zero = builder.makeDoubleConstant(0.0);
4989 one = builder.makeDoubleConstant(1.0);
4990 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004991
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004992 case glslang::EOpConvBoolToFloat16:
4993 convOp = spv::OpSelect;
4994 zero = builder.makeFloat16Constant(0.0F);
4995 one = builder.makeFloat16Constant(1.0F);
4996 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004997
4998 case glslang::EOpConvBoolToInt8:
4999 zero = builder.makeInt8Constant(0);
5000 one = builder.makeInt8Constant(1);
5001 convOp = spv::OpSelect;
5002 break;
5003
5004 case glslang::EOpConvBoolToUint8:
5005 zero = builder.makeUint8Constant(0);
5006 one = builder.makeUint8Constant(1);
5007 convOp = spv::OpSelect;
5008 break;
5009
5010 case glslang::EOpConvBoolToInt16:
5011 zero = builder.makeInt16Constant(0);
5012 one = builder.makeInt16Constant(1);
5013 convOp = spv::OpSelect;
5014 break;
5015
5016 case glslang::EOpConvBoolToUint16:
5017 zero = builder.makeUint16Constant(0);
5018 one = builder.makeUint16Constant(1);
5019 convOp = spv::OpSelect;
5020 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005021
John Kessenich140f3df2015-06-26 16:58:36 -06005022 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005023 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005024 if (op == glslang::EOpConvBoolToInt64)
5025 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005026 else
5027 zero = builder.makeIntConstant(0);
5028
5029 if (op == glslang::EOpConvBoolToInt64)
5030 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005031 else
5032 one = builder.makeIntConstant(1);
5033
John Kessenich140f3df2015-06-26 16:58:36 -06005034 convOp = spv::OpSelect;
5035 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005036
John Kessenich140f3df2015-06-26 16:58:36 -06005037 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005038 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005039 if (op == glslang::EOpConvBoolToUint64)
5040 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005041 else
5042 zero = builder.makeUintConstant(0);
5043
5044 if (op == glslang::EOpConvBoolToUint64)
5045 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005046 else
5047 one = builder.makeUintConstant(1);
5048
John Kessenich140f3df2015-06-26 16:58:36 -06005049 convOp = spv::OpSelect;
5050 break;
5051
John Kessenich66011cb2018-03-06 16:12:04 -07005052 case glslang::EOpConvInt8ToFloat16:
5053 case glslang::EOpConvInt8ToFloat:
5054 case glslang::EOpConvInt8ToDouble:
5055 case glslang::EOpConvInt16ToFloat16:
5056 case glslang::EOpConvInt16ToFloat:
5057 case glslang::EOpConvInt16ToDouble:
5058 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005059 case glslang::EOpConvIntToFloat:
5060 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005061 case glslang::EOpConvInt64ToFloat:
5062 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005063 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005064 convOp = spv::OpConvertSToF;
5065 break;
5066
John Kessenich66011cb2018-03-06 16:12:04 -07005067 case glslang::EOpConvUint8ToFloat16:
5068 case glslang::EOpConvUint8ToFloat:
5069 case glslang::EOpConvUint8ToDouble:
5070 case glslang::EOpConvUint16ToFloat16:
5071 case glslang::EOpConvUint16ToFloat:
5072 case glslang::EOpConvUint16ToDouble:
5073 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005074 case glslang::EOpConvUintToFloat:
5075 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005076 case glslang::EOpConvUint64ToFloat:
5077 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005078 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005079 convOp = spv::OpConvertUToF;
5080 break;
5081
5082 case glslang::EOpConvDoubleToFloat:
5083 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005084 case glslang::EOpConvDoubleToFloat16:
5085 case glslang::EOpConvFloat16ToDouble:
5086 case glslang::EOpConvFloatToFloat16:
5087 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005088 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005089 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005090 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005091 break;
5092
John Kessenich66011cb2018-03-06 16:12:04 -07005093 case glslang::EOpConvFloat16ToInt8:
5094 case glslang::EOpConvFloatToInt8:
5095 case glslang::EOpConvDoubleToInt8:
5096 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005097 case glslang::EOpConvFloatToInt16:
5098 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005099 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005100 case glslang::EOpConvFloatToInt:
5101 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005102 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005103 case glslang::EOpConvFloatToInt64:
5104 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005105 convOp = spv::OpConvertFToS;
5106 break;
5107
John Kessenich66011cb2018-03-06 16:12:04 -07005108 case glslang::EOpConvUint8ToInt8:
5109 case glslang::EOpConvInt8ToUint8:
5110 case glslang::EOpConvUint16ToInt16:
5111 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005112 case glslang::EOpConvUintToInt:
5113 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005114 case glslang::EOpConvUint64ToInt64:
5115 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005116 if (builder.isInSpecConstCodeGenMode()) {
5117 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005118 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5119 zero = builder.makeUint8Constant(0);
5120 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005121 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005122 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5123 zero = builder.makeUint64Constant(0);
5124 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005125 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005126 }
qining189b2032016-04-12 23:16:20 -04005127 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005128 // Use OpIAdd, instead of OpBitcast to do the conversion when
5129 // generating for OpSpecConstantOp instruction.
5130 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5131 }
5132 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005133 convOp = spv::OpBitcast;
5134 break;
5135
John Kessenich66011cb2018-03-06 16:12:04 -07005136 case glslang::EOpConvFloat16ToUint8:
5137 case glslang::EOpConvFloatToUint8:
5138 case glslang::EOpConvDoubleToUint8:
5139 case glslang::EOpConvFloat16ToUint16:
5140 case glslang::EOpConvFloatToUint16:
5141 case glslang::EOpConvDoubleToUint16:
5142 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005143 case glslang::EOpConvFloatToUint:
5144 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005145 case glslang::EOpConvFloatToUint64:
5146 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005147 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005148 convOp = spv::OpConvertFToU;
5149 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005150
John Kessenich66011cb2018-03-06 16:12:04 -07005151 case glslang::EOpConvInt8ToInt16:
5152 case glslang::EOpConvInt8ToInt:
5153 case glslang::EOpConvInt8ToInt64:
5154 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005155 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005156 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005157 case glslang::EOpConvIntToInt8:
5158 case glslang::EOpConvIntToInt16:
5159 case glslang::EOpConvIntToInt64:
5160 case glslang::EOpConvInt64ToInt8:
5161 case glslang::EOpConvInt64ToInt16:
5162 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005163 convOp = spv::OpSConvert;
5164 break;
5165
John Kessenich66011cb2018-03-06 16:12:04 -07005166 case glslang::EOpConvUint8ToUint16:
5167 case glslang::EOpConvUint8ToUint:
5168 case glslang::EOpConvUint8ToUint64:
5169 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005170 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005171 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005172 case glslang::EOpConvUintToUint8:
5173 case glslang::EOpConvUintToUint16:
5174 case glslang::EOpConvUintToUint64:
5175 case glslang::EOpConvUint64ToUint8:
5176 case glslang::EOpConvUint64ToUint16:
5177 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005178 convOp = spv::OpUConvert;
5179 break;
5180
John Kessenich66011cb2018-03-06 16:12:04 -07005181 case glslang::EOpConvInt8ToUint16:
5182 case glslang::EOpConvInt8ToUint:
5183 case glslang::EOpConvInt8ToUint64:
5184 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005185 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005186 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005187 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005188 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005189 case glslang::EOpConvIntToUint64:
5190 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005191 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005192 case glslang::EOpConvInt64ToUint:
5193 case glslang::EOpConvUint8ToInt16:
5194 case glslang::EOpConvUint8ToInt:
5195 case glslang::EOpConvUint8ToInt64:
5196 case glslang::EOpConvUint16ToInt8:
5197 case glslang::EOpConvUint16ToInt:
5198 case glslang::EOpConvUint16ToInt64:
5199 case glslang::EOpConvUintToInt8:
5200 case glslang::EOpConvUintToInt16:
5201 case glslang::EOpConvUintToInt64:
5202 case glslang::EOpConvUint64ToInt8:
5203 case glslang::EOpConvUint64ToInt16:
5204 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005205 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005206 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005207
5208 if (builder.isInSpecConstCodeGenMode()) {
5209 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005210 switch(op) {
5211 case glslang::EOpConvInt16ToUint8:
5212 case glslang::EOpConvIntToUint8:
5213 case glslang::EOpConvInt64ToUint8:
5214 case glslang::EOpConvUint16ToInt8:
5215 case glslang::EOpConvUintToInt8:
5216 case glslang::EOpConvUint64ToInt8:
5217 zero = builder.makeUint8Constant(0);
5218 break;
5219 case glslang::EOpConvInt8ToUint16:
5220 case glslang::EOpConvIntToUint16:
5221 case glslang::EOpConvInt64ToUint16:
5222 case glslang::EOpConvUint8ToInt16:
5223 case glslang::EOpConvUintToInt16:
5224 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005225 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005226 break;
5227 case glslang::EOpConvInt8ToUint:
5228 case glslang::EOpConvInt16ToUint:
5229 case glslang::EOpConvInt64ToUint:
5230 case glslang::EOpConvUint8ToInt:
5231 case glslang::EOpConvUint16ToInt:
5232 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005233 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005234 break;
5235 case glslang::EOpConvInt8ToUint64:
5236 case glslang::EOpConvInt16ToUint64:
5237 case glslang::EOpConvIntToUint64:
5238 case glslang::EOpConvUint8ToInt64:
5239 case glslang::EOpConvUint16ToInt64:
5240 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005241 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005242 break;
5243 default:
5244 assert(false && "Default missing");
5245 break;
5246 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005247 zero = makeSmearedConstant(zero, vectorSize);
5248 // Use OpIAdd, instead of OpBitcast to do the conversion when
5249 // generating for OpSpecConstantOp instruction.
5250 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5251 }
5252 // For normal run-time conversion instruction, use OpBitcast.
5253 convOp = spv::OpBitcast;
5254 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005255 default:
5256 break;
5257 }
5258
5259 spv::Id result = 0;
5260 if (convOp == spv::OpNop)
5261 return result;
5262
5263 if (convOp == spv::OpSelect) {
5264 zero = makeSmearedConstant(zero, vectorSize);
5265 one = makeSmearedConstant(one, vectorSize);
5266 result = builder.createTriOp(convOp, destType, operand, one, zero);
5267 } else
5268 result = builder.createUnaryOp(convOp, destType, operand);
5269
John Kessenichead86222018-03-28 18:01:20 -06005270 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005271 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005272 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005273}
5274
5275spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5276{
5277 if (vectorSize == 0)
5278 return constant;
5279
5280 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5281 std::vector<spv::Id> components;
5282 for (int c = 0; c < vectorSize; ++c)
5283 components.push_back(constant);
5284 return builder.makeCompositeConstant(vectorTypeId, components);
5285}
5286
John Kessenich426394d2015-07-23 10:22:48 -06005287// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005288spv::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 -06005289{
5290 spv::Op opCode = spv::OpNop;
5291
5292 switch (op) {
5293 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005294 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005295 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005296 opCode = spv::OpAtomicIAdd;
5297 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005298 case glslang::EOpAtomicCounterSubtract:
5299 opCode = spv::OpAtomicISub;
5300 break;
John Kessenich426394d2015-07-23 10:22:48 -06005301 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005302 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005303 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005304 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005305 break;
5306 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005307 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005308 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005309 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005310 break;
5311 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005312 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005313 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005314 opCode = spv::OpAtomicAnd;
5315 break;
5316 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005317 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005318 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005319 opCode = spv::OpAtomicOr;
5320 break;
5321 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005322 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005323 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005324 opCode = spv::OpAtomicXor;
5325 break;
5326 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005327 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005328 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005329 opCode = spv::OpAtomicExchange;
5330 break;
5331 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005332 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005333 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005334 opCode = spv::OpAtomicCompareExchange;
5335 break;
5336 case glslang::EOpAtomicCounterIncrement:
5337 opCode = spv::OpAtomicIIncrement;
5338 break;
5339 case glslang::EOpAtomicCounterDecrement:
5340 opCode = spv::OpAtomicIDecrement;
5341 break;
5342 case glslang::EOpAtomicCounter:
5343 opCode = spv::OpAtomicLoad;
5344 break;
5345 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005346 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005347 break;
5348 }
5349
Rex Xue8fe8b02017-09-26 15:42:56 +08005350 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5351 builder.addCapability(spv::CapabilityInt64Atomics);
5352
John Kessenich426394d2015-07-23 10:22:48 -06005353 // Sort out the operands
5354 // - mapping from glslang -> SPV
5355 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005356 // - compare-exchange swaps the value and comparator
5357 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005358 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005359 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5360 auto opIt = operands.begin(); // walk the glslang operands
5361 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005362 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5363 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5364 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005365 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5366 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005367 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005368 spvAtomicOperands.push_back(*(opIt + 1));
5369 spvAtomicOperands.push_back(*opIt);
5370 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005371 }
John Kessenich426394d2015-07-23 10:22:48 -06005372
John Kessenich3e60a6f2015-09-14 22:45:16 -06005373 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005374 for (; opIt != operands.end(); ++opIt)
5375 spvAtomicOperands.push_back(*opIt);
5376
John Kessenich48d6e792017-10-06 21:21:48 -06005377 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5378
5379 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5380 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5381 if (op == glslang::EOpAtomicCounterDecrement)
5382 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5383
5384 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005385}
5386
John Kessenich91cef522016-05-05 16:45:40 -06005387// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005388spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005389{
Corentin Walleze7061422018-08-08 15:20:15 +02005390#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005391 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5392 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005393#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005394
Rex Xu51596642016-09-21 18:56:12 +08005395 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005396 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005397 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5398
chaocf200da82016-12-20 12:44:35 -08005399 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5400 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005401 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5402 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005403 } else if (op == glslang::EOpAnyInvocation ||
5404 op == glslang::EOpAllInvocations ||
5405 op == glslang::EOpAllInvocationsEqual) {
5406 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5407 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005408 } else {
5409 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005410#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005411 if (op == glslang::EOpMinInvocationsNonUniform ||
5412 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005413 op == glslang::EOpAddInvocationsNonUniform ||
5414 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5415 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5416 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5417 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5418 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5419 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005420 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005421#endif
Rex Xu51596642016-09-21 18:56:12 +08005422
Rex Xu9d93a232016-05-05 12:30:44 +08005423#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005424 switch (op) {
5425 case glslang::EOpMinInvocations:
5426 case glslang::EOpMaxInvocations:
5427 case glslang::EOpAddInvocations:
5428 case glslang::EOpMinInvocationsNonUniform:
5429 case glslang::EOpMaxInvocationsNonUniform:
5430 case glslang::EOpAddInvocationsNonUniform:
5431 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005432 break;
5433 case glslang::EOpMinInvocationsInclusiveScan:
5434 case glslang::EOpMaxInvocationsInclusiveScan:
5435 case glslang::EOpAddInvocationsInclusiveScan:
5436 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5437 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5438 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5439 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005440 break;
5441 case glslang::EOpMinInvocationsExclusiveScan:
5442 case glslang::EOpMaxInvocationsExclusiveScan:
5443 case glslang::EOpAddInvocationsExclusiveScan:
5444 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5445 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5446 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5447 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005448 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005449 default:
5450 break;
Rex Xu430ef402016-10-14 17:22:23 +08005451 }
John Kessenich149afc32018-08-14 13:31:43 -06005452 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5453 spvGroupOperands.push_back(scope);
5454 if (groupOperation != spv::GroupOperationMax) {
5455 spv::IdImmediate groupOp = { false, groupOperation };
5456 spvGroupOperands.push_back(groupOp);
5457 }
Rex Xu9d93a232016-05-05 12:30:44 +08005458#endif
Rex Xu51596642016-09-21 18:56:12 +08005459 }
5460
John Kessenich149afc32018-08-14 13:31:43 -06005461 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5462 spv::IdImmediate op = { true, *opIt };
5463 spvGroupOperands.push_back(op);
5464 }
John Kessenich91cef522016-05-05 16:45:40 -06005465
5466 switch (op) {
5467 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005468 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005469 break;
John Kessenich91cef522016-05-05 16:45:40 -06005470 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005471 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005472 break;
John Kessenich91cef522016-05-05 16:45:40 -06005473 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005474 opCode = spv::OpSubgroupAllEqualKHR;
5475 break;
Rex Xu51596642016-09-21 18:56:12 +08005476 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005477 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005478 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005479 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005480 break;
5481 case glslang::EOpReadFirstInvocation:
5482 opCode = spv::OpSubgroupFirstInvocationKHR;
5483 break;
5484 case glslang::EOpBallot:
5485 {
5486 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5487 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5488 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5489 //
5490 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5491 //
5492 spv::Id uintType = builder.makeUintType(32);
5493 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5494 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5495
5496 std::vector<spv::Id> components;
5497 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5498 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5499
5500 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5501 return builder.createUnaryOp(spv::OpBitcast, typeId,
5502 builder.createCompositeConstruct(uvec2Type, components));
5503 }
5504
Rex Xu9d93a232016-05-05 12:30:44 +08005505#ifdef AMD_EXTENSIONS
5506 case glslang::EOpMinInvocations:
5507 case glslang::EOpMaxInvocations:
5508 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005509 case glslang::EOpMinInvocationsInclusiveScan:
5510 case glslang::EOpMaxInvocationsInclusiveScan:
5511 case glslang::EOpAddInvocationsInclusiveScan:
5512 case glslang::EOpMinInvocationsExclusiveScan:
5513 case glslang::EOpMaxInvocationsExclusiveScan:
5514 case glslang::EOpAddInvocationsExclusiveScan:
5515 if (op == glslang::EOpMinInvocations ||
5516 op == glslang::EOpMinInvocationsInclusiveScan ||
5517 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005518 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005519 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005520 else {
5521 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005522 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005523 else
Rex Xu51596642016-09-21 18:56:12 +08005524 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005525 }
Rex Xu430ef402016-10-14 17:22:23 +08005526 } else if (op == glslang::EOpMaxInvocations ||
5527 op == glslang::EOpMaxInvocationsInclusiveScan ||
5528 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005529 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005530 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005531 else {
5532 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005533 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005534 else
Rex Xu51596642016-09-21 18:56:12 +08005535 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005536 }
5537 } else {
5538 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005539 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005540 else
Rex Xu51596642016-09-21 18:56:12 +08005541 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005542 }
5543
Rex Xu2bbbe062016-08-23 15:41:05 +08005544 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005545 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005546
5547 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005548 case glslang::EOpMinInvocationsNonUniform:
5549 case glslang::EOpMaxInvocationsNonUniform:
5550 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005551 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5552 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5553 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5554 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5555 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5556 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5557 if (op == glslang::EOpMinInvocationsNonUniform ||
5558 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5559 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005560 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005561 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005562 else {
5563 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005564 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005565 else
Rex Xu51596642016-09-21 18:56:12 +08005566 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005567 }
5568 }
Rex Xu430ef402016-10-14 17:22:23 +08005569 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5570 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5571 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005572 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005573 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005574 else {
5575 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005576 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005577 else
Rex Xu51596642016-09-21 18:56:12 +08005578 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005579 }
5580 }
5581 else {
5582 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005583 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005584 else
Rex Xu51596642016-09-21 18:56:12 +08005585 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005586 }
5587
Rex Xu2bbbe062016-08-23 15:41:05 +08005588 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005589 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005590
5591 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005592#endif
John Kessenich91cef522016-05-05 16:45:40 -06005593 default:
5594 logger->missingFunctionality("invocation operation");
5595 return spv::NoResult;
5596 }
Rex Xu51596642016-09-21 18:56:12 +08005597
5598 assert(opCode != spv::OpNop);
5599 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005600}
5601
Rex Xu2bbbe062016-08-23 15:41:05 +08005602// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005603spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5604 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005605{
Rex Xub7072052016-09-26 15:53:40 +08005606#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005607 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5608 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005609 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005610 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005611 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5612 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5613 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005614#else
5615 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5616 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005617 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5618 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005619#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005620
5621 // Handle group invocation operations scalar by scalar.
5622 // The result type is the same type as the original type.
5623 // The algorithm is to:
5624 // - break the vector into scalars
5625 // - apply the operation to each scalar
5626 // - make a vector out the scalar results
5627
5628 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005629 int numComponents = builder.getNumComponents(operands[0]);
5630 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005631 std::vector<spv::Id> results;
5632
5633 // do each scalar op
5634 for (int comp = 0; comp < numComponents; ++comp) {
5635 std::vector<unsigned int> indexes;
5636 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06005637 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
5638 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005639 if (op == spv::OpSubgroupReadInvocationKHR) {
5640 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005641 spv::IdImmediate operand = { true, operands[1] };
5642 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08005643 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06005644 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5645 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08005646 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005647 spv::IdImmediate operand = { true, operands[1] };
5648 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08005649 } else {
John Kessenich149afc32018-08-14 13:31:43 -06005650 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5651 spvGroupOperands.push_back(scope);
5652 spv::IdImmediate groupOp = { false, groupOperation };
5653 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08005654 spvGroupOperands.push_back(scalar);
5655 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005656
Rex Xub7072052016-09-26 15:53:40 +08005657 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005658 }
5659
5660 // put the pieces together
5661 return builder.createCompositeConstruct(typeId, results);
5662}
Rex Xu2bbbe062016-08-23 15:41:05 +08005663
John Kessenich66011cb2018-03-06 16:12:04 -07005664// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06005665spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
5666 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07005667{
5668 // Add the required capabilities.
5669 switch (op) {
5670 case glslang::EOpSubgroupElect:
5671 builder.addCapability(spv::CapabilityGroupNonUniform);
5672 break;
5673 case glslang::EOpSubgroupAll:
5674 case glslang::EOpSubgroupAny:
5675 case glslang::EOpSubgroupAllEqual:
5676 builder.addCapability(spv::CapabilityGroupNonUniform);
5677 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5678 break;
5679 case glslang::EOpSubgroupBroadcast:
5680 case glslang::EOpSubgroupBroadcastFirst:
5681 case glslang::EOpSubgroupBallot:
5682 case glslang::EOpSubgroupInverseBallot:
5683 case glslang::EOpSubgroupBallotBitExtract:
5684 case glslang::EOpSubgroupBallotBitCount:
5685 case glslang::EOpSubgroupBallotInclusiveBitCount:
5686 case glslang::EOpSubgroupBallotExclusiveBitCount:
5687 case glslang::EOpSubgroupBallotFindLSB:
5688 case glslang::EOpSubgroupBallotFindMSB:
5689 builder.addCapability(spv::CapabilityGroupNonUniform);
5690 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5691 break;
5692 case glslang::EOpSubgroupShuffle:
5693 case glslang::EOpSubgroupShuffleXor:
5694 builder.addCapability(spv::CapabilityGroupNonUniform);
5695 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5696 break;
5697 case glslang::EOpSubgroupShuffleUp:
5698 case glslang::EOpSubgroupShuffleDown:
5699 builder.addCapability(spv::CapabilityGroupNonUniform);
5700 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5701 break;
5702 case glslang::EOpSubgroupAdd:
5703 case glslang::EOpSubgroupMul:
5704 case glslang::EOpSubgroupMin:
5705 case glslang::EOpSubgroupMax:
5706 case glslang::EOpSubgroupAnd:
5707 case glslang::EOpSubgroupOr:
5708 case glslang::EOpSubgroupXor:
5709 case glslang::EOpSubgroupInclusiveAdd:
5710 case glslang::EOpSubgroupInclusiveMul:
5711 case glslang::EOpSubgroupInclusiveMin:
5712 case glslang::EOpSubgroupInclusiveMax:
5713 case glslang::EOpSubgroupInclusiveAnd:
5714 case glslang::EOpSubgroupInclusiveOr:
5715 case glslang::EOpSubgroupInclusiveXor:
5716 case glslang::EOpSubgroupExclusiveAdd:
5717 case glslang::EOpSubgroupExclusiveMul:
5718 case glslang::EOpSubgroupExclusiveMin:
5719 case glslang::EOpSubgroupExclusiveMax:
5720 case glslang::EOpSubgroupExclusiveAnd:
5721 case glslang::EOpSubgroupExclusiveOr:
5722 case glslang::EOpSubgroupExclusiveXor:
5723 builder.addCapability(spv::CapabilityGroupNonUniform);
5724 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5725 break;
5726 case glslang::EOpSubgroupClusteredAdd:
5727 case glslang::EOpSubgroupClusteredMul:
5728 case glslang::EOpSubgroupClusteredMin:
5729 case glslang::EOpSubgroupClusteredMax:
5730 case glslang::EOpSubgroupClusteredAnd:
5731 case glslang::EOpSubgroupClusteredOr:
5732 case glslang::EOpSubgroupClusteredXor:
5733 builder.addCapability(spv::CapabilityGroupNonUniform);
5734 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5735 break;
5736 case glslang::EOpSubgroupQuadBroadcast:
5737 case glslang::EOpSubgroupQuadSwapHorizontal:
5738 case glslang::EOpSubgroupQuadSwapVertical:
5739 case glslang::EOpSubgroupQuadSwapDiagonal:
5740 builder.addCapability(spv::CapabilityGroupNonUniform);
5741 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5742 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005743#ifdef NV_EXTENSIONS
5744 case glslang::EOpSubgroupPartitionedAdd:
5745 case glslang::EOpSubgroupPartitionedMul:
5746 case glslang::EOpSubgroupPartitionedMin:
5747 case glslang::EOpSubgroupPartitionedMax:
5748 case glslang::EOpSubgroupPartitionedAnd:
5749 case glslang::EOpSubgroupPartitionedOr:
5750 case glslang::EOpSubgroupPartitionedXor:
5751 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5752 case glslang::EOpSubgroupPartitionedInclusiveMul:
5753 case glslang::EOpSubgroupPartitionedInclusiveMin:
5754 case glslang::EOpSubgroupPartitionedInclusiveMax:
5755 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5756 case glslang::EOpSubgroupPartitionedInclusiveOr:
5757 case glslang::EOpSubgroupPartitionedInclusiveXor:
5758 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5759 case glslang::EOpSubgroupPartitionedExclusiveMul:
5760 case glslang::EOpSubgroupPartitionedExclusiveMin:
5761 case glslang::EOpSubgroupPartitionedExclusiveMax:
5762 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5763 case glslang::EOpSubgroupPartitionedExclusiveOr:
5764 case glslang::EOpSubgroupPartitionedExclusiveXor:
5765 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5766 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5767 break;
5768#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005769 default: assert(0 && "Unhandled subgroup operation!");
5770 }
5771
5772 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5773 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5774 const bool isBool = typeProxy == glslang::EbtBool;
5775
5776 spv::Op opCode = spv::OpNop;
5777
5778 // Figure out which opcode to use.
5779 switch (op) {
5780 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5781 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5782 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5783 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5784 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5785 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5786 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5787 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5788 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5789 case glslang::EOpSubgroupBallotBitCount:
5790 case glslang::EOpSubgroupBallotInclusiveBitCount:
5791 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5792 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5793 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5794 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5795 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5796 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5797 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5798 case glslang::EOpSubgroupAdd:
5799 case glslang::EOpSubgroupInclusiveAdd:
5800 case glslang::EOpSubgroupExclusiveAdd:
5801 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005802#ifdef NV_EXTENSIONS
5803 case glslang::EOpSubgroupPartitionedAdd:
5804 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5805 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5806#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005807 if (isFloat) {
5808 opCode = spv::OpGroupNonUniformFAdd;
5809 } else {
5810 opCode = spv::OpGroupNonUniformIAdd;
5811 }
5812 break;
5813 case glslang::EOpSubgroupMul:
5814 case glslang::EOpSubgroupInclusiveMul:
5815 case glslang::EOpSubgroupExclusiveMul:
5816 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005817#ifdef NV_EXTENSIONS
5818 case glslang::EOpSubgroupPartitionedMul:
5819 case glslang::EOpSubgroupPartitionedInclusiveMul:
5820 case glslang::EOpSubgroupPartitionedExclusiveMul:
5821#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005822 if (isFloat) {
5823 opCode = spv::OpGroupNonUniformFMul;
5824 } else {
5825 opCode = spv::OpGroupNonUniformIMul;
5826 }
5827 break;
5828 case glslang::EOpSubgroupMin:
5829 case glslang::EOpSubgroupInclusiveMin:
5830 case glslang::EOpSubgroupExclusiveMin:
5831 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005832#ifdef NV_EXTENSIONS
5833 case glslang::EOpSubgroupPartitionedMin:
5834 case glslang::EOpSubgroupPartitionedInclusiveMin:
5835 case glslang::EOpSubgroupPartitionedExclusiveMin:
5836#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005837 if (isFloat) {
5838 opCode = spv::OpGroupNonUniformFMin;
5839 } else if (isUnsigned) {
5840 opCode = spv::OpGroupNonUniformUMin;
5841 } else {
5842 opCode = spv::OpGroupNonUniformSMin;
5843 }
5844 break;
5845 case glslang::EOpSubgroupMax:
5846 case glslang::EOpSubgroupInclusiveMax:
5847 case glslang::EOpSubgroupExclusiveMax:
5848 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005849#ifdef NV_EXTENSIONS
5850 case glslang::EOpSubgroupPartitionedMax:
5851 case glslang::EOpSubgroupPartitionedInclusiveMax:
5852 case glslang::EOpSubgroupPartitionedExclusiveMax:
5853#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005854 if (isFloat) {
5855 opCode = spv::OpGroupNonUniformFMax;
5856 } else if (isUnsigned) {
5857 opCode = spv::OpGroupNonUniformUMax;
5858 } else {
5859 opCode = spv::OpGroupNonUniformSMax;
5860 }
5861 break;
5862 case glslang::EOpSubgroupAnd:
5863 case glslang::EOpSubgroupInclusiveAnd:
5864 case glslang::EOpSubgroupExclusiveAnd:
5865 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005866#ifdef NV_EXTENSIONS
5867 case glslang::EOpSubgroupPartitionedAnd:
5868 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5869 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5870#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005871 if (isBool) {
5872 opCode = spv::OpGroupNonUniformLogicalAnd;
5873 } else {
5874 opCode = spv::OpGroupNonUniformBitwiseAnd;
5875 }
5876 break;
5877 case glslang::EOpSubgroupOr:
5878 case glslang::EOpSubgroupInclusiveOr:
5879 case glslang::EOpSubgroupExclusiveOr:
5880 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005881#ifdef NV_EXTENSIONS
5882 case glslang::EOpSubgroupPartitionedOr:
5883 case glslang::EOpSubgroupPartitionedInclusiveOr:
5884 case glslang::EOpSubgroupPartitionedExclusiveOr:
5885#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005886 if (isBool) {
5887 opCode = spv::OpGroupNonUniformLogicalOr;
5888 } else {
5889 opCode = spv::OpGroupNonUniformBitwiseOr;
5890 }
5891 break;
5892 case glslang::EOpSubgroupXor:
5893 case glslang::EOpSubgroupInclusiveXor:
5894 case glslang::EOpSubgroupExclusiveXor:
5895 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005896#ifdef NV_EXTENSIONS
5897 case glslang::EOpSubgroupPartitionedXor:
5898 case glslang::EOpSubgroupPartitionedInclusiveXor:
5899 case glslang::EOpSubgroupPartitionedExclusiveXor:
5900#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005901 if (isBool) {
5902 opCode = spv::OpGroupNonUniformLogicalXor;
5903 } else {
5904 opCode = spv::OpGroupNonUniformBitwiseXor;
5905 }
5906 break;
5907 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5908 case glslang::EOpSubgroupQuadSwapHorizontal:
5909 case glslang::EOpSubgroupQuadSwapVertical:
5910 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5911 default: assert(0 && "Unhandled subgroup operation!");
5912 }
5913
John Kessenich149afc32018-08-14 13:31:43 -06005914 // get the right Group Operation
5915 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07005916 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06005917 default:
5918 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005919 case glslang::EOpSubgroupBallotBitCount:
5920 case glslang::EOpSubgroupAdd:
5921 case glslang::EOpSubgroupMul:
5922 case glslang::EOpSubgroupMin:
5923 case glslang::EOpSubgroupMax:
5924 case glslang::EOpSubgroupAnd:
5925 case glslang::EOpSubgroupOr:
5926 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06005927 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07005928 break;
5929 case glslang::EOpSubgroupBallotInclusiveBitCount:
5930 case glslang::EOpSubgroupInclusiveAdd:
5931 case glslang::EOpSubgroupInclusiveMul:
5932 case glslang::EOpSubgroupInclusiveMin:
5933 case glslang::EOpSubgroupInclusiveMax:
5934 case glslang::EOpSubgroupInclusiveAnd:
5935 case glslang::EOpSubgroupInclusiveOr:
5936 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005937 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07005938 break;
5939 case glslang::EOpSubgroupBallotExclusiveBitCount:
5940 case glslang::EOpSubgroupExclusiveAdd:
5941 case glslang::EOpSubgroupExclusiveMul:
5942 case glslang::EOpSubgroupExclusiveMin:
5943 case glslang::EOpSubgroupExclusiveMax:
5944 case glslang::EOpSubgroupExclusiveAnd:
5945 case glslang::EOpSubgroupExclusiveOr:
5946 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005947 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07005948 break;
5949 case glslang::EOpSubgroupClusteredAdd:
5950 case glslang::EOpSubgroupClusteredMul:
5951 case glslang::EOpSubgroupClusteredMin:
5952 case glslang::EOpSubgroupClusteredMax:
5953 case glslang::EOpSubgroupClusteredAnd:
5954 case glslang::EOpSubgroupClusteredOr:
5955 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06005956 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07005957 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005958#ifdef NV_EXTENSIONS
5959 case glslang::EOpSubgroupPartitionedAdd:
5960 case glslang::EOpSubgroupPartitionedMul:
5961 case glslang::EOpSubgroupPartitionedMin:
5962 case glslang::EOpSubgroupPartitionedMax:
5963 case glslang::EOpSubgroupPartitionedAnd:
5964 case glslang::EOpSubgroupPartitionedOr:
5965 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06005966 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005967 break;
5968 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5969 case glslang::EOpSubgroupPartitionedInclusiveMul:
5970 case glslang::EOpSubgroupPartitionedInclusiveMin:
5971 case glslang::EOpSubgroupPartitionedInclusiveMax:
5972 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5973 case glslang::EOpSubgroupPartitionedInclusiveOr:
5974 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005975 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005976 break;
5977 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5978 case glslang::EOpSubgroupPartitionedExclusiveMul:
5979 case glslang::EOpSubgroupPartitionedExclusiveMin:
5980 case glslang::EOpSubgroupPartitionedExclusiveMax:
5981 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5982 case glslang::EOpSubgroupPartitionedExclusiveOr:
5983 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005984 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005985 break;
5986#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005987 }
5988
John Kessenich149afc32018-08-14 13:31:43 -06005989 // build the instruction
5990 std::vector<spv::IdImmediate> spvGroupOperands;
5991
5992 // Every operation begins with the Execution Scope operand.
5993 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5994 spvGroupOperands.push_back(executionScope);
5995
5996 // Next, for all operations that use a Group Operation, push that as an operand.
5997 if (groupOperation != spv::GroupOperationMax) {
5998 spv::IdImmediate groupOperand = { false, groupOperation };
5999 spvGroupOperands.push_back(groupOperand);
6000 }
6001
John Kessenich66011cb2018-03-06 16:12:04 -07006002 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006003 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6004 spv::IdImmediate operand = { true, *opIt };
6005 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006006 }
6007
6008 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006009 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006010 switch (op) {
6011 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006012 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6013 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6014 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6015 }
6016 if (directionId != spv::NoResult) {
6017 spv::IdImmediate direction = { true, directionId };
6018 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006019 }
6020
6021 return builder.createOp(opCode, typeId, spvGroupOperands);
6022}
6023
John Kessenich5e4b1242015-08-06 22:53:06 -06006024spv::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 -06006025{
John Kessenich66011cb2018-03-06 16:12:04 -07006026 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6027 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006028
John Kessenich140f3df2015-06-26 16:58:36 -06006029 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006030 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006031 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006032 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006033 spv::Id typeId0 = 0;
6034 if (consumedOperands > 0)
6035 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006036 spv::Id typeId1 = 0;
6037 if (consumedOperands > 1)
6038 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006039 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006040
6041 switch (op) {
6042 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006043 if (isFloat)
6044 libCall = spv::GLSLstd450FMin;
6045 else if (isUnsigned)
6046 libCall = spv::GLSLstd450UMin;
6047 else
6048 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006049 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006050 break;
6051 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006052 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006053 break;
6054 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006055 if (isFloat)
6056 libCall = spv::GLSLstd450FMax;
6057 else if (isUnsigned)
6058 libCall = spv::GLSLstd450UMax;
6059 else
6060 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006061 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006062 break;
6063 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006064 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006065 break;
6066 case glslang::EOpDot:
6067 opCode = spv::OpDot;
6068 break;
6069 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006070 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006071 break;
6072
6073 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006074 if (isFloat)
6075 libCall = spv::GLSLstd450FClamp;
6076 else if (isUnsigned)
6077 libCall = spv::GLSLstd450UClamp;
6078 else
6079 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006080 builder.promoteScalar(precision, operands.front(), operands[1]);
6081 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006082 break;
6083 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006084 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6085 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006086 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006087 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006088 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006089 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006090 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006091 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006092 break;
6093 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006094 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006095 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006096 break;
6097 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006098 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006099 builder.promoteScalar(precision, operands[0], operands[2]);
6100 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006101 break;
6102
6103 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006104 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006105 break;
6106 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006107 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006108 break;
6109 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006110 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006111 break;
6112 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006113 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006114 break;
6115 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006116 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006117 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006118 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006119#ifdef AMD_EXTENSIONS
6120 if (typeProxy == glslang::EbtFloat16)
6121 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6122#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006123 libCall = spv::GLSLstd450InterpolateAtSample;
6124 break;
6125 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006126#ifdef AMD_EXTENSIONS
6127 if (typeProxy == glslang::EbtFloat16)
6128 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6129#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006130 libCall = spv::GLSLstd450InterpolateAtOffset;
6131 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006132 case glslang::EOpAddCarry:
6133 opCode = spv::OpIAddCarry;
6134 typeId = builder.makeStructResultType(typeId0, typeId0);
6135 consumedOperands = 2;
6136 break;
6137 case glslang::EOpSubBorrow:
6138 opCode = spv::OpISubBorrow;
6139 typeId = builder.makeStructResultType(typeId0, typeId0);
6140 consumedOperands = 2;
6141 break;
6142 case glslang::EOpUMulExtended:
6143 opCode = spv::OpUMulExtended;
6144 typeId = builder.makeStructResultType(typeId0, typeId0);
6145 consumedOperands = 2;
6146 break;
6147 case glslang::EOpIMulExtended:
6148 opCode = spv::OpSMulExtended;
6149 typeId = builder.makeStructResultType(typeId0, typeId0);
6150 consumedOperands = 2;
6151 break;
6152 case glslang::EOpBitfieldExtract:
6153 if (isUnsigned)
6154 opCode = spv::OpBitFieldUExtract;
6155 else
6156 opCode = spv::OpBitFieldSExtract;
6157 break;
6158 case glslang::EOpBitfieldInsert:
6159 opCode = spv::OpBitFieldInsert;
6160 break;
6161
6162 case glslang::EOpFma:
6163 libCall = spv::GLSLstd450Fma;
6164 break;
6165 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006166 {
6167 libCall = spv::GLSLstd450FrexpStruct;
6168 assert(builder.isPointerType(typeId1));
6169 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006170 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006171#ifdef AMD_EXTENSIONS
6172 if (width == 16)
6173 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6174 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6175#endif
Rex Xu470026f2017-03-29 17:12:40 +08006176 if (builder.getNumComponents(operands[0]) == 1)
6177 frexpIntType = builder.makeIntegerType(width, true);
6178 else
6179 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6180 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6181 consumedOperands = 1;
6182 }
John Kessenich55e7d112015-11-15 21:33:39 -07006183 break;
6184 case glslang::EOpLdexp:
6185 libCall = spv::GLSLstd450Ldexp;
6186 break;
6187
Rex Xu574ab042016-04-14 16:53:07 +08006188 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006189 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006190
John Kessenich66011cb2018-03-06 16:12:04 -07006191 case glslang::EOpSubgroupBroadcast:
6192 case glslang::EOpSubgroupBallotBitExtract:
6193 case glslang::EOpSubgroupShuffle:
6194 case glslang::EOpSubgroupShuffleXor:
6195 case glslang::EOpSubgroupShuffleUp:
6196 case glslang::EOpSubgroupShuffleDown:
6197 case glslang::EOpSubgroupClusteredAdd:
6198 case glslang::EOpSubgroupClusteredMul:
6199 case glslang::EOpSubgroupClusteredMin:
6200 case glslang::EOpSubgroupClusteredMax:
6201 case glslang::EOpSubgroupClusteredAnd:
6202 case glslang::EOpSubgroupClusteredOr:
6203 case glslang::EOpSubgroupClusteredXor:
6204 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006205#ifdef NV_EXTENSIONS
6206 case glslang::EOpSubgroupPartitionedAdd:
6207 case glslang::EOpSubgroupPartitionedMul:
6208 case glslang::EOpSubgroupPartitionedMin:
6209 case glslang::EOpSubgroupPartitionedMax:
6210 case glslang::EOpSubgroupPartitionedAnd:
6211 case glslang::EOpSubgroupPartitionedOr:
6212 case glslang::EOpSubgroupPartitionedXor:
6213 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6214 case glslang::EOpSubgroupPartitionedInclusiveMul:
6215 case glslang::EOpSubgroupPartitionedInclusiveMin:
6216 case glslang::EOpSubgroupPartitionedInclusiveMax:
6217 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6218 case glslang::EOpSubgroupPartitionedInclusiveOr:
6219 case glslang::EOpSubgroupPartitionedInclusiveXor:
6220 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6221 case glslang::EOpSubgroupPartitionedExclusiveMul:
6222 case glslang::EOpSubgroupPartitionedExclusiveMin:
6223 case glslang::EOpSubgroupPartitionedExclusiveMax:
6224 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6225 case glslang::EOpSubgroupPartitionedExclusiveOr:
6226 case glslang::EOpSubgroupPartitionedExclusiveXor:
6227#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006228 return createSubgroupOperation(op, typeId, operands, typeProxy);
6229
Rex Xu9d93a232016-05-05 12:30:44 +08006230#ifdef AMD_EXTENSIONS
6231 case glslang::EOpSwizzleInvocations:
6232 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6233 libCall = spv::SwizzleInvocationsAMD;
6234 break;
6235 case glslang::EOpSwizzleInvocationsMasked:
6236 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6237 libCall = spv::SwizzleInvocationsMaskedAMD;
6238 break;
6239 case glslang::EOpWriteInvocation:
6240 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6241 libCall = spv::WriteInvocationAMD;
6242 break;
6243
6244 case glslang::EOpMin3:
6245 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6246 if (isFloat)
6247 libCall = spv::FMin3AMD;
6248 else {
6249 if (isUnsigned)
6250 libCall = spv::UMin3AMD;
6251 else
6252 libCall = spv::SMin3AMD;
6253 }
6254 break;
6255 case glslang::EOpMax3:
6256 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6257 if (isFloat)
6258 libCall = spv::FMax3AMD;
6259 else {
6260 if (isUnsigned)
6261 libCall = spv::UMax3AMD;
6262 else
6263 libCall = spv::SMax3AMD;
6264 }
6265 break;
6266 case glslang::EOpMid3:
6267 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6268 if (isFloat)
6269 libCall = spv::FMid3AMD;
6270 else {
6271 if (isUnsigned)
6272 libCall = spv::UMid3AMD;
6273 else
6274 libCall = spv::SMid3AMD;
6275 }
6276 break;
6277
6278 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006279 if (typeProxy == glslang::EbtFloat16)
6280 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006281 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6282 libCall = spv::InterpolateAtVertexAMD;
6283 break;
6284#endif
6285
John Kessenich140f3df2015-06-26 16:58:36 -06006286 default:
6287 return 0;
6288 }
6289
6290 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006291 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006292 // Use an extended instruction from the standard library.
6293 // Construct the call arguments, without modifying the original operands vector.
6294 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6295 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006296 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006297 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006298 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006299 case 0:
6300 // should all be handled by visitAggregate and createNoArgOperation
6301 assert(0);
6302 return 0;
6303 case 1:
6304 // should all be handled by createUnaryOperation
6305 assert(0);
6306 return 0;
6307 case 2:
6308 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6309 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006310 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006311 // anything 3 or over doesn't have l-value operands, so all should be consumed
6312 assert(consumedOperands == operands.size());
6313 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006314 break;
6315 }
6316 }
6317
John Kessenich55e7d112015-11-15 21:33:39 -07006318 // Decode the return types that were structures
6319 switch (op) {
6320 case glslang::EOpAddCarry:
6321 case glslang::EOpSubBorrow:
6322 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6323 id = builder.createCompositeExtract(id, typeId0, 0);
6324 break;
6325 case glslang::EOpUMulExtended:
6326 case glslang::EOpIMulExtended:
6327 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6328 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6329 break;
6330 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006331 {
6332 assert(operands.size() == 2);
6333 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6334 // "exp" is floating-point type (from HLSL intrinsic)
6335 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6336 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6337 builder.createStore(member1, operands[1]);
6338 } else
6339 // "exp" is integer type (from GLSL built-in function)
6340 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6341 id = builder.createCompositeExtract(id, typeId0, 0);
6342 }
John Kessenich55e7d112015-11-15 21:33:39 -07006343 break;
6344 default:
6345 break;
6346 }
6347
John Kessenich32cfd492016-02-02 12:37:46 -07006348 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006349}
6350
Rex Xu9d93a232016-05-05 12:30:44 +08006351// Intrinsics with no arguments (or no return value, and no precision).
6352spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006353{
6354 // TODO: get the barrier operands correct
6355
6356 switch (op) {
6357 case glslang::EOpEmitVertex:
6358 builder.createNoResultOp(spv::OpEmitVertex);
6359 return 0;
6360 case glslang::EOpEndPrimitive:
6361 builder.createNoResultOp(spv::OpEndPrimitive);
6362 return 0;
6363 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006364 if (glslangIntermediate->getStage() == EShLangTessControl) {
6365 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6366 // TODO: prefer the following, when available:
6367 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6368 // spv::MemorySemanticsPatchMask |
6369 // spv::MemorySemanticsAcquireReleaseMask);
6370 } else {
6371 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6372 spv::MemorySemanticsWorkgroupMemoryMask |
6373 spv::MemorySemanticsAcquireReleaseMask);
6374 }
John Kessenich140f3df2015-06-26 16:58:36 -06006375 return 0;
6376 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006377 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6378 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006379 return 0;
6380 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006381 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6382 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006383 return 0;
6384 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006385 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6386 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006387 return 0;
6388 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006389 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6390 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006391 return 0;
6392 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006393 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6394 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006395 return 0;
6396 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006397 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6398 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006399 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006400 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006401 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006402 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006403 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006404 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006405 case glslang::EOpDeviceMemoryBarrier:
6406 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6407 spv::MemorySemanticsImageMemoryMask |
6408 spv::MemorySemanticsAcquireReleaseMask);
6409 return 0;
6410 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6411 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6412 spv::MemorySemanticsImageMemoryMask |
6413 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006414 return 0;
6415 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006416 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6417 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006418 return 0;
6419 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006420 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6421 spv::MemorySemanticsWorkgroupMemoryMask |
6422 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006423 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006424 case glslang::EOpSubgroupBarrier:
6425 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6426 spv::MemorySemanticsAcquireReleaseMask);
6427 return spv::NoResult;
6428 case glslang::EOpSubgroupMemoryBarrier:
6429 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6430 spv::MemorySemanticsAcquireReleaseMask);
6431 return spv::NoResult;
6432 case glslang::EOpSubgroupMemoryBarrierBuffer:
6433 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6434 spv::MemorySemanticsAcquireReleaseMask);
6435 return spv::NoResult;
6436 case glslang::EOpSubgroupMemoryBarrierImage:
6437 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6438 spv::MemorySemanticsAcquireReleaseMask);
6439 return spv::NoResult;
6440 case glslang::EOpSubgroupMemoryBarrierShared:
6441 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6442 spv::MemorySemanticsAcquireReleaseMask);
6443 return spv::NoResult;
6444 case glslang::EOpSubgroupElect: {
6445 std::vector<spv::Id> operands;
6446 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6447 }
Rex Xu9d93a232016-05-05 12:30:44 +08006448#ifdef AMD_EXTENSIONS
6449 case glslang::EOpTime:
6450 {
6451 std::vector<spv::Id> args; // Dummy arguments
6452 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6453 return builder.setPrecision(id, precision);
6454 }
6455#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006456 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006457 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006458 return 0;
6459 }
6460}
6461
6462spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6463{
John Kessenich2f273362015-07-18 22:34:27 -06006464 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006465 spv::Id id;
6466 if (symbolValues.end() != iter) {
6467 id = iter->second;
6468 return id;
6469 }
6470
6471 // it was not found, create it
6472 id = createSpvVariable(symbol);
6473 symbolValues[symbol->getId()] = id;
6474
Rex Xuc884b4a2016-06-29 15:03:44 +08006475 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006476 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6477 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6478 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006479 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006480 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006481 if (symbol->getQualifier().hasIndex())
6482 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6483 if (symbol->getQualifier().hasComponent())
6484 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006485 // atomic counters use this:
6486 if (symbol->getQualifier().hasOffset())
6487 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006488 }
6489
scygan2c864272016-05-18 18:09:17 +02006490 if (symbol->getQualifier().hasLocation())
6491 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006492 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006493 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006494 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006495 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006496 }
John Kessenich140f3df2015-06-26 16:58:36 -06006497 if (symbol->getQualifier().hasSet())
6498 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006499 else if (IsDescriptorResource(symbol->getType())) {
6500 // default to 0
6501 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6502 }
John Kessenich140f3df2015-06-26 16:58:36 -06006503 if (symbol->getQualifier().hasBinding())
6504 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006505 if (symbol->getQualifier().hasAttachment())
6506 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006507 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006508 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006509 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006510 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006511 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006512 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006513 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6514 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6515 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6516 }
6517 if (symbol->getQualifier().hasXfbOffset())
6518 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006519 }
6520
Rex Xu1da878f2016-02-21 20:59:01 +08006521 if (symbol->getType().isImage()) {
6522 std::vector<spv::Decoration> memory;
6523 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6524 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006525 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006526 }
6527
John Kessenich140f3df2015-06-26 16:58:36 -06006528 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006529 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006530 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006531 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006532
John Kessenich5611c6d2018-04-05 11:25:02 -06006533 // nonuniform
6534 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6535
John Kessenichecba76f2017-01-06 00:34:48 -07006536#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006537 if (builtIn == spv::BuiltInSampleMask) {
6538 spv::Decoration decoration;
6539 // GL_NV_sample_mask_override_coverage extension
6540 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006541 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006542 else
6543 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006544 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006545 if (decoration != spv::DecorationMax) {
6546 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6547 }
6548 }
chaoc771d89f2017-01-13 01:10:53 -08006549 else if (builtIn == spv::BuiltInLayer) {
6550 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006551 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006552 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006553 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6554 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6555 }
John Kessenichb41bff62017-08-11 13:07:17 -06006556 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006557 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6558 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006559 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6560 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6561 }
6562 }
6563
chaoc6e5acae2016-12-20 13:28:52 -08006564 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006565 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006566 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006567 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6568 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006569#endif
6570
John Kessenich5d610ee2018-03-07 18:05:55 -07006571 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6572 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6573 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6574 symbol->getType().getQualifier().semanticName);
6575 }
6576
John Kessenich140f3df2015-06-26 16:58:36 -06006577 return id;
6578}
6579
John Kessenich55e7d112015-11-15 21:33:39 -07006580// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006581// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006582//
6583// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6584//
6585// Recursively walk the nodes. The nodes form a tree whose leaves are
6586// regular constants, which themselves are trees that createSpvConstant()
6587// recursively walks. So, this function walks the "top" of the tree:
6588// - emit specialization constant-building instructions for specConstant
6589// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006590spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006591{
John Kessenich7cc0e282016-03-20 00:46:02 -06006592 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006593
qining4f4bb812016-04-03 23:55:17 -04006594 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006595 if (! node.getQualifier().specConstant) {
6596 // hand off to the non-spec-constant path
6597 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6598 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006599 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006600 nextConst, false);
6601 }
6602
6603 // We now know we have a specialization constant to build
6604
John Kessenichd94c0032016-05-30 19:29:40 -06006605 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006606 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6607 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6608 std::vector<spv::Id> dimConstId;
6609 for (int dim = 0; dim < 3; ++dim) {
6610 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6611 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006612 if (specConst) {
6613 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6614 glslangIntermediate->getLocalSizeSpecId(dim));
6615 }
qining4f4bb812016-04-03 23:55:17 -04006616 }
6617 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6618 }
6619
6620 // An AST node labelled as specialization constant should be a symbol node.
6621 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6622 if (auto* sn = node.getAsSymbolNode()) {
6623 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006624 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6625 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6626 // will set the builder into spec constant op instruction generating mode.
6627 sub_tree->traverse(this);
6628 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006629 } else if (auto* const_union_array = &sn->getConstArray()){
6630 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006631 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6632 builder.addName(id, sn->getName().c_str());
6633 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006634 }
6635 }
qining4f4bb812016-04-03 23:55:17 -04006636
6637 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6638 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006639 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006640 exit(1);
6641 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006642}
6643
John Kessenich140f3df2015-06-26 16:58:36 -06006644// Use 'consts' as the flattened glslang source of scalar constants to recursively
6645// build the aggregate SPIR-V constant.
6646//
6647// If there are not enough elements present in 'consts', 0 will be substituted;
6648// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6649//
qining08408382016-03-21 09:51:37 -04006650spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006651{
6652 // vector of constants for SPIR-V
6653 std::vector<spv::Id> spvConsts;
6654
6655 // Type is used for struct and array constants
6656 spv::Id typeId = convertGlslangToSpvType(glslangType);
6657
6658 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006659 glslang::TType elementType(glslangType, 0);
6660 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006661 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006662 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006663 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006664 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006665 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006666 } else if (glslangType.getStruct()) {
6667 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6668 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006669 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006670 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006671 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6672 bool zero = nextConst >= consts.size();
6673 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006674 case glslang::EbtInt8:
6675 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6676 break;
6677 case glslang::EbtUint8:
6678 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6679 break;
6680 case glslang::EbtInt16:
6681 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6682 break;
6683 case glslang::EbtUint16:
6684 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6685 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006686 case glslang::EbtInt:
6687 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6688 break;
6689 case glslang::EbtUint:
6690 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6691 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006692 case glslang::EbtInt64:
6693 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6694 break;
6695 case glslang::EbtUint64:
6696 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6697 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006698 case glslang::EbtFloat:
6699 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6700 break;
6701 case glslang::EbtDouble:
6702 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6703 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006704 case glslang::EbtFloat16:
6705 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6706 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006707 case glslang::EbtBool:
6708 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6709 break;
6710 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006711 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006712 break;
6713 }
6714 ++nextConst;
6715 }
6716 } else {
6717 // we have a non-aggregate (scalar) constant
6718 bool zero = nextConst >= consts.size();
6719 spv::Id scalar = 0;
6720 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006721 case glslang::EbtInt8:
6722 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6723 break;
6724 case glslang::EbtUint8:
6725 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6726 break;
6727 case glslang::EbtInt16:
6728 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6729 break;
6730 case glslang::EbtUint16:
6731 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6732 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006733 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006734 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006735 break;
6736 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006737 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006738 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006739 case glslang::EbtInt64:
6740 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6741 break;
6742 case glslang::EbtUint64:
6743 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6744 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006745 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006746 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006747 break;
6748 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006749 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006750 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006751 case glslang::EbtFloat16:
6752 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6753 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006754 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006755 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006756 break;
6757 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006758 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006759 break;
6760 }
6761 ++nextConst;
6762 return scalar;
6763 }
6764
6765 return builder.makeCompositeConstant(typeId, spvConsts);
6766}
6767
John Kessenich7c1aa102015-10-15 13:29:11 -06006768// Return true if the node is a constant or symbol whose reading has no
6769// non-trivial observable cost or effect.
6770bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6771{
6772 // don't know what this is
6773 if (node == nullptr)
6774 return false;
6775
6776 // a constant is safe
6777 if (node->getAsConstantUnion() != nullptr)
6778 return true;
6779
6780 // not a symbol means non-trivial
6781 if (node->getAsSymbolNode() == nullptr)
6782 return false;
6783
6784 // a symbol, depends on what's being read
6785 switch (node->getType().getQualifier().storage) {
6786 case glslang::EvqTemporary:
6787 case glslang::EvqGlobal:
6788 case glslang::EvqIn:
6789 case glslang::EvqInOut:
6790 case glslang::EvqConst:
6791 case glslang::EvqConstReadOnly:
6792 case glslang::EvqUniform:
6793 return true;
6794 default:
6795 return false;
6796 }
qining25262b32016-05-06 17:25:16 -04006797}
John Kessenich7c1aa102015-10-15 13:29:11 -06006798
6799// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006800// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006801// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006802// Return true if trivial.
6803bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6804{
6805 if (node == nullptr)
6806 return false;
6807
John Kessenich84cc15f2017-05-24 16:44:47 -06006808 // count non scalars as trivial, as well as anything coming from HLSL
6809 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006810 return true;
6811
John Kessenich7c1aa102015-10-15 13:29:11 -06006812 // symbols and constants are trivial
6813 if (isTrivialLeaf(node))
6814 return true;
6815
6816 // otherwise, it needs to be a simple operation or one or two leaf nodes
6817
6818 // not a simple operation
6819 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6820 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6821 if (binaryNode == nullptr && unaryNode == nullptr)
6822 return false;
6823
6824 // not on leaf nodes
6825 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6826 return false;
6827
6828 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6829 return false;
6830 }
6831
6832 switch (node->getAsOperator()->getOp()) {
6833 case glslang::EOpLogicalNot:
6834 case glslang::EOpConvIntToBool:
6835 case glslang::EOpConvUintToBool:
6836 case glslang::EOpConvFloatToBool:
6837 case glslang::EOpConvDoubleToBool:
6838 case glslang::EOpEqual:
6839 case glslang::EOpNotEqual:
6840 case glslang::EOpLessThan:
6841 case glslang::EOpGreaterThan:
6842 case glslang::EOpLessThanEqual:
6843 case glslang::EOpGreaterThanEqual:
6844 case glslang::EOpIndexDirect:
6845 case glslang::EOpIndexDirectStruct:
6846 case glslang::EOpLogicalXor:
6847 case glslang::EOpAny:
6848 case glslang::EOpAll:
6849 return true;
6850 default:
6851 return false;
6852 }
6853}
6854
6855// Emit short-circuiting code, where 'right' is never evaluated unless
6856// the left side is true (for &&) or false (for ||).
6857spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6858{
6859 spv::Id boolTypeId = builder.makeBoolType();
6860
6861 // emit left operand
6862 builder.clearAccessChain();
6863 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006864 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006865
6866 // Operands to accumulate OpPhi operands
6867 std::vector<spv::Id> phiOperands;
6868 // accumulate left operand's phi information
6869 phiOperands.push_back(leftId);
6870 phiOperands.push_back(builder.getBuildPoint()->getId());
6871
6872 // Make the two kinds of operation symmetric with a "!"
6873 // || => emit "if (! left) result = right"
6874 // && => emit "if ( left) result = right"
6875 //
6876 // TODO: this runtime "not" for || could be avoided by adding functionality
6877 // to 'builder' to have an "else" without an "then"
6878 if (op == glslang::EOpLogicalOr)
6879 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6880
6881 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006882 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006883
6884 // emit right operand as the "then" part of the "if"
6885 builder.clearAccessChain();
6886 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006887 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006888
6889 // accumulate left operand's phi information
6890 phiOperands.push_back(rightId);
6891 phiOperands.push_back(builder.getBuildPoint()->getId());
6892
6893 // finish the "if"
6894 ifBuilder.makeEndIf();
6895
6896 // phi together the two results
6897 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6898}
6899
Frank Henigman541f7bb2018-01-16 00:18:26 -05006900#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006901// Return type Id of the imported set of extended instructions corresponds to the name.
6902// Import this set if it has not been imported yet.
6903spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6904{
6905 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6906 return extBuiltinMap[name];
6907 else {
Rex Xu51596642016-09-21 18:56:12 +08006908 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006909 spv::Id extBuiltins = builder.import(name);
6910 extBuiltinMap[name] = extBuiltins;
6911 return extBuiltins;
6912 }
6913}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006914#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006915
John Kessenich140f3df2015-06-26 16:58:36 -06006916}; // end anonymous namespace
6917
6918namespace glslang {
6919
John Kessenich68d78fd2015-07-12 19:28:10 -06006920void GetSpirvVersion(std::string& version)
6921{
John Kessenich9e55f632015-07-15 10:03:39 -06006922 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006923 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006924 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006925 version = buf;
6926}
6927
John Kessenicha372a3e2017-11-02 22:32:14 -06006928// For low-order part of the generator's magic number. Bump up
6929// when there is a change in the style (e.g., if SSA form changes,
6930// or a different instruction sequence to do something gets used).
6931int GetSpirvGeneratorVersion()
6932{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006933 // return 1; // start
6934 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006935 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006936 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006937 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06006938 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6939 // versions 4 and 6 each generate OpArrayLength as it has long been done
6940 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06006941}
6942
John Kessenich140f3df2015-06-26 16:58:36 -06006943// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006944void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006945{
6946 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006947 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006948 if (out.fail())
6949 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006950 for (int i = 0; i < (int)spirv.size(); ++i) {
6951 unsigned int word = spirv[i];
6952 out.write((const char*)&word, 4);
6953 }
6954 out.close();
6955}
6956
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006957// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006958void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006959{
6960 std::ofstream out;
6961 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006962 if (out.fail())
6963 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006964 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06006965 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07006966 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006967 if (varName != nullptr) {
6968 out << "\t #pragma once" << std::endl;
6969 out << "const uint32_t " << varName << "[] = {" << std::endl;
6970 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006971 const int WORDS_PER_LINE = 8;
6972 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6973 out << "\t";
6974 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6975 const unsigned int word = spirv[i + j];
6976 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6977 if (i + j + 1 < (int)spirv.size()) {
6978 out << ",";
6979 }
6980 }
6981 out << std::endl;
6982 }
Flavio15017db2017-02-15 14:29:33 -08006983 if (varName != nullptr) {
6984 out << "};";
6985 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006986 out.close();
6987}
6988
John Kessenich140f3df2015-06-26 16:58:36 -06006989//
6990// Set up the glslang traversal
6991//
John Kessenich4e11b612018-08-30 16:56:59 -06006992void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006993{
Lei Zhang17535f72016-05-04 15:55:59 -04006994 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006995 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006996}
6997
John Kessenich4e11b612018-08-30 16:56:59 -06006998void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06006999 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007000{
John Kessenich140f3df2015-06-26 16:58:36 -06007001 TIntermNode* root = intermediate.getTreeRoot();
7002
7003 if (root == 0)
7004 return;
7005
John Kessenich4e11b612018-08-30 16:56:59 -06007006 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007007 if (options == nullptr)
7008 options = &defaultOptions;
7009
John Kessenich4e11b612018-08-30 16:56:59 -06007010 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007011
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007012 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007013 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007014 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007015 it.dumpSpv(spirv);
7016
GregFfb03a552018-03-29 11:49:14 -06007017#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007018 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7019 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007020 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007021 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007022
John Kessenich4e11b612018-08-30 16:56:59 -06007023 if (options->validate)
7024 SpirvToolsValidate(intermediate, spirv, logger);
7025
John Kessenich717c80a2018-08-23 15:17:10 -06007026 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007027 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007028
GregFcd1f1692017-09-21 18:40:22 -06007029#endif
7030
John Kessenich4e11b612018-08-30 16:56:59 -06007031 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007032}
7033
7034}; // end namespace glslang