blob: 587460e7a5980051a646a50fefdcfc182a09c8f3 [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);
Jeff Bolz36831c92018-09-05 10:11:41 -0500132 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
133 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
134 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
135 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100136 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700137 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700138 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
139 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700140 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600141 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600142 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
144 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600145 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
146 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
147 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
150 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600151 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600152 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
153 glslang::TLayoutPacking, const glslang::TQualifier&);
154 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
155 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700156 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700157 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800158 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600159 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700160 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700161 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
162 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700163 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
164 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100165 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600166
John Kessenich6fccb3c2016-09-19 16:01:41 -0600167 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600168 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600169 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void makeFunctions(const glslang::TIntermSequence&);
171 void makeGlobalInitializers(const glslang::TIntermSequence&);
172 void visitFunctions(const glslang::TIntermSequence&);
173 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600175 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
176 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600177 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
178
John Kessenichead86222018-03-28 18:01:20 -0600179 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
180 glslang::TBasicType typeProxy, bool reduceComparison = true);
181 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
182 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
186 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600188 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800190 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 +0800191 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800192 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700193 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600194 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 +0800195 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400197 spv::Id createSpvConstant(const glslang::TIntermTyped&);
198 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600199 bool isTrivialLeaf(const glslang::TIntermTyped* node);
200 bool isTrivial(const glslang::TIntermTyped* node);
201 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500202#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800203 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500204#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700205 void addPre13Extension(const char* ext)
206 {
207 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
208 builder.addExtension(ext);
209 }
John Kessenich140f3df2015-06-26 16:58:36 -0600210
John Kessenich121853f2017-05-31 17:11:16 -0600211 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600213 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700214 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 int sequenceDepth;
216
Lei Zhang17535f72016-05-04 15:55:59 -0400217 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400218
John Kessenich140f3df2015-06-26 16:58:36 -0600219 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
220 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700221 bool inEntryPoint;
222 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700223 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 -0700224 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600225 const glslang::TIntermediate* glslangIntermediate;
226 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800227 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600228
John Kessenich2f273362015-07-18 22:34:27 -0600229 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600230 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600231 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700232 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700233 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
234 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600237};
238
239//
240// Helper functions for translating glslang representations to SPIR-V enumerants.
241//
242
243// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700244spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600245{
John Kessenich66e2faf2016-03-12 18:34:36 -0700246 switch (source) {
247 case glslang::EShSourceGlsl:
248 switch (profile) {
249 case ENoProfile:
250 case ECoreProfile:
251 case ECompatibilityProfile:
252 return spv::SourceLanguageGLSL;
253 case EEsProfile:
254 return spv::SourceLanguageESSL;
255 default:
256 return spv::SourceLanguageUnknown;
257 }
258 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600259 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 default:
261 return spv::SourceLanguageUnknown;
262 }
263}
264
265// Translate glslang language (stage) to SPIR-V execution model.
266spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
267{
268 switch (stage) {
269 case EShLangVertex: return spv::ExecutionModelVertex;
270 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
271 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
272 case EShLangGeometry: return spv::ExecutionModelGeometry;
273 case EShLangFragment: return spv::ExecutionModelFragment;
274 case EShLangCompute: return spv::ExecutionModelGLCompute;
275 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700276 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600277 return spv::ExecutionModelFragment;
278 }
279}
280
John Kessenich140f3df2015-06-26 16:58:36 -0600281// Translate glslang sampler type to SPIR-V dimensionality.
282spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
283{
284 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700285 case glslang::Esd1D: return spv::Dim1D;
286 case glslang::Esd2D: return spv::Dim2D;
287 case glslang::Esd3D: return spv::Dim3D;
288 case glslang::EsdCube: return spv::DimCube;
289 case glslang::EsdRect: return spv::DimRect;
290 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700291 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 return spv::Dim2D;
295 }
296}
297
John Kessenichf6640762016-08-01 19:44:00 -0600298// Translate glslang precision to SPIR-V precision decorations.
299spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600300{
John Kessenichf6640762016-08-01 19:44:00 -0600301 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700302 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600303 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 default:
305 return spv::NoPrecision;
306 }
307}
308
John Kessenichf6640762016-08-01 19:44:00 -0600309// Translate glslang type to SPIR-V precision decorations.
310spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
311{
312 return TranslatePrecisionDecoration(type.getQualifier().precision);
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600316spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600317{
318 if (type.getBasicType() == glslang::EbtBlock) {
319 switch (type.getQualifier().storage) {
320 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600321 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case glslang::EvqVaryingIn: return spv::DecorationBlock;
323 case glslang::EvqVaryingOut: return spv::DecorationBlock;
324 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700325 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600326 break;
327 }
328 }
329
John Kessenich4016e382016-07-15 11:53:56 -0600330 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600331}
332
Rex Xu1da878f2016-02-21 20:59:01 +0800333// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500334void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800335{
Jeff Bolz36831c92018-09-05 10:11:41 -0500336 if (!useVulkanMemoryModel) {
337 if (qualifier.coherent)
338 memory.push_back(spv::DecorationCoherent);
339 if (qualifier.volatil) {
340 memory.push_back(spv::DecorationVolatile);
341 memory.push_back(spv::DecorationCoherent);
342 }
John Kessenich14b85d32018-06-04 15:36:03 -0600343 }
Rex Xu1da878f2016-02-21 20:59:01 +0800344 if (qualifier.restrict)
345 memory.push_back(spv::DecorationRestrict);
346 if (qualifier.readonly)
347 memory.push_back(spv::DecorationNonWritable);
348 if (qualifier.writeonly)
349 memory.push_back(spv::DecorationNonReadable);
350}
351
John Kessenich140f3df2015-06-26 16:58:36 -0600352// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700353spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600354{
355 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700356 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600357 case glslang::ElmRowMajor:
358 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700359 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600360 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700361 default:
362 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 }
365 } else {
366 switch (type.getBasicType()) {
367 default:
John Kessenich4016e382016-07-15 11:53:56 -0600368 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 break;
370 case glslang::EbtBlock:
371 switch (type.getQualifier().storage) {
372 case glslang::EvqUniform:
373 case glslang::EvqBuffer:
374 switch (type.getQualifier().layoutPacking) {
375 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
377 default:
John Kessenich4016e382016-07-15 11:53:56 -0600378 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600379 }
380 case glslang::EvqVaryingIn:
381 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700382 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700385 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 }
388 }
389 }
390}
391
392// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600393// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700394// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800395spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600396{
Rex Xubbceed72016-05-21 09:40:44 +0800397 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700398 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800400 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700401 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700402 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800404#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800405 else if (qualifier.explicitInterp) {
406 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800407 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800408 }
Rex Xu9d93a232016-05-05 12:30:44 +0800409#endif
Rex Xubbceed72016-05-21 09:40:44 +0800410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800412}
413
414// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600415// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800416// should be applied.
417spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
418{
419 if (qualifier.patch)
420 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700421 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700423 else if (qualifier.sample) {
424 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600425 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700426 } else
John Kessenich4016e382016-07-15 11:53:56 -0600427 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600428}
429
John Kessenich92187592016-02-01 13:45:25 -0700430// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700431spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700433 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600434 return spv::DecorationInvariant;
435 else
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600437}
438
qining9220dbb2016-05-04 17:34:38 -0400439// If glslang type is noContraction, return SPIR-V NoContraction decoration.
440spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
441{
442 if (qualifier.noContraction)
443 return spv::DecorationNoContraction;
444 else
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400446}
447
John Kessenich5611c6d2018-04-05 11:25:02 -0600448// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
449spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
450{
451 if (qualifier.isNonUniform()) {
452 builder.addExtension("SPV_EXT_descriptor_indexing");
453 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
454 return spv::DecorationNonUniformEXT;
455 } else
456 return spv::DecorationMax;
457}
458
Jeff Bolz36831c92018-09-05 10:11:41 -0500459spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
460{
461 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
462 return spv::MemoryAccessMaskNone;
463 }
464 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
465 if (coherentFlags.volatil ||
466 coherentFlags.coherent ||
467 coherentFlags.devicecoherent ||
468 coherentFlags.queuefamilycoherent ||
469 coherentFlags.workgroupcoherent ||
470 coherentFlags.subgroupcoherent) {
471 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
472 spv::MemoryAccessMakePointerVisibleKHRMask;
473 }
474 if (coherentFlags.nonprivate) {
475 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
476 }
477 if (coherentFlags.volatil) {
478 mask = mask | spv::MemoryAccessVolatileMask;
479 }
480 if (mask != spv::MemoryAccessMaskNone) {
481 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
482 }
483 return mask;
484}
485
486spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
487{
488 if (!glslangIntermediate->usingVulkanMemoryModel()) {
489 return spv::ImageOperandsMaskNone;
490 }
491 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
492 if (coherentFlags.volatil ||
493 coherentFlags.coherent ||
494 coherentFlags.devicecoherent ||
495 coherentFlags.queuefamilycoherent ||
496 coherentFlags.workgroupcoherent ||
497 coherentFlags.subgroupcoherent) {
498 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
499 spv::ImageOperandsMakeTexelVisibleKHRMask;
500 }
501 if (coherentFlags.nonprivate) {
502 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
503 }
504 if (coherentFlags.volatil) {
505 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
506 }
507 if (mask != spv::ImageOperandsMaskNone) {
508 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
509 }
510 return mask;
511}
512
513spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
514{
515 spv::Builder::AccessChain::CoherentFlags flags;
516 flags.coherent = type.getQualifier().coherent;
517 flags.devicecoherent = type.getQualifier().devicecoherent;
518 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
519 // shared variables are implicitly workgroupcoherent in GLSL.
520 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
521 type.getQualifier().storage == glslang::EvqShared;
522 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
523 // *coherent variables are implicitly nonprivate in GLSL
524 flags.nonprivate = type.getQualifier().nonprivate ||
525 type.getQualifier().subgroupcoherent ||
526 type.getQualifier().workgroupcoherent ||
527 type.getQualifier().queuefamilycoherent ||
528 type.getQualifier().devicecoherent ||
529 type.getQualifier().coherent;
530 flags.volatil = type.getQualifier().volatil;
531 flags.isImage = type.getBasicType() == glslang::EbtSampler;
532 return flags;
533}
534
535spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
536{
537 spv::Scope scope;
538 if (coherentFlags.coherent) {
539 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
540 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
541 } else if (coherentFlags.devicecoherent) {
542 scope = spv::ScopeDevice;
543 } else if (coherentFlags.queuefamilycoherent) {
544 scope = spv::ScopeQueueFamilyKHR;
545 } else if (coherentFlags.workgroupcoherent) {
546 scope = spv::ScopeWorkgroup;
547 } else if (coherentFlags.subgroupcoherent) {
548 scope = spv::ScopeSubgroup;
549 } else {
550 scope = spv::ScopeMax;
551 }
552 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
553 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
554 }
555 return scope;
556}
557
David Netoa901ffe2016-06-08 14:11:40 +0100558// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
559// associated capabilities when required. For some built-in variables, a capability
560// is generated only when using the variable in an executable instruction, but not when
561// just declaring a struct member variable with it. This is true for PointSize,
562// ClipDistance, and CullDistance.
563spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600564{
565 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700566 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600567 // Defer adding the capability until the built-in is actually used.
568 if (! memberDeclaration) {
569 switch (glslangIntermediate->getStage()) {
570 case EShLangGeometry:
571 builder.addCapability(spv::CapabilityGeometryPointSize);
572 break;
573 case EShLangTessControl:
574 case EShLangTessEvaluation:
575 builder.addCapability(spv::CapabilityTessellationPointSize);
576 break;
577 default:
578 break;
579 }
John Kessenich92187592016-02-01 13:45:25 -0700580 }
581 return spv::BuiltInPointSize;
582
John Kessenichebb50532016-05-16 19:22:05 -0600583 // These *Distance capabilities logically belong here, but if the member is declared and
584 // then never used, consumers of SPIR-V prefer the capability not be declared.
585 // They are now generated when used, rather than here when declared.
586 // Potentially, the specification should be more clear what the minimum
587 // use needed is to trigger the capability.
588 //
John Kessenich92187592016-02-01 13:45:25 -0700589 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100590 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800591 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700592 return spv::BuiltInClipDistance;
593
594 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100595 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800596 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700597 return spv::BuiltInCullDistance;
598
599 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600600 builder.addCapability(spv::CapabilityMultiViewport);
601 if (glslangIntermediate->getStage() == EShLangVertex ||
602 glslangIntermediate->getStage() == EShLangTessControl ||
603 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800604
John Kessenichba6a3c22017-09-13 13:22:50 -0600605 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
606 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800607 }
John Kessenich92187592016-02-01 13:45:25 -0700608 return spv::BuiltInViewportIndex;
609
John Kessenich5e801132016-02-15 11:09:46 -0700610 case glslang::EbvSampleId:
611 builder.addCapability(spv::CapabilitySampleRateShading);
612 return spv::BuiltInSampleId;
613
614 case glslang::EbvSamplePosition:
615 builder.addCapability(spv::CapabilitySampleRateShading);
616 return spv::BuiltInSamplePosition;
617
618 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700619 return spv::BuiltInSampleMask;
620
John Kessenich78a45572016-07-08 14:05:15 -0600621 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600622 builder.addCapability(spv::CapabilityGeometry);
623 if (glslangIntermediate->getStage() == EShLangVertex ||
624 glslangIntermediate->getStage() == EShLangTessControl ||
625 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800626
John Kessenichba6a3c22017-09-13 13:22:50 -0600627 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
628 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800629 }
John Kessenich78a45572016-07-08 14:05:15 -0600630 return spv::BuiltInLayer;
631
John Kessenich140f3df2015-06-26 16:58:36 -0600632 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600633 case glslang::EbvVertexId: return spv::BuiltInVertexId;
634 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700635 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
636 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800637
John Kessenichda581a22015-10-14 14:10:30 -0600638 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700639 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800640 builder.addCapability(spv::CapabilityDrawParameters);
641 return spv::BuiltInBaseVertex;
642
John Kessenichda581a22015-10-14 14:10:30 -0600643 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700644 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800645 builder.addCapability(spv::CapabilityDrawParameters);
646 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200647
John Kessenichda581a22015-10-14 14:10:30 -0600648 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700649 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800650 builder.addCapability(spv::CapabilityDrawParameters);
651 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200652
653 case glslang::EbvPrimitiveId:
654 if (glslangIntermediate->getStage() == EShLangFragment)
655 builder.addCapability(spv::CapabilityGeometry);
656 return spv::BuiltInPrimitiveId;
657
Rex Xu37cdcee2017-06-29 17:46:34 +0800658 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800659 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
660 builder.addCapability(spv::CapabilityStencilExportEXT);
661 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800662
John Kessenich140f3df2015-06-26 16:58:36 -0600663 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600664 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
665 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
666 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
667 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
668 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
669 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
670 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600671 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
672 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
673 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
674 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
675 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
676 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
677 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
678 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800679
Rex Xu574ab042016-04-14 16:53:07 +0800680 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800681 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800682 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
683 return spv::BuiltInSubgroupSize;
684
Rex Xu574ab042016-04-14 16:53:07 +0800685 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800686 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800687 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
688 return spv::BuiltInSubgroupLocalInvocationId;
689
Rex Xu574ab042016-04-14 16:53:07 +0800690 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800691 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
692 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
693 return spv::BuiltInSubgroupEqMaskKHR;
694
Rex Xu574ab042016-04-14 16:53:07 +0800695 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800696 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
697 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
698 return spv::BuiltInSubgroupGeMaskKHR;
699
Rex Xu574ab042016-04-14 16:53:07 +0800700 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800701 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
702 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
703 return spv::BuiltInSubgroupGtMaskKHR;
704
Rex Xu574ab042016-04-14 16:53:07 +0800705 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800706 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
707 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
708 return spv::BuiltInSubgroupLeMaskKHR;
709
Rex Xu574ab042016-04-14 16:53:07 +0800710 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800711 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
712 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
713 return spv::BuiltInSubgroupLtMaskKHR;
714
John Kessenich66011cb2018-03-06 16:12:04 -0700715 case glslang::EbvNumSubgroups:
716 builder.addCapability(spv::CapabilityGroupNonUniform);
717 return spv::BuiltInNumSubgroups;
718
719 case glslang::EbvSubgroupID:
720 builder.addCapability(spv::CapabilityGroupNonUniform);
721 return spv::BuiltInSubgroupId;
722
723 case glslang::EbvSubgroupSize2:
724 builder.addCapability(spv::CapabilityGroupNonUniform);
725 return spv::BuiltInSubgroupSize;
726
727 case glslang::EbvSubgroupInvocation2:
728 builder.addCapability(spv::CapabilityGroupNonUniform);
729 return spv::BuiltInSubgroupLocalInvocationId;
730
731 case glslang::EbvSubgroupEqMask2:
732 builder.addCapability(spv::CapabilityGroupNonUniform);
733 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
734 return spv::BuiltInSubgroupEqMask;
735
736 case glslang::EbvSubgroupGeMask2:
737 builder.addCapability(spv::CapabilityGroupNonUniform);
738 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
739 return spv::BuiltInSubgroupGeMask;
740
741 case glslang::EbvSubgroupGtMask2:
742 builder.addCapability(spv::CapabilityGroupNonUniform);
743 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
744 return spv::BuiltInSubgroupGtMask;
745
746 case glslang::EbvSubgroupLeMask2:
747 builder.addCapability(spv::CapabilityGroupNonUniform);
748 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
749 return spv::BuiltInSubgroupLeMask;
750
751 case glslang::EbvSubgroupLtMask2:
752 builder.addCapability(spv::CapabilityGroupNonUniform);
753 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
754 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800755#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800756 case glslang::EbvBaryCoordNoPersp:
757 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
758 return spv::BuiltInBaryCoordNoPerspAMD;
759
760 case glslang::EbvBaryCoordNoPerspCentroid:
761 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
762 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
763
764 case glslang::EbvBaryCoordNoPerspSample:
765 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
766 return spv::BuiltInBaryCoordNoPerspSampleAMD;
767
768 case glslang::EbvBaryCoordSmooth:
769 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
770 return spv::BuiltInBaryCoordSmoothAMD;
771
772 case glslang::EbvBaryCoordSmoothCentroid:
773 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
774 return spv::BuiltInBaryCoordSmoothCentroidAMD;
775
776 case glslang::EbvBaryCoordSmoothSample:
777 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
778 return spv::BuiltInBaryCoordSmoothSampleAMD;
779
780 case glslang::EbvBaryCoordPullModel:
781 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
782 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800783#endif
chaoc771d89f2017-01-13 01:10:53 -0800784
John Kessenich6c8aaac2017-02-27 01:20:51 -0700785 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700786 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700787 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700788 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700789
790 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700791 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700792 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700793 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700794
chaoc771d89f2017-01-13 01:10:53 -0800795#ifdef NV_EXTENSIONS
796 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800797 if (!memberDeclaration) {
798 builder.addExtension(spv::E_SPV_NV_viewport_array2);
799 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
800 }
chaoc771d89f2017-01-13 01:10:53 -0800801 return spv::BuiltInViewportMaskNV;
802 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800803 if (!memberDeclaration) {
804 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
805 builder.addCapability(spv::CapabilityShaderStereoViewNV);
806 }
chaoc771d89f2017-01-13 01:10:53 -0800807 return spv::BuiltInSecondaryPositionNV;
808 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800809 if (!memberDeclaration) {
810 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
811 builder.addCapability(spv::CapabilityShaderStereoViewNV);
812 }
chaoc771d89f2017-01-13 01:10:53 -0800813 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800814 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800815 if (!memberDeclaration) {
816 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
817 builder.addCapability(spv::CapabilityPerViewAttributesNV);
818 }
chaocdf3956c2017-02-14 14:52:34 -0800819 return spv::BuiltInPositionPerViewNV;
820 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800821 if (!memberDeclaration) {
822 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
823 builder.addCapability(spv::CapabilityPerViewAttributesNV);
824 }
chaocdf3956c2017-02-14 14:52:34 -0800825 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700826 case glslang::EbvFragFullyCoveredNV:
827 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
828 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
829 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800830#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800831 default:
832 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600833 }
834}
835
Rex Xufc618912015-09-09 16:42:49 +0800836// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700837spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800838{
839 assert(type.getBasicType() == glslang::EbtSampler);
840
John Kessenich5d0fa972016-02-15 11:57:00 -0700841 // Check for capabilities
842 switch (type.getQualifier().layoutFormat) {
843 case glslang::ElfRg32f:
844 case glslang::ElfRg16f:
845 case glslang::ElfR11fG11fB10f:
846 case glslang::ElfR16f:
847 case glslang::ElfRgba16:
848 case glslang::ElfRgb10A2:
849 case glslang::ElfRg16:
850 case glslang::ElfRg8:
851 case glslang::ElfR16:
852 case glslang::ElfR8:
853 case glslang::ElfRgba16Snorm:
854 case glslang::ElfRg16Snorm:
855 case glslang::ElfRg8Snorm:
856 case glslang::ElfR16Snorm:
857 case glslang::ElfR8Snorm:
858
859 case glslang::ElfRg32i:
860 case glslang::ElfRg16i:
861 case glslang::ElfRg8i:
862 case glslang::ElfR16i:
863 case glslang::ElfR8i:
864
865 case glslang::ElfRgb10a2ui:
866 case glslang::ElfRg32ui:
867 case glslang::ElfRg16ui:
868 case glslang::ElfRg8ui:
869 case glslang::ElfR16ui:
870 case glslang::ElfR8ui:
871 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
872 break;
873
874 default:
875 break;
876 }
877
878 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800879 switch (type.getQualifier().layoutFormat) {
880 case glslang::ElfNone: return spv::ImageFormatUnknown;
881 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
882 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
883 case glslang::ElfR32f: return spv::ImageFormatR32f;
884 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
885 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
886 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
887 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
888 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
889 case glslang::ElfR16f: return spv::ImageFormatR16f;
890 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
891 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
892 case glslang::ElfRg16: return spv::ImageFormatRg16;
893 case glslang::ElfRg8: return spv::ImageFormatRg8;
894 case glslang::ElfR16: return spv::ImageFormatR16;
895 case glslang::ElfR8: return spv::ImageFormatR8;
896 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
897 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
898 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
899 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
900 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
901 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
902 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
903 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
904 case glslang::ElfR32i: return spv::ImageFormatR32i;
905 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
906 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
907 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
908 case glslang::ElfR16i: return spv::ImageFormatR16i;
909 case glslang::ElfR8i: return spv::ImageFormatR8i;
910 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
911 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
912 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
913 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
914 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
915 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
916 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
917 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
918 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
919 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600920 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800921 }
922}
923
John Kesseniche18fd202018-01-30 11:01:39 -0700924spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800925{
John Kesseniche18fd202018-01-30 11:01:39 -0700926 if (selectionNode.getFlatten())
927 return spv::SelectionControlFlattenMask;
928 if (selectionNode.getDontFlatten())
929 return spv::SelectionControlDontFlattenMask;
930 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800931}
932
John Kesseniche18fd202018-01-30 11:01:39 -0700933spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600934{
John Kesseniche18fd202018-01-30 11:01:39 -0700935 if (switchNode.getFlatten())
936 return spv::SelectionControlFlattenMask;
937 if (switchNode.getDontFlatten())
938 return spv::SelectionControlDontFlattenMask;
939 return spv::SelectionControlMaskNone;
940}
941
John Kessenicha2858d92018-01-31 08:11:18 -0700942// return a non-0 dependency if the dependency argument must be set
943spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
944 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700945{
946 spv::LoopControlMask control = spv::LoopControlMaskNone;
947
948 if (loopNode.getDontUnroll())
949 control = control | spv::LoopControlDontUnrollMask;
950 if (loopNode.getUnroll())
951 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700952 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700953 control = control | spv::LoopControlDependencyInfiniteMask;
954 else if (loopNode.getLoopDependency() > 0) {
955 control = control | spv::LoopControlDependencyLengthMask;
956 dependencyLength = loopNode.getLoopDependency();
957 }
John Kesseniche18fd202018-01-30 11:01:39 -0700958
959 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600960}
961
John Kessenicha5c5fb62017-05-05 05:09:58 -0600962// Translate glslang type to SPIR-V storage class.
963spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
964{
965 if (type.getQualifier().isPipeInput())
966 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600967 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600968 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600969
970 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
971 type.getQualifier().storage == glslang::EvqUniform) {
972 if (type.getBasicType() == glslang::EbtAtomicUint)
973 return spv::StorageClassAtomicCounter;
974 if (type.containsOpaque())
975 return spv::StorageClassUniformConstant;
976 }
977
978 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700979 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600980 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600981 }
982
983 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600984 if (type.getQualifier().layoutPushConstant)
985 return spv::StorageClassPushConstant;
986 if (type.getBasicType() == glslang::EbtBlock)
987 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600988 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600989 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600990
991 switch (type.getQualifier().storage) {
992 case glslang::EvqShared: return spv::StorageClassWorkgroup;
993 case glslang::EvqGlobal: return spv::StorageClassPrivate;
994 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
995 case glslang::EvqTemporary: return spv::StorageClassFunction;
996 default:
997 assert(0);
998 break;
999 }
1000
1001 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001002}
1003
John Kessenich5611c6d2018-04-05 11:25:02 -06001004// Add capabilities pertaining to how an array is indexed.
1005void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1006 const glslang::TType& indexType)
1007{
1008 if (indexType.getQualifier().isNonUniform()) {
1009 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001010 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001011 if (baseType.getBasicType() == glslang::EbtSampler) {
1012 if (baseType.getQualifier().hasAttachment())
1013 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1014 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1015 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1016 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1017 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1018 else if (baseType.isImage())
1019 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1020 else if (baseType.isTexture())
1021 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1022 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1023 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1024 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1025 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1026 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1027 }
1028 } else {
1029 // assume a dynamically uniform index
1030 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001031 if (baseType.getQualifier().hasAttachment()) {
1032 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001033 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001034 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1035 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001036 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001037 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1038 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001039 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001040 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001041 }
1042 }
1043}
1044
qining25262b32016-05-06 17:25:16 -04001045// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001046// descriptor set.
1047bool IsDescriptorResource(const glslang::TType& type)
1048{
John Kessenichf7497e22016-03-08 21:36:22 -07001049 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001050 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -07001051 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001052
1053 // non block...
1054 // basically samplerXXX/subpass/sampler/texture are all included
1055 // if they are the global-scope-class, not the function parameter
1056 // (or local, if they ever exist) class.
1057 if (type.getBasicType() == glslang::EbtSampler)
1058 return type.getQualifier().isUniformOrBuffer();
1059
1060 // None of the above.
1061 return false;
1062}
1063
John Kesseniche0b6cad2015-12-24 10:30:13 -07001064void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1065{
1066 if (child.layoutMatrix == glslang::ElmNone)
1067 child.layoutMatrix = parent.layoutMatrix;
1068
1069 if (parent.invariant)
1070 child.invariant = true;
1071 if (parent.nopersp)
1072 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001073#ifdef AMD_EXTENSIONS
1074 if (parent.explicitInterp)
1075 child.explicitInterp = true;
1076#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001077 if (parent.flat)
1078 child.flat = true;
1079 if (parent.centroid)
1080 child.centroid = true;
1081 if (parent.patch)
1082 child.patch = true;
1083 if (parent.sample)
1084 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001085 if (parent.coherent)
1086 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001087 if (parent.devicecoherent)
1088 child.devicecoherent = true;
1089 if (parent.queuefamilycoherent)
1090 child.queuefamilycoherent = true;
1091 if (parent.workgroupcoherent)
1092 child.workgroupcoherent = true;
1093 if (parent.subgroupcoherent)
1094 child.subgroupcoherent = true;
1095 if (parent.nonprivate)
1096 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001097 if (parent.volatil)
1098 child.volatil = true;
1099 if (parent.restrict)
1100 child.restrict = true;
1101 if (parent.readonly)
1102 child.readonly = true;
1103 if (parent.writeonly)
1104 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001105}
1106
John Kessenichf2b7f332016-09-01 17:05:23 -06001107bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001108{
John Kessenich7b9fa252016-01-21 18:56:57 -07001109 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001110 // - struct members might inherit from a struct declaration
1111 // (note that non-block structs don't explicitly inherit,
1112 // only implicitly, meaning no decoration involved)
1113 // - affect decorations on the struct members
1114 // (note smooth does not, and expecting something like volatile
1115 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001116 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001117 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001118}
1119
John Kessenich140f3df2015-06-26 16:58:36 -06001120//
1121// Implement the TGlslangToSpvTraverser class.
1122//
1123
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001124TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001125 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1126 : TIntermTraverser(true, false, true),
1127 options(options),
1128 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001129 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001130 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001131 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001132 glslangIntermediate(glslangIntermediate)
1133{
1134 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1135
1136 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001137 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1138 glslangIntermediate->getVersion());
1139
John Kessenich121853f2017-05-31 17:11:16 -06001140 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001141 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001142 builder.setSourceFile(glslangIntermediate->getSourceFile());
1143
1144 // Set the source shader's text. If for SPV version 1.0, include
1145 // a preamble in comments stating the OpModuleProcessed instructions.
1146 // Otherwise, emit those as actual instructions.
1147 std::string text;
1148 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1149 for (int p = 0; p < (int)processes.size(); ++p) {
1150 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1151 text.append("// OpModuleProcessed ");
1152 text.append(processes[p]);
1153 text.append("\n");
1154 } else
1155 builder.addModuleProcessed(processes[p]);
1156 }
1157 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1158 text.append("#line 1\n");
1159 text.append(glslangIntermediate->getSourceText());
1160 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001161 }
John Kessenich140f3df2015-06-26 16:58:36 -06001162 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001163 if (glslangIntermediate->usingVulkanMemoryModel()) {
1164 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1165 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1166 } else {
1167 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1168 }
John Kessenicheee9d532016-09-19 18:09:30 -06001169 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1170 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001171
1172 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001173 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1174 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001175 builder.addSourceExtension(it->c_str());
1176
1177 // Add the top-level modes for this shader.
1178
John Kessenich92187592016-02-01 13:45:25 -07001179 if (glslangIntermediate->getXfbMode()) {
1180 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001181 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001182 }
John Kessenich140f3df2015-06-26 16:58:36 -06001183
1184 unsigned int mode;
1185 switch (glslangIntermediate->getStage()) {
1186 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001187 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001188 break;
1189
steve-lunarge7412492017-03-23 11:56:07 -06001190 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001191 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001192 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001193
steve-lunarge7412492017-03-23 11:56:07 -06001194 glslang::TLayoutGeometry primitive;
1195
1196 if (glslangIntermediate->getStage() == EShLangTessControl) {
1197 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1198 primitive = glslangIntermediate->getOutputPrimitive();
1199 } else {
1200 primitive = glslangIntermediate->getInputPrimitive();
1201 }
1202
1203 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001204 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1205 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1206 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001207 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001208 }
John Kessenich4016e382016-07-15 11:53:56 -06001209 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1211
John Kesseniche6903322015-10-13 16:29:02 -06001212 switch (glslangIntermediate->getVertexSpacing()) {
1213 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1214 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1215 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001216 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001217 }
John Kessenich4016e382016-07-15 11:53:56 -06001218 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001219 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1220
1221 switch (glslangIntermediate->getVertexOrder()) {
1222 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1223 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001224 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001225 }
John Kessenich4016e382016-07-15 11:53:56 -06001226 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001227 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1228
1229 if (glslangIntermediate->getPointMode())
1230 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001231 break;
1232
1233 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001234 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001235 switch (glslangIntermediate->getInputPrimitive()) {
1236 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1237 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1238 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001239 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001240 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001241 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001242 }
John Kessenich4016e382016-07-15 11:53:56 -06001243 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001244 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001245
John Kessenich140f3df2015-06-26 16:58:36 -06001246 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1247
1248 switch (glslangIntermediate->getOutputPrimitive()) {
1249 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1250 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1251 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001252 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
John Kessenich4016e382016-07-15 11:53:56 -06001254 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001255 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1256 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1257 break;
1258
1259 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001260 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 if (glslangIntermediate->getPixelCenterInteger())
1262 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001263
John Kessenich140f3df2015-06-26 16:58:36 -06001264 if (glslangIntermediate->getOriginUpperLeft())
1265 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001266 else
1267 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001268
1269 if (glslangIntermediate->getEarlyFragmentTests())
1270 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1271
chaocc1204522017-06-30 17:14:30 -07001272 if (glslangIntermediate->getPostDepthCoverage()) {
1273 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1274 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1275 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1276 }
1277
John Kesseniche6903322015-10-13 16:29:02 -06001278 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001279 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1280 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001281 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001282 }
John Kessenich4016e382016-07-15 11:53:56 -06001283 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001284 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1285
1286 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1287 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001288 break;
1289
1290 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001291 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001292 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1293 glslangIntermediate->getLocalSize(1),
1294 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001295 break;
1296
1297 default:
1298 break;
1299 }
John Kessenich140f3df2015-06-26 16:58:36 -06001300}
1301
John Kessenichfca82622016-11-26 13:23:20 -07001302// Finish creating SPV, after the traversal is complete.
1303void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001304{
John Kessenichf04c51b2018-08-03 15:56:12 -06001305 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001306 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001307 builder.setBuildPoint(shaderEntry->getLastBlock());
1308 builder.leaveFunction();
1309 }
1310
John Kessenich7ba63412015-12-20 17:37:07 -07001311 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001312 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1313 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001314
John Kessenichf04c51b2018-08-03 15:56:12 -06001315 // Add capabilities, extensions, remove unneeded decorations, etc.,
1316 // based on the resulting SPIR-V.
1317 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001318}
1319
John Kessenichfca82622016-11-26 13:23:20 -07001320// Write the SPV into 'out'.
1321void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001322{
John Kessenichfca82622016-11-26 13:23:20 -07001323 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001324}
1325
1326//
1327// Implement the traversal functions.
1328//
1329// Return true from interior nodes to have the external traversal
1330// continue on to children. Return false if children were
1331// already processed.
1332//
1333
1334//
qining25262b32016-05-06 17:25:16 -04001335// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001336// - uniform/input reads
1337// - output writes
1338// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1339// - something simple that degenerates into the last bullet
1340//
1341void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1342{
qining75d1d802016-04-06 14:42:01 -04001343 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1344 if (symbol->getType().getQualifier().isSpecConstant())
1345 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1346
John Kessenich140f3df2015-06-26 16:58:36 -06001347 // getSymbolId() will set up all the IO decorations on the first call.
1348 // Formal function parameters were mapped during makeFunctions().
1349 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001350
1351 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1352 if (builder.isPointer(id)) {
1353 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001354 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1355 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1356 iOSet.insert(id);
1357 }
John Kessenich7ba63412015-12-20 17:37:07 -07001358 }
1359
1360 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001361 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001362 // Prepare to generate code for the access
1363
1364 // L-value chains will be computed left to right. We're on the symbol now,
1365 // which is the left-most part of the access chain, so now is "clear" time,
1366 // followed by setting the base.
1367 builder.clearAccessChain();
1368
1369 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001370 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001371 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001372 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001373 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001374 // These are also pure R-values.
1375 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001376 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001377 builder.setAccessChainRValue(id);
1378 else
1379 builder.setAccessChainLValue(id);
1380 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001381
1382 // Process linkage-only nodes for any special additional interface work.
1383 if (linkageOnly) {
1384 if (glslangIntermediate->getHlslFunctionality1()) {
1385 // Map implicit counter buffers to their originating buffers, which should have been
1386 // seen by now, given earlier pruning of unused counters, and preservation of order
1387 // of declaration.
1388 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1389 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1390 // Save possible originating buffers for counter buffers, keyed by
1391 // making the potential counter-buffer name.
1392 std::string keyName = symbol->getName().c_str();
1393 keyName = glslangIntermediate->addCounterBufferName(keyName);
1394 counterOriginator[keyName] = symbol;
1395 } else {
1396 // Handle a counter buffer, by finding the saved originating buffer.
1397 std::string keyName = symbol->getName().c_str();
1398 auto it = counterOriginator.find(keyName);
1399 if (it != counterOriginator.end()) {
1400 id = getSymbolId(it->second);
1401 if (id != spv::NoResult) {
1402 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001403 if (counterId != spv::NoResult) {
1404 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001405 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001406 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001407 }
1408 }
1409 }
1410 }
1411 }
1412 }
John Kessenich140f3df2015-06-26 16:58:36 -06001413}
1414
1415bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1416{
John Kesseniche485c7a2017-05-31 18:50:53 -06001417 builder.setLine(node->getLoc().line);
1418
qining40887662016-04-03 22:20:42 -04001419 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1420 if (node->getType().getQualifier().isSpecConstant())
1421 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1422
John Kessenich140f3df2015-06-26 16:58:36 -06001423 // First, handle special cases
1424 switch (node->getOp()) {
1425 case glslang::EOpAssign:
1426 case glslang::EOpAddAssign:
1427 case glslang::EOpSubAssign:
1428 case glslang::EOpMulAssign:
1429 case glslang::EOpVectorTimesMatrixAssign:
1430 case glslang::EOpVectorTimesScalarAssign:
1431 case glslang::EOpMatrixTimesScalarAssign:
1432 case glslang::EOpMatrixTimesMatrixAssign:
1433 case glslang::EOpDivAssign:
1434 case glslang::EOpModAssign:
1435 case glslang::EOpAndAssign:
1436 case glslang::EOpInclusiveOrAssign:
1437 case glslang::EOpExclusiveOrAssign:
1438 case glslang::EOpLeftShiftAssign:
1439 case glslang::EOpRightShiftAssign:
1440 // A bin-op assign "a += b" means the same thing as "a = a + b"
1441 // where a is evaluated before b. For a simple assignment, GLSL
1442 // says to evaluate the left before the right. So, always, left
1443 // node then right node.
1444 {
1445 // get the left l-value, save it away
1446 builder.clearAccessChain();
1447 node->getLeft()->traverse(this);
1448 spv::Builder::AccessChain lValue = builder.getAccessChain();
1449
1450 // evaluate the right
1451 builder.clearAccessChain();
1452 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001453 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001454
1455 if (node->getOp() != glslang::EOpAssign) {
1456 // the left is also an r-value
1457 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001458 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001459
1460 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001461 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001462 TranslateNoContractionDecoration(node->getType().getQualifier()),
1463 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001464 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001465 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1466 node->getType().getBasicType());
1467
1468 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001469 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001470 }
1471
1472 // store the result
1473 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001474 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001475
1476 // assignments are expressions having an rValue after they are evaluated...
1477 builder.clearAccessChain();
1478 builder.setAccessChainRValue(rValue);
1479 }
1480 return false;
1481 case glslang::EOpIndexDirect:
1482 case glslang::EOpIndexDirectStruct:
1483 {
1484 // Get the left part of the access chain.
1485 node->getLeft()->traverse(this);
1486
1487 // Add the next element in the chain
1488
David Netoa901ffe2016-06-08 14:11:40 +01001489 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001490 if (! node->getLeft()->getType().isArray() &&
1491 node->getLeft()->getType().isVector() &&
1492 node->getOp() == glslang::EOpIndexDirect) {
1493 // This is essentially a hard-coded vector swizzle of size 1,
1494 // so short circuit the access-chain stuff with a swizzle.
1495 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001496 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001497 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001498 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001499 int spvIndex = glslangIndex;
1500 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1501 node->getOp() == glslang::EOpIndexDirectStruct)
1502 {
1503 // This may be, e.g., an anonymous block-member selection, which generally need
1504 // index remapping due to hidden members in anonymous blocks.
1505 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1506 assert(remapper.size() > 0);
1507 spvIndex = remapper[glslangIndex];
1508 }
John Kessenichebb50532016-05-16 19:22:05 -06001509
David Netoa901ffe2016-06-08 14:11:40 +01001510 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001511 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001512
1513 // Add capabilities here for accessing PointSize and clip/cull distance.
1514 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001515 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001516 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001517 }
1518 }
1519 return false;
1520 case glslang::EOpIndexIndirect:
1521 {
1522 // Structure or array or vector indirection.
1523 // Will use native SPIR-V access-chain for struct and array indirection;
1524 // matrices are arrays of vectors, so will also work for a matrix.
1525 // Will use the access chain's 'component' for variable index into a vector.
1526
1527 // This adapter is building access chains left to right.
1528 // Set up the access chain to the left.
1529 node->getLeft()->traverse(this);
1530
1531 // save it so that computing the right side doesn't trash it
1532 spv::Builder::AccessChain partial = builder.getAccessChain();
1533
1534 // compute the next index in the chain
1535 builder.clearAccessChain();
1536 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001537 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001538
John Kessenich5611c6d2018-04-05 11:25:02 -06001539 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1540
John Kessenich140f3df2015-06-26 16:58:36 -06001541 // restore the saved access chain
1542 builder.setAccessChain(partial);
1543
1544 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001545 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001546 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001547 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001548 }
1549 return false;
1550 case glslang::EOpVectorSwizzle:
1551 {
1552 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001553 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001554 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001555 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001556 }
1557 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001558 case glslang::EOpMatrixSwizzle:
1559 logger->missingFunctionality("matrix swizzle");
1560 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001561 case glslang::EOpLogicalOr:
1562 case glslang::EOpLogicalAnd:
1563 {
1564
1565 // These may require short circuiting, but can sometimes be done as straight
1566 // binary operations. The right operand must be short circuited if it has
1567 // side effects, and should probably be if it is complex.
1568 if (isTrivial(node->getRight()->getAsTyped()))
1569 break; // handle below as a normal binary operation
1570 // otherwise, we need to do dynamic short circuiting on the right operand
1571 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1572 builder.clearAccessChain();
1573 builder.setAccessChainRValue(result);
1574 }
1575 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001576 default:
1577 break;
1578 }
1579
1580 // Assume generic binary op...
1581
John Kessenich32cfd492016-02-02 12:37:46 -07001582 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001583 builder.clearAccessChain();
1584 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001585 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001586
John Kessenich32cfd492016-02-02 12:37:46 -07001587 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001588 builder.clearAccessChain();
1589 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001590 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001591
John Kessenich32cfd492016-02-02 12:37:46 -07001592 // get result
John Kessenichead86222018-03-28 18:01:20 -06001593 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001594 TranslateNoContractionDecoration(node->getType().getQualifier()),
1595 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001596 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001597 convertGlslangToSpvType(node->getType()), left, right,
1598 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001599
John Kessenich50e57562015-12-21 21:21:11 -07001600 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001601 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001602 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001603 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001604 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001605 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001606 return false;
1607 }
John Kessenich140f3df2015-06-26 16:58:36 -06001608}
1609
1610bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1611{
John Kesseniche485c7a2017-05-31 18:50:53 -06001612 builder.setLine(node->getLoc().line);
1613
qining40887662016-04-03 22:20:42 -04001614 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1615 if (node->getType().getQualifier().isSpecConstant())
1616 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1617
John Kessenichfc51d282015-08-19 13:34:18 -06001618 spv::Id result = spv::NoResult;
1619
1620 // try texturing first
1621 result = createImageTextureFunctionCall(node);
1622 if (result != spv::NoResult) {
1623 builder.clearAccessChain();
1624 builder.setAccessChainRValue(result);
1625
1626 return false; // done with this node
1627 }
1628
1629 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001630
1631 if (node->getOp() == glslang::EOpArrayLength) {
1632 // Quite special; won't want to evaluate the operand.
1633
John Kessenich5611c6d2018-04-05 11:25:02 -06001634 // Currently, the front-end does not allow .length() on an array until it is sized,
1635 // except for the last block membeor of an SSBO.
1636 // TODO: If this changes, link-time sized arrays might show up here, and need their
1637 // size extracted.
1638
John Kessenichc9a80832015-09-12 12:17:44 -06001639 // Normal .length() would have been constant folded by the front-end.
1640 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001641 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001642
John Kessenichc9a80832015-09-12 12:17:44 -06001643 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1644 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001645 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1646 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001647
1648 builder.clearAccessChain();
1649 builder.setAccessChainRValue(length);
1650
1651 return false;
1652 }
1653
John Kessenichfc51d282015-08-19 13:34:18 -06001654 // Start by evaluating the operand
1655
John Kessenich8c8505c2016-07-26 12:50:38 -06001656 // Does it need a swizzle inversion? If so, evaluation is inverted;
1657 // operate first on the swizzle base, then apply the swizzle.
1658 spv::Id invertedType = spv::NoType;
1659 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1660 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1661 invertedType = getInvertedSwizzleType(*node->getOperand());
1662
John Kessenich140f3df2015-06-26 16:58:36 -06001663 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001664 if (invertedType != spv::NoType)
1665 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1666 else
1667 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001668
Rex Xufc618912015-09-09 16:42:49 +08001669 spv::Id operand = spv::NoResult;
1670
1671 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1672 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001673 node->getOp() == glslang::EOpAtomicCounter ||
1674 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001675 operand = builder.accessChainGetLValue(); // Special case l-value operands
1676 else
John Kessenich32cfd492016-02-02 12:37:46 -07001677 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001678
John Kessenichead86222018-03-28 18:01:20 -06001679 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001680 TranslateNoContractionDecoration(node->getType().getQualifier()),
1681 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001682
1683 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001684 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001685 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001686
1687 // if not, then possibly an operation
1688 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001689 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001690
1691 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001692 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001693 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001694 builder.addDecoration(result, decorations.nonUniform);
1695 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001696
John Kessenich140f3df2015-06-26 16:58:36 -06001697 builder.clearAccessChain();
1698 builder.setAccessChainRValue(result);
1699
1700 return false; // done with this node
1701 }
1702
1703 // it must be a special case, check...
1704 switch (node->getOp()) {
1705 case glslang::EOpPostIncrement:
1706 case glslang::EOpPostDecrement:
1707 case glslang::EOpPreIncrement:
1708 case glslang::EOpPreDecrement:
1709 {
1710 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001711 spv::Id one = 0;
1712 if (node->getBasicType() == glslang::EbtFloat)
1713 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001714 else if (node->getBasicType() == glslang::EbtDouble)
1715 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001716 else if (node->getBasicType() == glslang::EbtFloat16)
1717 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001718 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1719 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001720 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1721 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001722 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1723 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001724 else
1725 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001726 glslang::TOperator op;
1727 if (node->getOp() == glslang::EOpPreIncrement ||
1728 node->getOp() == glslang::EOpPostIncrement)
1729 op = glslang::EOpAdd;
1730 else
1731 op = glslang::EOpSub;
1732
John Kessenichead86222018-03-28 18:01:20 -06001733 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001734 convertGlslangToSpvType(node->getType()), operand, one,
1735 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001736 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001737
1738 // The result of operation is always stored, but conditionally the
1739 // consumed result. The consumed result is always an r-value.
1740 builder.accessChainStore(result);
1741 builder.clearAccessChain();
1742 if (node->getOp() == glslang::EOpPreIncrement ||
1743 node->getOp() == glslang::EOpPreDecrement)
1744 builder.setAccessChainRValue(result);
1745 else
1746 builder.setAccessChainRValue(operand);
1747 }
1748
1749 return false;
1750
1751 case glslang::EOpEmitStreamVertex:
1752 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1753 return false;
1754 case glslang::EOpEndStreamPrimitive:
1755 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1756 return false;
1757
1758 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001759 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001760 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001761 }
John Kessenich140f3df2015-06-26 16:58:36 -06001762}
1763
1764bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1765{
qining27e04a02016-04-14 16:40:20 -04001766 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1767 if (node->getType().getQualifier().isSpecConstant())
1768 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1769
John Kessenichfc51d282015-08-19 13:34:18 -06001770 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001771 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1772 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001773
1774 // try texturing
1775 result = createImageTextureFunctionCall(node);
1776 if (result != spv::NoResult) {
1777 builder.clearAccessChain();
1778 builder.setAccessChainRValue(result);
1779
1780 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001781 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001782#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001783 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001784#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001785 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001786 // "imageStore" is a special case, which has no result
1787 return false;
1788 }
John Kessenichfc51d282015-08-19 13:34:18 -06001789
John Kessenich140f3df2015-06-26 16:58:36 -06001790 glslang::TOperator binOp = glslang::EOpNull;
1791 bool reduceComparison = true;
1792 bool isMatrix = false;
1793 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001794 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001795
1796 assert(node->getOp());
1797
John Kessenichf6640762016-08-01 19:44:00 -06001798 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001799
1800 switch (node->getOp()) {
1801 case glslang::EOpSequence:
1802 {
1803 if (preVisit)
1804 ++sequenceDepth;
1805 else
1806 --sequenceDepth;
1807
1808 if (sequenceDepth == 1) {
1809 // If this is the parent node of all the functions, we want to see them
1810 // early, so all call points have actual SPIR-V functions to reference.
1811 // In all cases, still let the traverser visit the children for us.
1812 makeFunctions(node->getAsAggregate()->getSequence());
1813
John Kessenich6fccb3c2016-09-19 16:01:41 -06001814 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001815 // anything else gets there, so visit out of order, doing them all now.
1816 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1817
John Kessenich6a60c2f2016-12-08 21:01:59 -07001818 // 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 -06001819 // so do them manually.
1820 visitFunctions(node->getAsAggregate()->getSequence());
1821
1822 return false;
1823 }
1824
1825 return true;
1826 }
1827 case glslang::EOpLinkerObjects:
1828 {
1829 if (visit == glslang::EvPreVisit)
1830 linkageOnly = true;
1831 else
1832 linkageOnly = false;
1833
1834 return true;
1835 }
1836 case glslang::EOpComma:
1837 {
1838 // processing from left to right naturally leaves the right-most
1839 // lying around in the access chain
1840 glslang::TIntermSequence& glslangOperands = node->getSequence();
1841 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1842 glslangOperands[i]->traverse(this);
1843
1844 return false;
1845 }
1846 case glslang::EOpFunction:
1847 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001848 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001849 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001850 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001851 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001852 } else {
1853 handleFunctionEntry(node);
1854 }
1855 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001856 if (inEntryPoint)
1857 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001858 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001859 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861
1862 return true;
1863 case glslang::EOpParameters:
1864 // Parameters will have been consumed by EOpFunction processing, but not
1865 // the body, so we still visited the function node's children, making this
1866 // child redundant.
1867 return false;
1868 case glslang::EOpFunctionCall:
1869 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001870 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 if (node->isUserDefined())
1872 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001873 // 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 -07001874 if (result) {
1875 builder.clearAccessChain();
1876 builder.setAccessChainRValue(result);
1877 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001878 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001879
1880 return false;
1881 }
1882 case glslang::EOpConstructMat2x2:
1883 case glslang::EOpConstructMat2x3:
1884 case glslang::EOpConstructMat2x4:
1885 case glslang::EOpConstructMat3x2:
1886 case glslang::EOpConstructMat3x3:
1887 case glslang::EOpConstructMat3x4:
1888 case glslang::EOpConstructMat4x2:
1889 case glslang::EOpConstructMat4x3:
1890 case glslang::EOpConstructMat4x4:
1891 case glslang::EOpConstructDMat2x2:
1892 case glslang::EOpConstructDMat2x3:
1893 case glslang::EOpConstructDMat2x4:
1894 case glslang::EOpConstructDMat3x2:
1895 case glslang::EOpConstructDMat3x3:
1896 case glslang::EOpConstructDMat3x4:
1897 case glslang::EOpConstructDMat4x2:
1898 case glslang::EOpConstructDMat4x3:
1899 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001900 case glslang::EOpConstructIMat2x2:
1901 case glslang::EOpConstructIMat2x3:
1902 case glslang::EOpConstructIMat2x4:
1903 case glslang::EOpConstructIMat3x2:
1904 case glslang::EOpConstructIMat3x3:
1905 case glslang::EOpConstructIMat3x4:
1906 case glslang::EOpConstructIMat4x2:
1907 case glslang::EOpConstructIMat4x3:
1908 case glslang::EOpConstructIMat4x4:
1909 case glslang::EOpConstructUMat2x2:
1910 case glslang::EOpConstructUMat2x3:
1911 case glslang::EOpConstructUMat2x4:
1912 case glslang::EOpConstructUMat3x2:
1913 case glslang::EOpConstructUMat3x3:
1914 case glslang::EOpConstructUMat3x4:
1915 case glslang::EOpConstructUMat4x2:
1916 case glslang::EOpConstructUMat4x3:
1917 case glslang::EOpConstructUMat4x4:
1918 case glslang::EOpConstructBMat2x2:
1919 case glslang::EOpConstructBMat2x3:
1920 case glslang::EOpConstructBMat2x4:
1921 case glslang::EOpConstructBMat3x2:
1922 case glslang::EOpConstructBMat3x3:
1923 case glslang::EOpConstructBMat3x4:
1924 case glslang::EOpConstructBMat4x2:
1925 case glslang::EOpConstructBMat4x3:
1926 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001927 case glslang::EOpConstructF16Mat2x2:
1928 case glslang::EOpConstructF16Mat2x3:
1929 case glslang::EOpConstructF16Mat2x4:
1930 case glslang::EOpConstructF16Mat3x2:
1931 case glslang::EOpConstructF16Mat3x3:
1932 case glslang::EOpConstructF16Mat3x4:
1933 case glslang::EOpConstructF16Mat4x2:
1934 case glslang::EOpConstructF16Mat4x3:
1935 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001936 isMatrix = true;
1937 // fall through
1938 case glslang::EOpConstructFloat:
1939 case glslang::EOpConstructVec2:
1940 case glslang::EOpConstructVec3:
1941 case glslang::EOpConstructVec4:
1942 case glslang::EOpConstructDouble:
1943 case glslang::EOpConstructDVec2:
1944 case glslang::EOpConstructDVec3:
1945 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001946 case glslang::EOpConstructFloat16:
1947 case glslang::EOpConstructF16Vec2:
1948 case glslang::EOpConstructF16Vec3:
1949 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001950 case glslang::EOpConstructBool:
1951 case glslang::EOpConstructBVec2:
1952 case glslang::EOpConstructBVec3:
1953 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001954 case glslang::EOpConstructInt8:
1955 case glslang::EOpConstructI8Vec2:
1956 case glslang::EOpConstructI8Vec3:
1957 case glslang::EOpConstructI8Vec4:
1958 case glslang::EOpConstructUint8:
1959 case glslang::EOpConstructU8Vec2:
1960 case glslang::EOpConstructU8Vec3:
1961 case glslang::EOpConstructU8Vec4:
1962 case glslang::EOpConstructInt16:
1963 case glslang::EOpConstructI16Vec2:
1964 case glslang::EOpConstructI16Vec3:
1965 case glslang::EOpConstructI16Vec4:
1966 case glslang::EOpConstructUint16:
1967 case glslang::EOpConstructU16Vec2:
1968 case glslang::EOpConstructU16Vec3:
1969 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001970 case glslang::EOpConstructInt:
1971 case glslang::EOpConstructIVec2:
1972 case glslang::EOpConstructIVec3:
1973 case glslang::EOpConstructIVec4:
1974 case glslang::EOpConstructUint:
1975 case glslang::EOpConstructUVec2:
1976 case glslang::EOpConstructUVec3:
1977 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001978 case glslang::EOpConstructInt64:
1979 case glslang::EOpConstructI64Vec2:
1980 case glslang::EOpConstructI64Vec3:
1981 case glslang::EOpConstructI64Vec4:
1982 case glslang::EOpConstructUint64:
1983 case glslang::EOpConstructU64Vec2:
1984 case glslang::EOpConstructU64Vec3:
1985 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001986 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001987 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001988 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001989 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001990 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001991 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001992 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001993 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001994 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001995 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001996 std::vector<spv::Id> constituents;
1997 for (int c = 0; c < (int)arguments.size(); ++c)
1998 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001999 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002000 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002001 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002002 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002003 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002004
2005 builder.clearAccessChain();
2006 builder.setAccessChainRValue(constructed);
2007
2008 return false;
2009 }
2010
2011 // These six are component-wise compares with component-wise results.
2012 // Forward on to createBinaryOperation(), requesting a vector result.
2013 case glslang::EOpLessThan:
2014 case glslang::EOpGreaterThan:
2015 case glslang::EOpLessThanEqual:
2016 case glslang::EOpGreaterThanEqual:
2017 case glslang::EOpVectorEqual:
2018 case glslang::EOpVectorNotEqual:
2019 {
2020 // Map the operation to a binary
2021 binOp = node->getOp();
2022 reduceComparison = false;
2023 switch (node->getOp()) {
2024 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2025 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2026 default: binOp = node->getOp(); break;
2027 }
2028
2029 break;
2030 }
2031 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002032 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002033 binOp = glslang::EOpMul;
2034 break;
2035 case glslang::EOpOuterProduct:
2036 // two vectors multiplied to make a matrix
2037 binOp = glslang::EOpOuterProduct;
2038 break;
2039 case glslang::EOpDot:
2040 {
qining25262b32016-05-06 17:25:16 -04002041 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002042 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002043 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002044 binOp = glslang::EOpMul;
2045 break;
2046 }
2047 case glslang::EOpMod:
2048 // when an aggregate, this is the floating-point mod built-in function,
2049 // which can be emitted by the one in createBinaryOperation()
2050 binOp = glslang::EOpMod;
2051 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002052 case glslang::EOpEmitVertex:
2053 case glslang::EOpEndPrimitive:
2054 case glslang::EOpBarrier:
2055 case glslang::EOpMemoryBarrier:
2056 case glslang::EOpMemoryBarrierAtomicCounter:
2057 case glslang::EOpMemoryBarrierBuffer:
2058 case glslang::EOpMemoryBarrierImage:
2059 case glslang::EOpMemoryBarrierShared:
2060 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002061 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002062 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002063 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002064 case glslang::EOpWorkgroupMemoryBarrier:
2065 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002066 case glslang::EOpSubgroupBarrier:
2067 case glslang::EOpSubgroupMemoryBarrier:
2068 case glslang::EOpSubgroupMemoryBarrierBuffer:
2069 case glslang::EOpSubgroupMemoryBarrierImage:
2070 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002071 noReturnValue = true;
2072 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2073 break;
2074
Jeff Bolz36831c92018-09-05 10:11:41 -05002075 case glslang::EOpAtomicStore:
2076 noReturnValue = true;
2077 // fallthrough
2078 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002079 case glslang::EOpAtomicAdd:
2080 case glslang::EOpAtomicMin:
2081 case glslang::EOpAtomicMax:
2082 case glslang::EOpAtomicAnd:
2083 case glslang::EOpAtomicOr:
2084 case glslang::EOpAtomicXor:
2085 case glslang::EOpAtomicExchange:
2086 case glslang::EOpAtomicCompSwap:
2087 atomic = true;
2088 break;
2089
John Kessenich0d0c6d32017-07-23 16:08:26 -06002090 case glslang::EOpAtomicCounterAdd:
2091 case glslang::EOpAtomicCounterSubtract:
2092 case glslang::EOpAtomicCounterMin:
2093 case glslang::EOpAtomicCounterMax:
2094 case glslang::EOpAtomicCounterAnd:
2095 case glslang::EOpAtomicCounterOr:
2096 case glslang::EOpAtomicCounterXor:
2097 case glslang::EOpAtomicCounterExchange:
2098 case glslang::EOpAtomicCounterCompSwap:
2099 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2100 builder.addCapability(spv::CapabilityAtomicStorageOps);
2101 atomic = true;
2102 break;
2103
John Kessenich140f3df2015-06-26 16:58:36 -06002104 default:
2105 break;
2106 }
2107
2108 //
2109 // See if it maps to a regular operation.
2110 //
John Kessenich140f3df2015-06-26 16:58:36 -06002111 if (binOp != glslang::EOpNull) {
2112 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2113 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2114 assert(left && right);
2115
2116 builder.clearAccessChain();
2117 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002118 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002119
2120 builder.clearAccessChain();
2121 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002122 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002123
John Kesseniche485c7a2017-05-31 18:50:53 -06002124 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002125 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002126 TranslateNoContractionDecoration(node->getType().getQualifier()),
2127 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002128 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002129 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002130 left->getType().getBasicType(), reduceComparison);
2131
2132 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002133 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002134 builder.clearAccessChain();
2135 builder.setAccessChainRValue(result);
2136
2137 return false;
2138 }
2139
John Kessenich426394d2015-07-23 10:22:48 -06002140 //
2141 // Create the list of operands.
2142 //
John Kessenich140f3df2015-06-26 16:58:36 -06002143 glslang::TIntermSequence& glslangOperands = node->getSequence();
2144 std::vector<spv::Id> operands;
2145 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002146 // special case l-value operands; there are just a few
2147 bool lvalue = false;
2148 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002149 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002150 case glslang::EOpModf:
2151 if (arg == 1)
2152 lvalue = true;
2153 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002154 case glslang::EOpInterpolateAtSample:
2155 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002156#ifdef AMD_EXTENSIONS
2157 case glslang::EOpInterpolateAtVertex:
2158#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002159 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002160 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002161
2162 // Does it need a swizzle inversion? If so, evaluation is inverted;
2163 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002164 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002165 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2166 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2167 }
Rex Xu7a26c172015-12-08 17:12:09 +08002168 break;
Rex Xud4782c12015-09-06 16:30:11 +08002169 case glslang::EOpAtomicAdd:
2170 case glslang::EOpAtomicMin:
2171 case glslang::EOpAtomicMax:
2172 case glslang::EOpAtomicAnd:
2173 case glslang::EOpAtomicOr:
2174 case glslang::EOpAtomicXor:
2175 case glslang::EOpAtomicExchange:
2176 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002177 case glslang::EOpAtomicLoad:
2178 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002179 case glslang::EOpAtomicCounterAdd:
2180 case glslang::EOpAtomicCounterSubtract:
2181 case glslang::EOpAtomicCounterMin:
2182 case glslang::EOpAtomicCounterMax:
2183 case glslang::EOpAtomicCounterAnd:
2184 case glslang::EOpAtomicCounterOr:
2185 case glslang::EOpAtomicCounterXor:
2186 case glslang::EOpAtomicCounterExchange:
2187 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002188 if (arg == 0)
2189 lvalue = true;
2190 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002191 case glslang::EOpAddCarry:
2192 case glslang::EOpSubBorrow:
2193 if (arg == 2)
2194 lvalue = true;
2195 break;
2196 case glslang::EOpUMulExtended:
2197 case glslang::EOpIMulExtended:
2198 if (arg >= 2)
2199 lvalue = true;
2200 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002201 default:
2202 break;
2203 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002204 builder.clearAccessChain();
2205 if (invertedType != spv::NoType && arg == 0)
2206 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2207 else
2208 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002209 if (lvalue)
2210 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002211 else {
2212 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002213 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002214 }
John Kessenich140f3df2015-06-26 16:58:36 -06002215 }
John Kessenich426394d2015-07-23 10:22:48 -06002216
John Kesseniche485c7a2017-05-31 18:50:53 -06002217 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002218 if (atomic) {
2219 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002220 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002221 } else {
2222 // Pass through to generic operations.
2223 switch (glslangOperands.size()) {
2224 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002225 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002226 break;
2227 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002228 {
2229 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002230 TranslateNoContractionDecoration(node->getType().getQualifier()),
2231 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002232 result = createUnaryOperation(
2233 node->getOp(), decorations,
2234 resultType(), operands.front(),
2235 glslangOperands[0]->getAsTyped()->getBasicType());
2236 }
John Kessenich426394d2015-07-23 10:22:48 -06002237 break;
2238 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002239 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002240 break;
2241 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002242 if (invertedType)
2243 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002244 }
2245
2246 if (noReturnValue)
2247 return false;
2248
2249 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002250 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002251 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002252 } else {
2253 builder.clearAccessChain();
2254 builder.setAccessChainRValue(result);
2255 return false;
2256 }
2257}
2258
John Kessenich433e9ff2017-01-26 20:31:11 -07002259// This path handles both if-then-else and ?:
2260// The if-then-else has a node type of void, while
2261// ?: has either a void or a non-void node type
2262//
2263// Leaving the result, when not void:
2264// GLSL only has r-values as the result of a :?, but
2265// if we have an l-value, that can be more efficient if it will
2266// become the base of a complex r-value expression, because the
2267// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002268bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2269{
John Kessenich4bee5312018-02-20 21:29:05 -07002270 // See if it simple and safe, or required, to execute both sides.
2271 // Crucially, side effects must be either semantically required or avoided,
2272 // and there are performance trade-offs.
2273 // Return true if required or a good idea (and safe) to execute both sides,
2274 // false otherwise.
2275 const auto bothSidesPolicy = [&]() -> bool {
2276 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002277 if (node->getTrueBlock() == nullptr ||
2278 node->getFalseBlock() == nullptr)
2279 return false;
2280
John Kessenich4bee5312018-02-20 21:29:05 -07002281 // required? (unless we write additional code to look for side effects
2282 // and make performance trade-offs if none are present)
2283 if (!node->getShortCircuit())
2284 return true;
2285
2286 // if not required to execute both, decide based on performance/practicality...
2287
2288 // see if OpSelect can handle it
2289 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2290 node->getBasicType() == glslang::EbtVoid)
2291 return false;
2292
John Kessenich433e9ff2017-01-26 20:31:11 -07002293 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2294 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2295
2296 // return true if a single operand to ? : is okay for OpSelect
2297 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002298 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002299 };
2300
2301 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2302 operandOkay(node->getFalseBlock()->getAsTyped());
2303 };
2304
John Kessenich4bee5312018-02-20 21:29:05 -07002305 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2306 // emit the condition before doing anything with selection
2307 node->getCondition()->traverse(this);
2308 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2309
2310 // Find a way of executing both sides and selecting the right result.
2311 const auto executeBothSides = [&]() -> void {
2312 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002313 node->getTrueBlock()->traverse(this);
2314 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2315 node->getFalseBlock()->traverse(this);
2316 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2317
John Kesseniche485c7a2017-05-31 18:50:53 -06002318 builder.setLine(node->getLoc().line);
2319
John Kessenich4bee5312018-02-20 21:29:05 -07002320 // done if void
2321 if (node->getBasicType() == glslang::EbtVoid)
2322 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002323
John Kessenich4bee5312018-02-20 21:29:05 -07002324 // emit code to select between trueValue and falseValue
2325
2326 // see if OpSelect can handle it
2327 if (node->getType().isScalar() || node->getType().isVector()) {
2328 // Emit OpSelect for this selection.
2329
2330 // smear condition to vector, if necessary (AST is always scalar)
2331 if (builder.isVector(trueValue))
2332 condition = builder.smearScalar(spv::NoPrecision, condition,
2333 builder.makeVectorType(builder.makeBoolType(),
2334 builder.getNumComponents(trueValue)));
2335
2336 // OpSelect
2337 result = builder.createTriOp(spv::OpSelect,
2338 convertGlslangToSpvType(node->getType()), condition,
2339 trueValue, falseValue);
2340
2341 builder.clearAccessChain();
2342 builder.setAccessChainRValue(result);
2343 } else {
2344 // We need control flow to select the result.
2345 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2346 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2347
2348 // Selection control:
2349 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2350
2351 // make an "if" based on the value created by the condition
2352 spv::Builder::If ifBuilder(condition, control, builder);
2353
2354 // emit the "then" statement
2355 builder.createStore(trueValue, result);
2356 ifBuilder.makeBeginElse();
2357 // emit the "else" statement
2358 builder.createStore(falseValue, result);
2359
2360 // finish off the control flow
2361 ifBuilder.makeEndIf();
2362
2363 builder.clearAccessChain();
2364 builder.setAccessChainLValue(result);
2365 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002366 };
2367
John Kessenich4bee5312018-02-20 21:29:05 -07002368 // Execute the one side needed, as per the condition
2369 const auto executeOneSide = [&]() {
2370 // Always emit control flow.
2371 if (node->getBasicType() != glslang::EbtVoid)
2372 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002373
John Kessenich4bee5312018-02-20 21:29:05 -07002374 // Selection control:
2375 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2376
2377 // make an "if" based on the value created by the condition
2378 spv::Builder::If ifBuilder(condition, control, builder);
2379
2380 // emit the "then" statement
2381 if (node->getTrueBlock() != nullptr) {
2382 node->getTrueBlock()->traverse(this);
2383 if (result != spv::NoResult)
2384 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2385 }
2386
2387 if (node->getFalseBlock() != nullptr) {
2388 ifBuilder.makeBeginElse();
2389 // emit the "else" statement
2390 node->getFalseBlock()->traverse(this);
2391 if (result != spv::NoResult)
2392 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2393 }
2394
2395 // finish off the control flow
2396 ifBuilder.makeEndIf();
2397
2398 if (result != spv::NoResult) {
2399 builder.clearAccessChain();
2400 builder.setAccessChainLValue(result);
2401 }
2402 };
2403
2404 // Try for OpSelect (or a requirement to execute both sides)
2405 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002406 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2407 if (node->getType().getQualifier().isSpecConstant())
2408 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002409 executeBothSides();
2410 } else
2411 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002412
2413 return false;
2414}
2415
2416bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2417{
2418 // emit and get the condition before doing anything with switch
2419 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002420 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002421
Rex Xu57e65922017-07-04 23:23:40 +08002422 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002423 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002424
John Kessenich140f3df2015-06-26 16:58:36 -06002425 // browse the children to sort out code segments
2426 int defaultSegment = -1;
2427 std::vector<TIntermNode*> codeSegments;
2428 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2429 std::vector<int> caseValues;
2430 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2431 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2432 TIntermNode* child = *c;
2433 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002434 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002435 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002436 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002437 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2438 } else
2439 codeSegments.push_back(child);
2440 }
2441
qining25262b32016-05-06 17:25:16 -04002442 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002443 // statements between the last case and the end of the switch statement
2444 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2445 (int)codeSegments.size() == defaultSegment)
2446 codeSegments.push_back(nullptr);
2447
2448 // make the switch statement
2449 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002450 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002451
2452 // emit all the code in the segments
2453 breakForLoop.push(false);
2454 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2455 builder.nextSwitchSegment(segmentBlocks, s);
2456 if (codeSegments[s])
2457 codeSegments[s]->traverse(this);
2458 else
2459 builder.addSwitchBreak();
2460 }
2461 breakForLoop.pop();
2462
2463 builder.endSwitch(segmentBlocks);
2464
2465 return false;
2466}
2467
2468void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2469{
2470 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002471 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002472
2473 builder.clearAccessChain();
2474 builder.setAccessChainRValue(constant);
2475}
2476
2477bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2478{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002479 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002480 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002481
2482 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002483 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2484 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002485
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002486 // Spec requires back edges to target header blocks, and every header block
2487 // must dominate its merge block. Make a header block first to ensure these
2488 // conditions are met. By definition, it will contain OpLoopMerge, followed
2489 // by a block-ending branch. But we don't want to put any other body/test
2490 // instructions in it, since the body/test may have arbitrary instructions,
2491 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002492 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002493 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002494 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002495 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002496 spv::Block& test = builder.makeNewBlock();
2497 builder.createBranch(&test);
2498
2499 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002500 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002501 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002502 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2503
2504 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002505 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002506 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002507 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002508 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002509 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002510
2511 builder.setBuildPoint(&blocks.continue_target);
2512 if (node->getTerminal())
2513 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002514 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002515 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002516 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002517 builder.createBranch(&blocks.body);
2518
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002519 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002520 builder.setBuildPoint(&blocks.body);
2521 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002522 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002523 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002524 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002525
2526 builder.setBuildPoint(&blocks.continue_target);
2527 if (node->getTerminal())
2528 node->getTerminal()->traverse(this);
2529 if (node->getTest()) {
2530 node->getTest()->traverse(this);
2531 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002532 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002533 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002534 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002535 // TODO: unless there was a break/return/discard instruction
2536 // somewhere in the body, this is an infinite loop, so we should
2537 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002538 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002539 }
John Kessenich140f3df2015-06-26 16:58:36 -06002540 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002541 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002542 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002543 return false;
2544}
2545
2546bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2547{
2548 if (node->getExpression())
2549 node->getExpression()->traverse(this);
2550
John Kesseniche485c7a2017-05-31 18:50:53 -06002551 builder.setLine(node->getLoc().line);
2552
John Kessenich140f3df2015-06-26 16:58:36 -06002553 switch (node->getFlowOp()) {
2554 case glslang::EOpKill:
2555 builder.makeDiscard();
2556 break;
2557 case glslang::EOpBreak:
2558 if (breakForLoop.top())
2559 builder.createLoopExit();
2560 else
2561 builder.addSwitchBreak();
2562 break;
2563 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002564 builder.createLoopContinue();
2565 break;
2566 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002567 if (node->getExpression()) {
2568 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2569 spv::Id returnId = accessChainLoad(glslangReturnType);
2570 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2571 builder.clearAccessChain();
2572 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2573 builder.setAccessChainLValue(copyId);
2574 multiTypeStore(glslangReturnType, returnId);
2575 returnId = builder.createLoad(copyId);
2576 }
2577 builder.makeReturn(false, returnId);
2578 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002579 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002580
2581 builder.clearAccessChain();
2582 break;
2583
2584 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002585 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002586 break;
2587 }
2588
2589 return false;
2590}
2591
2592spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2593{
qining25262b32016-05-06 17:25:16 -04002594 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002595 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002596 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002597 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002598 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002599 }
2600
2601 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002602 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002603 spv::Id spvType = convertGlslangToSpvType(node->getType());
2604
Rex Xucabbb782017-03-24 13:41:14 +08002605 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2606 node->getType().containsBasicType(glslang::EbtInt16) ||
2607 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002608 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002609 switch (storageClass) {
2610 case spv::StorageClassInput:
2611 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002612 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002613 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002614 break;
2615 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002616 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002617 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002618 break;
2619 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002620 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002621 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2622 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002623 else
2624 builder.addCapability(spv::CapabilityStorageUniform16);
2625 break;
2626 case spv::StorageClassStorageBuffer:
2627 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2628 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2629 break;
2630 default:
2631 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002632 }
2633 }
Rex Xuf89ad982017-04-07 23:22:33 +08002634
John Kessenich312dcfb2018-07-03 13:19:51 -06002635 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2636 node->getType().containsBasicType(glslang::EbtUint8);
2637 if (contains8BitType) {
2638 if (storageClass == spv::StorageClassPushConstant) {
2639 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2640 builder.addCapability(spv::CapabilityStoragePushConstant8);
2641 } else if (storageClass == spv::StorageClassUniform) {
2642 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2643 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2644 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2645 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2646 }
2647 }
2648
John Kessenich140f3df2015-06-26 16:58:36 -06002649 const char* name = node->getName().c_str();
2650 if (glslang::IsAnonymous(name))
2651 name = "";
2652
2653 return builder.createVariable(storageClass, spvType, name);
2654}
2655
2656// Return type Id of the sampled type.
2657spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2658{
2659 switch (sampler.type) {
2660 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002661#ifdef AMD_EXTENSIONS
2662 case glslang::EbtFloat16:
2663 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2664 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2665 return builder.makeFloatType(16);
2666#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002667 case glslang::EbtInt: return builder.makeIntType(32);
2668 case glslang::EbtUint: return builder.makeUintType(32);
2669 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002670 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002671 return builder.makeFloatType(32);
2672 }
2673}
2674
John Kessenich8c8505c2016-07-26 12:50:38 -06002675// If node is a swizzle operation, return the type that should be used if
2676// the swizzle base is first consumed by another operation, before the swizzle
2677// is applied.
2678spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2679{
John Kessenichecba76f2017-01-06 00:34:48 -07002680 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002681 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2682 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2683 else
2684 return spv::NoType;
2685}
2686
2687// When inverting a swizzle with a parent op, this function
2688// will apply the swizzle operation to a completed parent operation.
2689spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2690{
2691 std::vector<unsigned> swizzle;
2692 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2693 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2694}
2695
John Kessenich8c8505c2016-07-26 12:50:38 -06002696// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2697void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2698{
2699 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2700 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2701 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2702}
2703
John Kessenich3ac051e2015-12-20 11:29:16 -07002704// Convert from a glslang type to an SPV type, by calling into a
2705// recursive version of this function. This establishes the inherited
2706// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002707spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2708{
John Kessenichead86222018-03-28 18:01:20 -06002709 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002710}
2711
2712// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002713// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002714// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002715spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2716 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002717{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002718 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002719
2720 switch (type.getBasicType()) {
2721 case glslang::EbtVoid:
2722 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002723 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002724 break;
2725 case glslang::EbtFloat:
2726 spvType = builder.makeFloatType(32);
2727 break;
2728 case glslang::EbtDouble:
2729 spvType = builder.makeFloatType(64);
2730 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002731 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002732#if AMD_EXTENSIONS
2733 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2734 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2735#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002736 spvType = builder.makeFloatType(16);
2737 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002738 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002739 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2740 // a 32-bit int where non-0 means true.
2741 if (explicitLayout != glslang::ElpNone)
2742 spvType = builder.makeUintType(32);
2743 else
2744 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002745 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002746 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002747 spvType = builder.makeIntType(8);
2748 break;
2749 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002750 spvType = builder.makeUintType(8);
2751 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002752 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002753#ifdef AMD_EXTENSIONS
2754 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2755 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2756#endif
2757 spvType = builder.makeIntType(16);
2758 break;
2759 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002760#ifdef AMD_EXTENSIONS
2761 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2762 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2763#endif
2764 spvType = builder.makeUintType(16);
2765 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002766 case glslang::EbtInt:
2767 spvType = builder.makeIntType(32);
2768 break;
2769 case glslang::EbtUint:
2770 spvType = builder.makeUintType(32);
2771 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002772 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002773 spvType = builder.makeIntType(64);
2774 break;
2775 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002776 spvType = builder.makeUintType(64);
2777 break;
John Kessenich426394d2015-07-23 10:22:48 -06002778 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002779 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002780 spvType = builder.makeUintType(32);
2781 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002782 case glslang::EbtSampler:
2783 {
2784 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002785 if (sampler.sampler) {
2786 // pure sampler
2787 spvType = builder.makeSamplerType();
2788 } else {
2789 // an image is present, make its type
2790 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2791 sampler.image ? 2 : 1, TranslateImageFormat(type));
2792 if (sampler.combined) {
2793 // already has both image and sampler, make the combined type
2794 spvType = builder.makeSampledImageType(spvType);
2795 }
John Kessenich55e7d112015-11-15 21:33:39 -07002796 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002797 }
John Kessenich140f3df2015-06-26 16:58:36 -06002798 break;
2799 case glslang::EbtStruct:
2800 case glslang::EbtBlock:
2801 {
2802 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002803 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002804
2805 // Try to share structs for different layouts, but not yet for other
2806 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002807 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002808 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002809 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002810 break;
2811
2812 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002813 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002814 memberRemapper[glslangMembers].resize(glslangMembers->size());
2815 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002816 }
2817 break;
2818 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002819 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002820 break;
2821 }
2822
2823 if (type.isMatrix())
2824 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2825 else {
2826 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2827 if (type.getVectorSize() > 1)
2828 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2829 }
2830
2831 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002832 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2833
John Kessenichc9a80832015-09-12 12:17:44 -06002834 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002835 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002836 // We need to decorate array strides for types needing explicit layout, except blocks.
2837 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002838 // Use a dummy glslang type for querying internal strides of
2839 // arrays of arrays, but using just a one-dimensional array.
2840 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002841 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2842 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002843
2844 // Will compute the higher-order strides here, rather than making a whole
2845 // pile of types and doing repetitive recursion on their contents.
2846 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2847 }
John Kessenichf8842e52016-01-04 19:22:56 -07002848
2849 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002850 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002851 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002852 if (stride > 0)
2853 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002854 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002855 }
2856 } else {
2857 // single-dimensional array, and don't yet have stride
2858
John Kessenichf8842e52016-01-04 19:22:56 -07002859 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002860 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2861 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002862 }
John Kessenich31ed4832015-09-09 17:51:38 -06002863
John Kessenichead86222018-03-28 18:01:20 -06002864 // Do the outer dimension, which might not be known for a runtime-sized array.
2865 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2866 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002867 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002868 else {
2869 if (!lastBufferBlockMember) {
2870 builder.addExtension("SPV_EXT_descriptor_indexing");
2871 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2872 }
John Kessenichead86222018-03-28 18:01:20 -06002873 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002874 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002875 if (stride > 0)
2876 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002877 }
2878
2879 return spvType;
2880}
2881
John Kessenich0e737842017-03-24 18:38:16 -06002882// TODO: this functionality should exist at a higher level, in creating the AST
2883//
2884// Identify interface members that don't have their required extension turned on.
2885//
2886bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2887{
2888 auto& extensions = glslangIntermediate->getRequestedExtensions();
2889
Rex Xubcf291a2017-03-29 23:01:36 +08002890 if (member.getFieldName() == "gl_ViewportMask" &&
2891 extensions.find("GL_NV_viewport_array2") == extensions.end())
2892 return true;
2893 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2894 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2895 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002896 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2897 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2898 return true;
2899 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2900 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2901 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002902 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2903 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2904 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002905
2906 return false;
2907};
2908
John Kessenich6090df02016-06-30 21:18:02 -06002909// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2910// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2911// Mutually recursive with convertGlslangToSpvType().
2912spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2913 const glslang::TTypeList* glslangMembers,
2914 glslang::TLayoutPacking explicitLayout,
2915 const glslang::TQualifier& qualifier)
2916{
2917 // Create a vector of struct types for SPIR-V to consume
2918 std::vector<spv::Id> spvMembers;
2919 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 -06002920 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2921 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2922 if (glslangMember.hiddenMember()) {
2923 ++memberDelta;
2924 if (type.getBasicType() == glslang::EbtBlock)
2925 memberRemapper[glslangMembers][i] = -1;
2926 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002927 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002928 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002929 if (filterMember(glslangMember))
2930 continue;
2931 }
John Kessenich6090df02016-06-30 21:18:02 -06002932 // modify just this child's view of the qualifier
2933 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2934 InheritQualifiers(memberQualifier, qualifier);
2935
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002936 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002937 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002938 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002939
2940 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002941 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2942 i == (int)glslangMembers->size() - 1;
2943 spvMembers.push_back(
2944 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002945 }
2946 }
2947
2948 // Make the SPIR-V type
2949 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002950 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002951 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2952
2953 // Decorate it
2954 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2955
2956 return spvType;
2957}
2958
2959void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2960 const glslang::TTypeList* glslangMembers,
2961 glslang::TLayoutPacking explicitLayout,
2962 const glslang::TQualifier& qualifier,
2963 spv::Id spvType)
2964{
2965 // Name and decorate the non-hidden members
2966 int offset = -1;
2967 int locationOffset = 0; // for use within the members of this struct
2968 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2969 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2970 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002971 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002972 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002973 if (filterMember(glslangMember))
2974 continue;
2975 }
John Kessenich6090df02016-06-30 21:18:02 -06002976
2977 // modify just this child's view of the qualifier
2978 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2979 InheritQualifiers(memberQualifier, qualifier);
2980
2981 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002982 if (member < 0)
2983 continue;
2984
2985 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2986 builder.addMemberDecoration(spvType, member,
2987 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2988 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2989 // Add interpolation and auxiliary storage decorations only to
2990 // top-level members of Input and Output storage classes
2991 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2992 type.getQualifier().storage == glslang::EvqVaryingOut) {
2993 if (type.getBasicType() == glslang::EbtBlock ||
2994 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2995 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2996 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002997 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002998 }
2999 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003000
John Kessenich5d610ee2018-03-07 18:05:55 -07003001 if (type.getBasicType() == glslang::EbtBlock &&
3002 qualifier.storage == glslang::EvqBuffer) {
3003 // Add memory decorations only to top-level members of shader storage block
3004 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003005 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003006 for (unsigned int i = 0; i < memory.size(); ++i)
3007 builder.addMemberDecoration(spvType, member, memory[i]);
3008 }
John Kessenich6090df02016-06-30 21:18:02 -06003009
John Kessenich5d610ee2018-03-07 18:05:55 -07003010 // Location assignment was already completed correctly by the front end,
3011 // just track whether a member needs to be decorated.
3012 // Ignore member locations if the container is an array, as that's
3013 // ill-specified and decisions have been made to not allow this.
3014 if (! type.isArray() && memberQualifier.hasLocation())
3015 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003016
John Kessenich5d610ee2018-03-07 18:05:55 -07003017 if (qualifier.hasLocation()) // track for upcoming inheritance
3018 locationOffset += glslangIntermediate->computeTypeLocationSize(
3019 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003020
John Kessenich5d610ee2018-03-07 18:05:55 -07003021 // component, XFB, others
3022 if (glslangMember.getQualifier().hasComponent())
3023 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3024 glslangMember.getQualifier().layoutComponent);
3025 if (glslangMember.getQualifier().hasXfbOffset())
3026 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3027 glslangMember.getQualifier().layoutXfbOffset);
3028 else if (explicitLayout != glslang::ElpNone) {
3029 // figure out what to do with offset, which is accumulating
3030 int nextOffset;
3031 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3032 if (offset >= 0)
3033 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3034 offset = nextOffset;
3035 }
John Kessenich6090df02016-06-30 21:18:02 -06003036
John Kessenich5d610ee2018-03-07 18:05:55 -07003037 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3038 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3039 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003040
John Kessenich5d610ee2018-03-07 18:05:55 -07003041 // built-in variable decorations
3042 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3043 if (builtIn != spv::BuiltInMax)
3044 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003045
John Kessenich5611c6d2018-04-05 11:25:02 -06003046 // nonuniform
3047 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3048
John Kessenichead86222018-03-28 18:01:20 -06003049 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3050 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3051 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3052 memberQualifier.semanticName);
3053 }
3054
chaoc771d89f2017-01-13 01:10:53 -08003055#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003056 if (builtIn == spv::BuiltInLayer) {
3057 // SPV_NV_viewport_array2 extension
3058 if (glslangMember.getQualifier().layoutViewportRelative){
3059 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3060 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3061 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003062 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003063 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3064 builder.addMemberDecoration(spvType, member,
3065 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3066 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3067 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3068 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003069 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003070 }
3071 if (glslangMember.getQualifier().layoutPassthrough) {
3072 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3073 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3074 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3075 }
chaoc771d89f2017-01-13 01:10:53 -08003076#endif
John Kessenich6090df02016-06-30 21:18:02 -06003077 }
3078
3079 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003080 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3081 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003082 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3083 builder.addCapability(spv::CapabilityGeometryStreams);
3084 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3085 }
John Kessenich6090df02016-06-30 21:18:02 -06003086}
3087
John Kessenich6c292d32016-02-15 20:58:50 -07003088// Turn the expression forming the array size into an id.
3089// This is not quite trivial, because of specialization constants.
3090// Sometimes, a raw constant is turned into an Id, and sometimes
3091// a specialization constant expression is.
3092spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3093{
3094 // First, see if this is sized with a node, meaning a specialization constant:
3095 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3096 if (specNode != nullptr) {
3097 builder.clearAccessChain();
3098 specNode->traverse(this);
3099 return accessChainLoad(specNode->getAsTyped()->getType());
3100 }
qining25262b32016-05-06 17:25:16 -04003101
John Kessenich6c292d32016-02-15 20:58:50 -07003102 // Otherwise, need a compile-time (front end) size, get it:
3103 int size = arraySizes.getDimSize(dim);
3104 assert(size > 0);
3105 return builder.makeUintConstant(size);
3106}
3107
John Kessenich103bef92016-02-08 21:38:15 -07003108// Wrap the builder's accessChainLoad to:
3109// - localize handling of RelaxedPrecision
3110// - use the SPIR-V inferred type instead of another conversion of the glslang type
3111// (avoids unnecessary work and possible type punning for structures)
3112// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003113spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3114{
John Kessenich103bef92016-02-08 21:38:15 -07003115 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003116
3117 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3118 coherentFlags |= TranslateCoherent(type);
3119
John Kessenich5611c6d2018-04-05 11:25:02 -06003120 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003121 TranslateNonUniformDecoration(type.getQualifier()),
3122 nominalTypeId,
3123 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3124 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003125
3126 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003127 if (type.getBasicType() == glslang::EbtBool) {
3128 if (builder.isScalarType(nominalTypeId)) {
3129 // Conversion for bool
3130 spv::Id boolType = builder.makeBoolType();
3131 if (nominalTypeId != boolType)
3132 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3133 } else if (builder.isVectorType(nominalTypeId)) {
3134 // Conversion for bvec
3135 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3136 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3137 if (nominalTypeId != bvecType)
3138 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3139 }
3140 }
John Kessenich103bef92016-02-08 21:38:15 -07003141
3142 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003143}
3144
Rex Xu27253232016-02-23 17:51:09 +08003145// Wrap the builder's accessChainStore to:
3146// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003147//
3148// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003149void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3150{
3151 // Need to convert to abstract types when necessary
3152 if (type.getBasicType() == glslang::EbtBool) {
3153 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3154
3155 if (builder.isScalarType(nominalTypeId)) {
3156 // Conversion for bool
3157 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003158 if (nominalTypeId != boolType) {
3159 // keep these outside arguments, for determinant order-of-evaluation
3160 spv::Id one = builder.makeUintConstant(1);
3161 spv::Id zero = builder.makeUintConstant(0);
3162 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3163 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003164 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003165 } else if (builder.isVectorType(nominalTypeId)) {
3166 // Conversion for bvec
3167 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3168 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003169 if (nominalTypeId != bvecType) {
3170 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003171 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3172 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3173 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003174 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003175 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3176 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003177 }
3178 }
3179
Jeff Bolz36831c92018-09-05 10:11:41 -05003180 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3181 coherentFlags |= TranslateCoherent(type);
3182
3183 builder.accessChainStore(rvalue,
3184 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3185 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003186}
3187
John Kessenich4bf71552016-09-02 11:20:21 -06003188// For storing when types match at the glslang level, but not might match at the
3189// SPIR-V level.
3190//
3191// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003192// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003193// as in a member-decorated way.
3194//
3195// NOTE: This function can handle any store request; if it's not special it
3196// simplifies to a simple OpStore.
3197//
3198// Implicitly uses the existing builder.accessChain as the storage target.
3199void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3200{
John Kessenichb3e24e42016-09-11 12:33:43 -06003201 // we only do the complex path here if it's an aggregate
3202 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003203 accessChainStore(type, rValue);
3204 return;
3205 }
3206
John Kessenichb3e24e42016-09-11 12:33:43 -06003207 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003208 spv::Id rType = builder.getTypeId(rValue);
3209 spv::Id lValue = builder.accessChainGetLValue();
3210 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3211 if (lType == rType) {
3212 accessChainStore(type, rValue);
3213 return;
3214 }
3215
John Kessenichb3e24e42016-09-11 12:33:43 -06003216 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003217 // where the two types were the same type in GLSL. This requires member
3218 // by member copy, recursively.
3219
John Kessenichb3e24e42016-09-11 12:33:43 -06003220 // If an array, copy element by element.
3221 if (type.isArray()) {
3222 glslang::TType glslangElementType(type, 0);
3223 spv::Id elementRType = builder.getContainedTypeId(rType);
3224 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3225 // get the source member
3226 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003227
John Kessenichb3e24e42016-09-11 12:33:43 -06003228 // set up the target storage
3229 builder.clearAccessChain();
3230 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003231 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003232
John Kessenichb3e24e42016-09-11 12:33:43 -06003233 // store the member
3234 multiTypeStore(glslangElementType, elementRValue);
3235 }
3236 } else {
3237 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003238
John Kessenichb3e24e42016-09-11 12:33:43 -06003239 // loop over structure members
3240 const glslang::TTypeList& members = *type.getStruct();
3241 for (int m = 0; m < (int)members.size(); ++m) {
3242 const glslang::TType& glslangMemberType = *members[m].type;
3243
3244 // get the source member
3245 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3246 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3247
3248 // set up the target storage
3249 builder.clearAccessChain();
3250 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003251 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003252
3253 // store the member
3254 multiTypeStore(glslangMemberType, memberRValue);
3255 }
John Kessenich4bf71552016-09-02 11:20:21 -06003256 }
3257}
3258
John Kessenichf85e8062015-12-19 13:57:10 -07003259// Decide whether or not this type should be
3260// decorated with offsets and strides, and if so
3261// whether std140 or std430 rules should be applied.
3262glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003263{
John Kessenichf85e8062015-12-19 13:57:10 -07003264 // has to be a block
3265 if (type.getBasicType() != glslang::EbtBlock)
3266 return glslang::ElpNone;
3267
3268 // has to be a uniform or buffer block
3269 if (type.getQualifier().storage != glslang::EvqUniform &&
3270 type.getQualifier().storage != glslang::EvqBuffer)
3271 return glslang::ElpNone;
3272
3273 // return the layout to use
3274 switch (type.getQualifier().layoutPacking) {
3275 case glslang::ElpStd140:
3276 case glslang::ElpStd430:
3277 return type.getQualifier().layoutPacking;
3278 default:
3279 return glslang::ElpNone;
3280 }
John Kessenich31ed4832015-09-09 17:51:38 -06003281}
3282
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003283// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003284int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003285{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003286 int size;
John Kessenich49987892015-12-29 17:11:44 -07003287 int stride;
3288 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003289
3290 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003291}
3292
John Kessenich49987892015-12-29 17:11:44 -07003293// 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 -07003294// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003295int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003296{
John Kessenich49987892015-12-29 17:11:44 -07003297 glslang::TType elementType;
3298 elementType.shallowCopy(matrixType);
3299 elementType.clearArraySizes();
3300
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003301 int size;
John Kessenich49987892015-12-29 17:11:44 -07003302 int stride;
3303 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3304
3305 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003306}
3307
John Kessenich5e4b1242015-08-06 22:53:06 -06003308// Given a member type of a struct, realign the current offset for it, and compute
3309// the next (not yet aligned) offset for the next member, which will get aligned
3310// on the next call.
3311// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3312// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3313// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003314void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003315 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003316{
3317 // this will get a positive value when deemed necessary
3318 nextOffset = -1;
3319
John Kessenich5e4b1242015-08-06 22:53:06 -06003320 // override anything in currentOffset with user-set offset
3321 if (memberType.getQualifier().hasOffset())
3322 currentOffset = memberType.getQualifier().layoutOffset;
3323
3324 // It could be that current linker usage in glslang updated all the layoutOffset,
3325 // in which case the following code does not matter. But, that's not quite right
3326 // once cross-compilation unit GLSL validation is done, as the original user
3327 // settings are needed in layoutOffset, and then the following will come into play.
3328
John Kessenichf85e8062015-12-19 13:57:10 -07003329 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003330 if (! memberType.getQualifier().hasOffset())
3331 currentOffset = -1;
3332
3333 return;
3334 }
3335
John Kessenichf85e8062015-12-19 13:57:10 -07003336 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003337 if (currentOffset < 0)
3338 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003339
John Kessenich5e4b1242015-08-06 22:53:06 -06003340 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3341 // but possibly not yet correctly aligned.
3342
3343 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003344 int dummyStride;
3345 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003346
3347 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003348 // TODO: make this consistent in early phases of code:
3349 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3350 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3351 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003352 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003353 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003354 int dummySize;
3355 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3356 if (componentAlignment <= 4)
3357 memberAlignment = componentAlignment;
3358 }
3359
3360 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003361 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003362
3363 // Bump up to vec4 if there is a bad straddle
3364 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3365 glslang::RoundToPow2(currentOffset, 16);
3366
John Kessenich5e4b1242015-08-06 22:53:06 -06003367 nextOffset = currentOffset + memberSize;
3368}
3369
David Netoa901ffe2016-06-08 14:11:40 +01003370void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003371{
David Netoa901ffe2016-06-08 14:11:40 +01003372 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3373 switch (glslangBuiltIn)
3374 {
3375 case glslang::EbvClipDistance:
3376 case glslang::EbvCullDistance:
3377 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003378#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003379 case glslang::EbvViewportMaskNV:
3380 case glslang::EbvSecondaryPositionNV:
3381 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003382 case glslang::EbvPositionPerViewNV:
3383 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003384#endif
David Netoa901ffe2016-06-08 14:11:40 +01003385 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3386 // Alternately, we could just call this for any glslang built-in, since the
3387 // capability already guards against duplicates.
3388 TranslateBuiltInDecoration(glslangBuiltIn, false);
3389 break;
3390 default:
3391 // Capabilities were already generated when the struct was declared.
3392 break;
3393 }
John Kessenichebb50532016-05-16 19:22:05 -06003394}
3395
John Kessenich6fccb3c2016-09-19 16:01:41 -06003396bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003397{
John Kessenicheee9d532016-09-19 18:09:30 -06003398 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003399}
3400
John Kessenichd41993d2017-09-10 15:21:05 -06003401// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003402// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3403// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003404bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003405{
John Kessenich6a14f782017-12-04 02:48:10 -07003406 assert(qualifier == glslang::EvqIn ||
3407 qualifier == glslang::EvqOut ||
3408 qualifier == glslang::EvqInOut ||
3409 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003410 return qualifier != glslang::EvqConstReadOnly;
3411}
3412
3413// Is parameter pass-by-original?
3414bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3415 bool implicitThisParam)
3416{
3417 if (implicitThisParam) // implicit this
3418 return true;
3419 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003420 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003421 return paramType.containsOpaque() || // sampler, etc.
3422 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3423}
3424
John Kessenich140f3df2015-06-26 16:58:36 -06003425// Make all the functions, skeletally, without actually visiting their bodies.
3426void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3427{
Jeff Bolz36831c92018-09-05 10:11:41 -05003428 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003429 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3430 if (paramPrecision != spv::NoPrecision)
3431 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003432 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003433 };
3434
John Kessenich140f3df2015-06-26 16:58:36 -06003435 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3436 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003437 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003438 continue;
3439
3440 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003441 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003442 //
qining25262b32016-05-06 17:25:16 -04003443 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003444 // function. What it is an address of varies:
3445 //
John Kessenich4bf71552016-09-02 11:20:21 -06003446 // - "in" parameters not marked as "const" can be written to without modifying the calling
3447 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003448 //
3449 // - "const in" parameters can just be the r-value, as no writes need occur.
3450 //
John Kessenich4bf71552016-09-02 11:20:21 -06003451 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3452 // 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 -06003453
3454 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003455 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003456 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3457
John Kessenichfad62972017-07-18 02:35:46 -06003458 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3459 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003460
John Kessenichfad62972017-07-18 02:35:46 -06003461 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003462 for (int p = 0; p < (int)parameters.size(); ++p) {
3463 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3464 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003465 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003466 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003467 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003468 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3469 else
John Kessenich4bf71552016-09-02 11:20:21 -06003470 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003471 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003472 paramTypes.push_back(typeId);
3473 }
3474
3475 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003476 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3477 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003478 glslFunction->getName().c_str(), paramTypes,
3479 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003480 if (implicitThis)
3481 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003482
3483 // Track function to emit/call later
3484 functionMap[glslFunction->getName().c_str()] = function;
3485
3486 // Set the parameter id's
3487 for (int p = 0; p < (int)parameters.size(); ++p) {
3488 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3489 // give a name too
3490 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3491 }
3492 }
3493}
3494
3495// Process all the initializers, while skipping the functions and link objects
3496void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3497{
3498 builder.setBuildPoint(shaderEntry->getLastBlock());
3499 for (int i = 0; i < (int)initializers.size(); ++i) {
3500 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3501 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3502
3503 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003504 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003505 initializer->traverse(this);
3506 }
3507 }
3508}
3509
3510// Process all the functions, while skipping initializers.
3511void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3512{
3513 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3514 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003515 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003516 node->traverse(this);
3517 }
3518}
3519
3520void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3521{
qining25262b32016-05-06 17:25:16 -04003522 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003523 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003524 currentFunction = functionMap[node->getName().c_str()];
3525 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003526 builder.setBuildPoint(functionBlock);
3527}
3528
Rex Xu04db3f52015-09-16 11:44:02 +08003529void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003530{
Rex Xufc618912015-09-09 16:42:49 +08003531 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003532
3533 glslang::TSampler sampler = {};
3534 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003535#ifdef AMD_EXTENSIONS
3536 bool f16ShadowCompare = false;
3537#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003538 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003539 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3540 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003541#ifdef AMD_EXTENSIONS
3542 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3543#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003544 }
3545
John Kessenich140f3df2015-06-26 16:58:36 -06003546 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3547 builder.clearAccessChain();
3548 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003549
3550 // Special case l-value operands
3551 bool lvalue = false;
3552 switch (node.getOp()) {
3553 case glslang::EOpImageAtomicAdd:
3554 case glslang::EOpImageAtomicMin:
3555 case glslang::EOpImageAtomicMax:
3556 case glslang::EOpImageAtomicAnd:
3557 case glslang::EOpImageAtomicOr:
3558 case glslang::EOpImageAtomicXor:
3559 case glslang::EOpImageAtomicExchange:
3560 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003561 case glslang::EOpImageAtomicLoad:
3562 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003563 if (i == 0)
3564 lvalue = true;
3565 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003566 case glslang::EOpSparseImageLoad:
3567 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3568 lvalue = true;
3569 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003570#ifdef AMD_EXTENSIONS
3571 case glslang::EOpSparseTexture:
3572 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3573 lvalue = true;
3574 break;
3575 case glslang::EOpSparseTextureClamp:
3576 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3577 lvalue = true;
3578 break;
3579 case glslang::EOpSparseTextureLod:
3580 case glslang::EOpSparseTextureOffset:
3581 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3582 lvalue = true;
3583 break;
3584#else
Rex Xu48edadf2015-12-31 16:11:41 +08003585 case glslang::EOpSparseTexture:
3586 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3587 lvalue = true;
3588 break;
3589 case glslang::EOpSparseTextureClamp:
3590 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3591 lvalue = true;
3592 break;
3593 case glslang::EOpSparseTextureLod:
3594 case glslang::EOpSparseTextureOffset:
3595 if (i == 3)
3596 lvalue = true;
3597 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003598#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003599 case glslang::EOpSparseTextureFetch:
3600 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3601 lvalue = true;
3602 break;
3603 case glslang::EOpSparseTextureFetchOffset:
3604 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3605 lvalue = true;
3606 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003607#ifdef AMD_EXTENSIONS
3608 case glslang::EOpSparseTextureLodOffset:
3609 case glslang::EOpSparseTextureGrad:
3610 case glslang::EOpSparseTextureOffsetClamp:
3611 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3612 lvalue = true;
3613 break;
3614 case glslang::EOpSparseTextureGradOffset:
3615 case glslang::EOpSparseTextureGradClamp:
3616 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3617 lvalue = true;
3618 break;
3619 case glslang::EOpSparseTextureGradOffsetClamp:
3620 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3621 lvalue = true;
3622 break;
3623#else
Rex Xu48edadf2015-12-31 16:11:41 +08003624 case glslang::EOpSparseTextureLodOffset:
3625 case glslang::EOpSparseTextureGrad:
3626 case glslang::EOpSparseTextureOffsetClamp:
3627 if (i == 4)
3628 lvalue = true;
3629 break;
3630 case glslang::EOpSparseTextureGradOffset:
3631 case glslang::EOpSparseTextureGradClamp:
3632 if (i == 5)
3633 lvalue = true;
3634 break;
3635 case glslang::EOpSparseTextureGradOffsetClamp:
3636 if (i == 6)
3637 lvalue = true;
3638 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003639#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003640 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003641 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3642 lvalue = true;
3643 break;
3644 case glslang::EOpSparseTextureGatherOffset:
3645 case glslang::EOpSparseTextureGatherOffsets:
3646 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3647 lvalue = true;
3648 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003649#ifdef AMD_EXTENSIONS
3650 case glslang::EOpSparseTextureGatherLod:
3651 if (i == 3)
3652 lvalue = true;
3653 break;
3654 case glslang::EOpSparseTextureGatherLodOffset:
3655 case glslang::EOpSparseTextureGatherLodOffsets:
3656 if (i == 4)
3657 lvalue = true;
3658 break;
Rex Xu129799a2017-07-05 17:23:28 +08003659 case glslang::EOpSparseImageLoadLod:
3660 if (i == 3)
3661 lvalue = true;
3662 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003663#endif
Rex Xufc618912015-09-09 16:42:49 +08003664 default:
3665 break;
3666 }
3667
Rex Xu6b86d492015-09-16 17:48:22 +08003668 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003669 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003670 else
John Kessenich32cfd492016-02-02 12:37:46 -07003671 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003672 }
3673}
3674
John Kessenichfc51d282015-08-19 13:34:18 -06003675void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003676{
John Kessenichfc51d282015-08-19 13:34:18 -06003677 builder.clearAccessChain();
3678 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003679 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003680}
John Kessenich140f3df2015-06-26 16:58:36 -06003681
John Kessenichfc51d282015-08-19 13:34:18 -06003682spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3683{
John Kesseniche485c7a2017-05-31 18:50:53 -06003684 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003685 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003686
3687 builder.setLine(node->getLoc().line);
3688
John Kessenichfc51d282015-08-19 13:34:18 -06003689 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003690
3691 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3692 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3693 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003694#ifdef AMD_EXTENSIONS
3695 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3696 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3697 : false;
3698#endif
3699
John Kessenichfc51d282015-08-19 13:34:18 -06003700 std::vector<spv::Id> arguments;
3701 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003702 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003703 else
3704 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003705 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003706
3707 spv::Builder::TextureParameters params = { };
3708 params.sampler = arguments[0];
3709
Rex Xu04db3f52015-09-16 11:44:02 +08003710 glslang::TCrackedTextureOp cracked;
3711 node->crackTexture(sampler, cracked);
3712
amhagan05506bb2017-06-13 16:53:02 -04003713 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003714
John Kessenichfc51d282015-08-19 13:34:18 -06003715 // Check for queries
3716 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003717 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3718 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003719 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003720
John Kessenichfc51d282015-08-19 13:34:18 -06003721 switch (node->getOp()) {
3722 case glslang::EOpImageQuerySize:
3723 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003724 if (arguments.size() > 1) {
3725 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003726 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003727 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003728 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003729 case glslang::EOpImageQuerySamples:
3730 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003731 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003732 case glslang::EOpTextureQueryLod:
3733 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003734 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003735 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003736 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003737 case glslang::EOpSparseTexelsResident:
3738 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003739 default:
3740 assert(0);
3741 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003742 }
John Kessenich140f3df2015-06-26 16:58:36 -06003743 }
3744
LoopDawg4425f242018-02-18 11:40:01 -07003745 int components = node->getType().getVectorSize();
3746
3747 if (node->getOp() == glslang::EOpTextureFetch) {
3748 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3749 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3750 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3751 // here around e.g. which ones return scalars or other types.
3752 components = 4;
3753 }
3754
3755 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3756
3757 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3758
Rex Xufc618912015-09-09 16:42:49 +08003759 // Check for image functions other than queries
3760 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003761 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003762 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003763 spv::IdImmediate image = { true, *(opIt++) };
3764 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003765
3766 // Handle subpass operations
3767 // TODO: GLSL should change to have the "MS" only on the type rather than the
3768 // built-in function.
3769 if (cracked.subpass) {
3770 // add on the (0,0) coordinate
3771 spv::Id zero = builder.makeIntConstant(0);
3772 std::vector<spv::Id> comps;
3773 comps.push_back(zero);
3774 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003775 spv::IdImmediate coord = { true,
3776 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3777 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003778 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003779 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3780 operands.push_back(imageOperands);
3781 spv::IdImmediate imageOperand = { true, *(opIt++) };
3782 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003783 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003784 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3785 builder.setPrecision(result, precision);
3786 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003787 }
3788
John Kessenich149afc32018-08-14 13:31:43 -06003789 spv::IdImmediate coord = { true, *(opIt++) };
3790 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003791#ifdef AMD_EXTENSIONS
3792 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3793#else
John Kessenich56bab042015-09-16 10:54:31 -06003794 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003795#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003796 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003797 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003798 mask = mask | spv::ImageOperandsSampleMask;
3799 }
Rex Xu129799a2017-07-05 17:23:28 +08003800#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003801 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003802 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3803 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05003804 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07003805 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003806#endif
3807 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3808 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3809 if (mask) {
3810 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3811 operands.push_back(imageOperands);
3812 }
3813 if (mask & spv::ImageOperandsSampleMask) {
3814 spv::IdImmediate imageOperand = { true, *opIt++ };
3815 operands.push_back(imageOperand);
3816 }
3817#ifdef AMD_EXTENSIONS
3818 if (mask & spv::ImageOperandsLodMask) {
3819 spv::IdImmediate imageOperand = { true, *opIt++ };
3820 operands.push_back(imageOperand);
3821 }
3822#endif
3823 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3824 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3825 operands.push_back(imageOperand);
3826 }
3827
John Kessenich149afc32018-08-14 13:31:43 -06003828 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003829 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003830
John Kessenich149afc32018-08-14 13:31:43 -06003831 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003832 builder.setPrecision(result[0], precision);
3833
3834 // If needed, add a conversion constructor to the proper size.
3835 if (components != node->getType().getVectorSize())
3836 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3837
3838 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003839#ifdef AMD_EXTENSIONS
3840 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3841#else
John Kessenich56bab042015-09-16 10:54:31 -06003842 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003843#endif
Rex Xu129799a2017-07-05 17:23:28 +08003844
Jeff Bolz36831c92018-09-05 10:11:41 -05003845 // Push the texel value before the operands
3846#ifdef AMD_EXTENSIONS
3847 if (sampler.ms || cracked.lod) {
3848#else
3849 if (sampler.ms) {
3850#endif
John Kessenich149afc32018-08-14 13:31:43 -06003851 spv::IdImmediate texel = { true, *(opIt + 1) };
3852 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06003853 } else {
3854 spv::IdImmediate texel = { true, *opIt };
3855 operands.push_back(texel);
3856 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003857
3858 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
3859 if (sampler.ms) {
3860 mask = mask | spv::ImageOperandsSampleMask;
3861 }
3862#ifdef AMD_EXTENSIONS
3863 if (cracked.lod) {
3864 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3865 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3866 mask = mask | spv::ImageOperandsLodMask;
3867 }
3868#endif
3869 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3870 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
3871 if (mask) {
3872 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3873 operands.push_back(imageOperands);
3874 }
3875 if (mask & spv::ImageOperandsSampleMask) {
3876 spv::IdImmediate imageOperand = { true, *opIt++ };
3877 operands.push_back(imageOperand);
3878 }
3879#ifdef AMD_EXTENSIONS
3880 if (mask & spv::ImageOperandsLodMask) {
3881 spv::IdImmediate imageOperand = { true, *opIt++ };
3882 operands.push_back(imageOperand);
3883 }
3884#endif
3885 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
3886 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3887 operands.push_back(imageOperand);
3888 }
3889
John Kessenich56bab042015-09-16 10:54:31 -06003890 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003891 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003892 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003893 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003894#ifdef AMD_EXTENSIONS
3895 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3896#else
Rex Xu5eafa472016-02-19 22:24:03 +08003897 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003898#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003899 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003900 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003901 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3902
Jeff Bolz36831c92018-09-05 10:11:41 -05003903 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08003904 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003905 mask = mask | spv::ImageOperandsSampleMask;
3906 }
Rex Xu129799a2017-07-05 17:23:28 +08003907#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003908 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003909 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3910 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3911
Jeff Bolz36831c92018-09-05 10:11:41 -05003912 mask = mask | spv::ImageOperandsLodMask;
3913 }
3914#endif
3915 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3916 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3917 if (mask) {
3918 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06003919 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05003920 }
3921 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06003922 spv::IdImmediate imageOperand = { true, *opIt++ };
3923 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05003924 }
3925#ifdef AMD_EXTENSIONS
3926 if (mask & spv::ImageOperandsLodMask) {
3927 spv::IdImmediate imageOperand = { true, *opIt++ };
3928 operands.push_back(imageOperand);
3929 }
Rex Xu129799a2017-07-05 17:23:28 +08003930#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003931 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3932 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3933 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08003934 }
3935
3936 // Create the return type that was a special structure
3937 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003938 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003939 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3940 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3941
3942 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3943
3944 // Decode the return type
3945 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3946 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003947 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003948 // Process image atomic operations
3949
3950 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3951 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003952 // For non-MS, the sample value should be 0
3953 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3954 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003955
Jeff Bolz36831c92018-09-05 10:11:41 -05003956 spv::Id resultTypeId;
3957 // imageAtomicStore has a void return type so base the pointer type on
3958 // the type of the value operand.
3959 if (node->getOp() == glslang::EOpImageAtomicStore) {
3960 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
3961 } else {
3962 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
3963 }
John Kessenich56bab042015-09-16 10:54:31 -06003964 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003965
3966 std::vector<spv::Id> operands;
3967 operands.push_back(pointer);
3968 for (; opIt != arguments.end(); ++opIt)
3969 operands.push_back(*opIt);
3970
John Kessenich8c8505c2016-07-26 12:50:38 -06003971 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003972 }
3973 }
3974
amhagan05506bb2017-06-13 16:53:02 -04003975#ifdef AMD_EXTENSIONS
3976 // Check for fragment mask functions other than queries
3977 if (cracked.fragMask) {
3978 assert(sampler.ms);
3979
3980 auto opIt = arguments.begin();
3981 std::vector<spv::Id> operands;
3982
3983 // Extract the image if necessary
3984 if (builder.isSampledImage(params.sampler))
3985 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3986
3987 operands.push_back(params.sampler);
3988 ++opIt;
3989
3990 if (sampler.isSubpass()) {
3991 // add on the (0,0) coordinate
3992 spv::Id zero = builder.makeIntConstant(0);
3993 std::vector<spv::Id> comps;
3994 comps.push_back(zero);
3995 comps.push_back(zero);
3996 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3997 }
3998
3999 for (; opIt != arguments.end(); ++opIt)
4000 operands.push_back(*opIt);
4001
4002 spv::Op fragMaskOp = spv::OpNop;
4003 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4004 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4005 else if (node->getOp() == glslang::EOpFragmentFetch)
4006 fragMaskOp = spv::OpFragmentFetchAMD;
4007
4008 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4009 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4010 return builder.createOp(fragMaskOp, resultType(), operands);
4011 }
4012#endif
4013
Rex Xufc618912015-09-09 16:42:49 +08004014 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004015 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08004016 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4017
John Kessenichfc51d282015-08-19 13:34:18 -06004018 // check for bias argument
4019 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004020#ifdef AMD_EXTENSIONS
4021 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4022#else
Rex Xu71519fe2015-11-11 15:35:47 +08004023 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004024#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004025 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004026#ifdef AMD_EXTENSIONS
4027 if (cracked.gather)
4028 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004029
4030 if (f16ShadowCompare)
4031 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004032#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004033 if (cracked.offset)
4034 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004035#ifdef AMD_EXTENSIONS
4036 else if (cracked.offsets)
4037 ++nonBiasArgCount;
4038#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004039 if (cracked.grad)
4040 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004041 if (cracked.lodClamp)
4042 ++nonBiasArgCount;
4043 if (sparse)
4044 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004045
4046 if ((int)arguments.size() > nonBiasArgCount)
4047 bias = true;
4048 }
4049
John Kessenicha5c33d62016-06-02 23:45:21 -06004050 // See if the sampler param should really be just the SPV image part
4051 if (cracked.fetch) {
4052 // a fetch needs to have the image extracted first
4053 if (builder.isSampledImage(params.sampler))
4054 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4055 }
4056
Rex Xu225e0fc2016-11-17 17:47:59 +08004057#ifdef AMD_EXTENSIONS
4058 if (cracked.gather) {
4059 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4060 if (bias || cracked.lod ||
4061 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4062 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004063 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004064 }
4065 }
4066#endif
4067
John Kessenichfc51d282015-08-19 13:34:18 -06004068 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004069
John Kessenichfc51d282015-08-19 13:34:18 -06004070 params.coords = arguments[1];
4071 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004072 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004073
4074 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004075#ifdef AMD_EXTENSIONS
4076 if (cubeCompare || f16ShadowCompare) {
4077#else
Rex Xu48edadf2015-12-31 16:11:41 +08004078 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004079#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004080 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004081 ++extraArgs;
4082 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004083 params.Dref = arguments[2];
4084 ++extraArgs;
4085 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004086 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004087 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004088 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004089 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004090 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004091 dRefComp = builder.getNumComponents(params.coords) - 1;
4092 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004093 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4094 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004095
4096 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004097 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004098 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004099 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07004100 } else if (glslangIntermediate->getStage() != EShLangFragment) {
4101 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4102 noImplicitLod = true;
4103 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004104
4105 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004106 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004107 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004108 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004109 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004110
4111 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004112 if (cracked.grad) {
4113 params.gradX = arguments[2 + extraArgs];
4114 params.gradY = arguments[3 + extraArgs];
4115 extraArgs += 2;
4116 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004117
4118 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004119 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004120 params.offset = arguments[2 + extraArgs];
4121 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004122 } else if (cracked.offsets) {
4123 params.offsets = arguments[2 + extraArgs];
4124 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004125 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004126
4127 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004128 if (cracked.lodClamp) {
4129 params.lodClamp = arguments[2 + extraArgs];
4130 ++extraArgs;
4131 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004132
4133 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004134 if (sparse) {
4135 params.texelOut = arguments[2 + extraArgs];
4136 ++extraArgs;
4137 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004138
John Kessenich76d4dfc2016-06-16 12:43:23 -06004139 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004140 if (cracked.gather && ! sampler.shadow) {
4141 // default component is 0, if missing, otherwise an argument
4142 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004143 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004144 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004145 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004146 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004147 }
4148
4149 // bias
4150 if (bias) {
4151 params.bias = arguments[2 + extraArgs];
4152 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004153 }
John Kessenichfc51d282015-08-19 13:34:18 -06004154
John Kessenich65336482016-06-16 14:06:26 -06004155 // projective component (might not to move)
4156 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4157 // are divided by the last component of P."
4158 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4159 // unused components will appear after all used components."
4160 if (cracked.proj) {
4161 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4162 int projTargetComp;
4163 switch (sampler.dim) {
4164 case glslang::Esd1D: projTargetComp = 1; break;
4165 case glslang::Esd2D: projTargetComp = 2; break;
4166 case glslang::EsdRect: projTargetComp = 2; break;
4167 default: projTargetComp = projSourceComp; break;
4168 }
4169 // copy the projective coordinate if we have to
4170 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004171 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004172 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4173 projSourceComp);
4174 params.coords = builder.createCompositeInsert(projComp, params.coords,
4175 builder.getTypeId(params.coords), projTargetComp);
4176 }
4177 }
4178
Jeff Bolz36831c92018-09-05 10:11:41 -05004179 // nonprivate
4180 if (imageType.getQualifier().nonprivate) {
4181 params.nonprivate = true;
4182 }
4183
4184 // volatile
4185 if (imageType.getQualifier().volatil) {
4186 params.volatil = true;
4187 }
4188
St0fFa1184dd2018-04-09 21:08:14 +02004189 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004190 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004191 );
LoopDawg4425f242018-02-18 11:40:01 -07004192
4193 if (components != node->getType().getVectorSize())
4194 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4195
4196 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004197}
4198
4199spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4200{
4201 // Grab the function's pointer from the previously created function
4202 spv::Function* function = functionMap[node->getName().c_str()];
4203 if (! function)
4204 return 0;
4205
4206 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4207 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4208
4209 // See comments in makeFunctions() for details about the semantics for parameter passing.
4210 //
4211 // These imply we need a four step process:
4212 // 1. Evaluate the arguments
4213 // 2. Allocate and make copies of in, out, and inout arguments
4214 // 3. Make the call
4215 // 4. Copy back the results
4216
John Kessenichd3ed90b2018-05-04 11:43:03 -06004217 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004218 std::vector<spv::Builder::AccessChain> lValues;
4219 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004220 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004221 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004222 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004223 // build l-value
4224 builder.clearAccessChain();
4225 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004226 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004227 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004228 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004229 // save l-value
4230 lValues.push_back(builder.getAccessChain());
4231 } else {
4232 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004233 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004234 }
4235 }
4236
4237 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4238 // copy the original into that space.
4239 //
4240 // Also, build up the list of actual arguments to pass in for the call
4241 int lValueCount = 0;
4242 int rValueCount = 0;
4243 std::vector<spv::Id> spvArgs;
4244 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4245 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004246 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004247 builder.setAccessChain(lValues[lValueCount]);
4248 arg = builder.accessChainGetLValue();
4249 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004250 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004251 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004252 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004253 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4254 // need to copy the input into output space
4255 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004256 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004257 builder.clearAccessChain();
4258 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004259 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004260 }
4261 ++lValueCount;
4262 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004263 // process r-value, which involves a copy for a type mismatch
4264 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4265 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4266 builder.clearAccessChain();
4267 builder.setAccessChainLValue(argCopy);
4268 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4269 arg = builder.createLoad(argCopy);
4270 } else
4271 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004272 ++rValueCount;
4273 }
4274 spvArgs.push_back(arg);
4275 }
4276
4277 // 3. Make the call.
4278 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004279 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004280
4281 // 4. Copy back out an "out" arguments.
4282 lValueCount = 0;
4283 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004284 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004285 ++lValueCount;
4286 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004287 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4288 spv::Id copy = builder.createLoad(spvArgs[a]);
4289 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004290 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004291 }
4292 ++lValueCount;
4293 }
4294 }
4295
4296 return result;
4297}
4298
4299// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004300spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004301 spv::Id typeId, spv::Id left, spv::Id right,
4302 glslang::TBasicType typeProxy, bool reduceComparison)
4303{
John Kessenich66011cb2018-03-06 16:12:04 -07004304 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4305 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004306 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004307
4308 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004309 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004310 bool comparison = false;
4311
4312 switch (op) {
4313 case glslang::EOpAdd:
4314 case glslang::EOpAddAssign:
4315 if (isFloat)
4316 binOp = spv::OpFAdd;
4317 else
4318 binOp = spv::OpIAdd;
4319 break;
4320 case glslang::EOpSub:
4321 case glslang::EOpSubAssign:
4322 if (isFloat)
4323 binOp = spv::OpFSub;
4324 else
4325 binOp = spv::OpISub;
4326 break;
4327 case glslang::EOpMul:
4328 case glslang::EOpMulAssign:
4329 if (isFloat)
4330 binOp = spv::OpFMul;
4331 else
4332 binOp = spv::OpIMul;
4333 break;
4334 case glslang::EOpVectorTimesScalar:
4335 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004336 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004337 if (builder.isVector(right))
4338 std::swap(left, right);
4339 assert(builder.isScalar(right));
4340 needMatchingVectors = false;
4341 binOp = spv::OpVectorTimesScalar;
4342 } else
4343 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004344 break;
4345 case glslang::EOpVectorTimesMatrix:
4346 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004347 binOp = spv::OpVectorTimesMatrix;
4348 break;
4349 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004350 binOp = spv::OpMatrixTimesVector;
4351 break;
4352 case glslang::EOpMatrixTimesScalar:
4353 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004354 binOp = spv::OpMatrixTimesScalar;
4355 break;
4356 case glslang::EOpMatrixTimesMatrix:
4357 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004358 binOp = spv::OpMatrixTimesMatrix;
4359 break;
4360 case glslang::EOpOuterProduct:
4361 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004362 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004363 break;
4364
4365 case glslang::EOpDiv:
4366 case glslang::EOpDivAssign:
4367 if (isFloat)
4368 binOp = spv::OpFDiv;
4369 else if (isUnsigned)
4370 binOp = spv::OpUDiv;
4371 else
4372 binOp = spv::OpSDiv;
4373 break;
4374 case glslang::EOpMod:
4375 case glslang::EOpModAssign:
4376 if (isFloat)
4377 binOp = spv::OpFMod;
4378 else if (isUnsigned)
4379 binOp = spv::OpUMod;
4380 else
4381 binOp = spv::OpSMod;
4382 break;
4383 case glslang::EOpRightShift:
4384 case glslang::EOpRightShiftAssign:
4385 if (isUnsigned)
4386 binOp = spv::OpShiftRightLogical;
4387 else
4388 binOp = spv::OpShiftRightArithmetic;
4389 break;
4390 case glslang::EOpLeftShift:
4391 case glslang::EOpLeftShiftAssign:
4392 binOp = spv::OpShiftLeftLogical;
4393 break;
4394 case glslang::EOpAnd:
4395 case glslang::EOpAndAssign:
4396 binOp = spv::OpBitwiseAnd;
4397 break;
4398 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004399 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004400 binOp = spv::OpLogicalAnd;
4401 break;
4402 case glslang::EOpInclusiveOr:
4403 case glslang::EOpInclusiveOrAssign:
4404 binOp = spv::OpBitwiseOr;
4405 break;
4406 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004407 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004408 binOp = spv::OpLogicalOr;
4409 break;
4410 case glslang::EOpExclusiveOr:
4411 case glslang::EOpExclusiveOrAssign:
4412 binOp = spv::OpBitwiseXor;
4413 break;
4414 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004415 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004416 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004417 break;
4418
4419 case glslang::EOpLessThan:
4420 case glslang::EOpGreaterThan:
4421 case glslang::EOpLessThanEqual:
4422 case glslang::EOpGreaterThanEqual:
4423 case glslang::EOpEqual:
4424 case glslang::EOpNotEqual:
4425 case glslang::EOpVectorEqual:
4426 case glslang::EOpVectorNotEqual:
4427 comparison = true;
4428 break;
4429 default:
4430 break;
4431 }
4432
John Kessenich7c1aa102015-10-15 13:29:11 -06004433 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004434 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004435 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004436 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004437 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004438
4439 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004440 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004441 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004442
qining25262b32016-05-06 17:25:16 -04004443 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004444 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004445 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004446 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004447 }
4448
4449 if (! comparison)
4450 return 0;
4451
John Kessenich7c1aa102015-10-15 13:29:11 -06004452 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004453
John Kessenich4583b612016-08-07 19:14:22 -06004454 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004455 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4456 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004457 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004458 return result;
4459 }
John Kessenich140f3df2015-06-26 16:58:36 -06004460
4461 switch (op) {
4462 case glslang::EOpLessThan:
4463 if (isFloat)
4464 binOp = spv::OpFOrdLessThan;
4465 else if (isUnsigned)
4466 binOp = spv::OpULessThan;
4467 else
4468 binOp = spv::OpSLessThan;
4469 break;
4470 case glslang::EOpGreaterThan:
4471 if (isFloat)
4472 binOp = spv::OpFOrdGreaterThan;
4473 else if (isUnsigned)
4474 binOp = spv::OpUGreaterThan;
4475 else
4476 binOp = spv::OpSGreaterThan;
4477 break;
4478 case glslang::EOpLessThanEqual:
4479 if (isFloat)
4480 binOp = spv::OpFOrdLessThanEqual;
4481 else if (isUnsigned)
4482 binOp = spv::OpULessThanEqual;
4483 else
4484 binOp = spv::OpSLessThanEqual;
4485 break;
4486 case glslang::EOpGreaterThanEqual:
4487 if (isFloat)
4488 binOp = spv::OpFOrdGreaterThanEqual;
4489 else if (isUnsigned)
4490 binOp = spv::OpUGreaterThanEqual;
4491 else
4492 binOp = spv::OpSGreaterThanEqual;
4493 break;
4494 case glslang::EOpEqual:
4495 case glslang::EOpVectorEqual:
4496 if (isFloat)
4497 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004498 else if (isBool)
4499 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004500 else
4501 binOp = spv::OpIEqual;
4502 break;
4503 case glslang::EOpNotEqual:
4504 case glslang::EOpVectorNotEqual:
4505 if (isFloat)
4506 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004507 else if (isBool)
4508 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004509 else
4510 binOp = spv::OpINotEqual;
4511 break;
4512 default:
4513 break;
4514 }
4515
qining25262b32016-05-06 17:25:16 -04004516 if (binOp != spv::OpNop) {
4517 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004518 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004519 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004520 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004521 }
John Kessenich140f3df2015-06-26 16:58:36 -06004522
4523 return 0;
4524}
4525
John Kessenich04bb8a02015-12-12 12:28:14 -07004526//
4527// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4528// These can be any of:
4529//
4530// matrix * scalar
4531// scalar * matrix
4532// matrix * matrix linear algebraic
4533// matrix * vector
4534// vector * matrix
4535// matrix * matrix componentwise
4536// matrix op matrix op in {+, -, /}
4537// matrix op scalar op in {+, -, /}
4538// scalar op matrix op in {+, -, /}
4539//
John Kessenichead86222018-03-28 18:01:20 -06004540spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4541 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004542{
4543 bool firstClass = true;
4544
4545 // First, handle first-class matrix operations (* and matrix/scalar)
4546 switch (op) {
4547 case spv::OpFDiv:
4548 if (builder.isMatrix(left) && builder.isScalar(right)) {
4549 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004550 spv::Id resultType = builder.getTypeId(right);
4551 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004552 op = spv::OpMatrixTimesScalar;
4553 } else
4554 firstClass = false;
4555 break;
4556 case spv::OpMatrixTimesScalar:
4557 if (builder.isMatrix(right))
4558 std::swap(left, right);
4559 assert(builder.isScalar(right));
4560 break;
4561 case spv::OpVectorTimesMatrix:
4562 assert(builder.isVector(left));
4563 assert(builder.isMatrix(right));
4564 break;
4565 case spv::OpMatrixTimesVector:
4566 assert(builder.isMatrix(left));
4567 assert(builder.isVector(right));
4568 break;
4569 case spv::OpMatrixTimesMatrix:
4570 assert(builder.isMatrix(left));
4571 assert(builder.isMatrix(right));
4572 break;
4573 default:
4574 firstClass = false;
4575 break;
4576 }
4577
qining25262b32016-05-06 17:25:16 -04004578 if (firstClass) {
4579 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004580 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004581 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004582 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004583 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004584
LoopDawg592860c2016-06-09 08:57:35 -06004585 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004586 // The result type of all of them is the same type as the (a) matrix operand.
4587 // The algorithm is to:
4588 // - break the matrix(es) into vectors
4589 // - smear any scalar to a vector
4590 // - do vector operations
4591 // - make a matrix out the vector results
4592 switch (op) {
4593 case spv::OpFAdd:
4594 case spv::OpFSub:
4595 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004596 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004597 case spv::OpFMul:
4598 {
4599 // one time set up...
4600 bool leftMat = builder.isMatrix(left);
4601 bool rightMat = builder.isMatrix(right);
4602 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4603 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4604 spv::Id scalarType = builder.getScalarTypeId(typeId);
4605 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4606 std::vector<spv::Id> results;
4607 spv::Id smearVec = spv::NoResult;
4608 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004609 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004610 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004611 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004612
4613 // do each vector op
4614 for (unsigned int c = 0; c < numCols; ++c) {
4615 std::vector<unsigned int> indexes;
4616 indexes.push_back(c);
4617 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4618 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004619 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004620 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004621 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004622 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004623 }
4624
4625 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004626 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004627 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004628 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004629 }
4630 default:
4631 assert(0);
4632 return spv::NoResult;
4633 }
4634}
4635
John Kessenichead86222018-03-28 18:01:20 -06004636spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4637 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004638{
4639 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004640 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004641 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004642 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4643 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004644
4645 switch (op) {
4646 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004647 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004648 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004649 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004650 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004651 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004652 unaryOp = spv::OpSNegate;
4653 break;
4654
4655 case glslang::EOpLogicalNot:
4656 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004657 unaryOp = spv::OpLogicalNot;
4658 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004659 case glslang::EOpBitwiseNot:
4660 unaryOp = spv::OpNot;
4661 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004662
John Kessenich140f3df2015-06-26 16:58:36 -06004663 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004664 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004665 break;
4666 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004667 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004668 break;
4669 case glslang::EOpTranspose:
4670 unaryOp = spv::OpTranspose;
4671 break;
4672
4673 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004674 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004675 break;
4676 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004677 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004678 break;
4679 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004680 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004681 break;
4682 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004683 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004684 break;
4685 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004686 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004687 break;
4688 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004689 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004690 break;
4691 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004692 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004693 break;
4694 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004695 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004696 break;
4697
4698 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004699 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004700 break;
4701 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004702 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004703 break;
4704 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004705 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004706 break;
4707 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004708 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004709 break;
4710 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004711 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004712 break;
4713 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004714 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004715 break;
4716
4717 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004718 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004719 break;
4720 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004721 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004722 break;
4723
4724 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004725 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004726 break;
4727 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004728 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004729 break;
4730 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004731 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004732 break;
4733 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004734 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004735 break;
4736 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004737 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004738 break;
4739 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004740 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004741 break;
4742
4743 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004744 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004745 break;
4746 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004747 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004748 break;
4749 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004750 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004751 break;
4752 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004753 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004754 break;
4755 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004756 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004757 break;
4758 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004759 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004760 break;
4761
4762 case glslang::EOpIsNan:
4763 unaryOp = spv::OpIsNan;
4764 break;
4765 case glslang::EOpIsInf:
4766 unaryOp = spv::OpIsInf;
4767 break;
LoopDawg592860c2016-06-09 08:57:35 -06004768 case glslang::EOpIsFinite:
4769 unaryOp = spv::OpIsFinite;
4770 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004771
Rex Xucbc426e2015-12-15 16:03:10 +08004772 case glslang::EOpFloatBitsToInt:
4773 case glslang::EOpFloatBitsToUint:
4774 case glslang::EOpIntBitsToFloat:
4775 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004776 case glslang::EOpDoubleBitsToInt64:
4777 case glslang::EOpDoubleBitsToUint64:
4778 case glslang::EOpInt64BitsToDouble:
4779 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004780 case glslang::EOpFloat16BitsToInt16:
4781 case glslang::EOpFloat16BitsToUint16:
4782 case glslang::EOpInt16BitsToFloat16:
4783 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004784 unaryOp = spv::OpBitcast;
4785 break;
4786
John Kessenich140f3df2015-06-26 16:58:36 -06004787 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004788 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004789 break;
4790 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004791 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004792 break;
4793 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004794 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004795 break;
4796 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004797 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004798 break;
4799 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004800 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004801 break;
4802 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004803 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004804 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004805 case glslang::EOpPackSnorm4x8:
4806 libCall = spv::GLSLstd450PackSnorm4x8;
4807 break;
4808 case glslang::EOpUnpackSnorm4x8:
4809 libCall = spv::GLSLstd450UnpackSnorm4x8;
4810 break;
4811 case glslang::EOpPackUnorm4x8:
4812 libCall = spv::GLSLstd450PackUnorm4x8;
4813 break;
4814 case glslang::EOpUnpackUnorm4x8:
4815 libCall = spv::GLSLstd450UnpackUnorm4x8;
4816 break;
4817 case glslang::EOpPackDouble2x32:
4818 libCall = spv::GLSLstd450PackDouble2x32;
4819 break;
4820 case glslang::EOpUnpackDouble2x32:
4821 libCall = spv::GLSLstd450UnpackDouble2x32;
4822 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004823
Rex Xu8ff43de2016-04-22 16:51:45 +08004824 case glslang::EOpPackInt2x32:
4825 case glslang::EOpUnpackInt2x32:
4826 case glslang::EOpPackUint2x32:
4827 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004828 case glslang::EOpPack16:
4829 case glslang::EOpPack32:
4830 case glslang::EOpPack64:
4831 case glslang::EOpUnpack32:
4832 case glslang::EOpUnpack16:
4833 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004834 case glslang::EOpPackInt2x16:
4835 case glslang::EOpUnpackInt2x16:
4836 case glslang::EOpPackUint2x16:
4837 case glslang::EOpUnpackUint2x16:
4838 case glslang::EOpPackInt4x16:
4839 case glslang::EOpUnpackInt4x16:
4840 case glslang::EOpPackUint4x16:
4841 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004842 case glslang::EOpPackFloat2x16:
4843 case glslang::EOpUnpackFloat2x16:
4844 unaryOp = spv::OpBitcast;
4845 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004846
John Kessenich140f3df2015-06-26 16:58:36 -06004847 case glslang::EOpDPdx:
4848 unaryOp = spv::OpDPdx;
4849 break;
4850 case glslang::EOpDPdy:
4851 unaryOp = spv::OpDPdy;
4852 break;
4853 case glslang::EOpFwidth:
4854 unaryOp = spv::OpFwidth;
4855 break;
4856 case glslang::EOpDPdxFine:
4857 unaryOp = spv::OpDPdxFine;
4858 break;
4859 case glslang::EOpDPdyFine:
4860 unaryOp = spv::OpDPdyFine;
4861 break;
4862 case glslang::EOpFwidthFine:
4863 unaryOp = spv::OpFwidthFine;
4864 break;
4865 case glslang::EOpDPdxCoarse:
4866 unaryOp = spv::OpDPdxCoarse;
4867 break;
4868 case glslang::EOpDPdyCoarse:
4869 unaryOp = spv::OpDPdyCoarse;
4870 break;
4871 case glslang::EOpFwidthCoarse:
4872 unaryOp = spv::OpFwidthCoarse;
4873 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004874 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004875#ifdef AMD_EXTENSIONS
4876 if (typeProxy == glslang::EbtFloat16)
4877 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4878#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004879 libCall = spv::GLSLstd450InterpolateAtCentroid;
4880 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004881 case glslang::EOpAny:
4882 unaryOp = spv::OpAny;
4883 break;
4884 case glslang::EOpAll:
4885 unaryOp = spv::OpAll;
4886 break;
4887
4888 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004889 if (isFloat)
4890 libCall = spv::GLSLstd450FAbs;
4891 else
4892 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004893 break;
4894 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004895 if (isFloat)
4896 libCall = spv::GLSLstd450FSign;
4897 else
4898 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004899 break;
4900
John Kessenichfc51d282015-08-19 13:34:18 -06004901 case glslang::EOpAtomicCounterIncrement:
4902 case glslang::EOpAtomicCounterDecrement:
4903 case glslang::EOpAtomicCounter:
4904 {
4905 // Handle all of the atomics in one place, in createAtomicOperation()
4906 std::vector<spv::Id> operands;
4907 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004908 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004909 }
4910
John Kessenichfc51d282015-08-19 13:34:18 -06004911 case glslang::EOpBitFieldReverse:
4912 unaryOp = spv::OpBitReverse;
4913 break;
4914 case glslang::EOpBitCount:
4915 unaryOp = spv::OpBitCount;
4916 break;
4917 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004918 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004919 break;
4920 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004921 if (isUnsigned)
4922 libCall = spv::GLSLstd450FindUMsb;
4923 else
4924 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004925 break;
4926
Rex Xu574ab042016-04-14 16:53:07 +08004927 case glslang::EOpBallot:
4928 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004929 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004930 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004931 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004932#ifdef AMD_EXTENSIONS
4933 case glslang::EOpMinInvocations:
4934 case glslang::EOpMaxInvocations:
4935 case glslang::EOpAddInvocations:
4936 case glslang::EOpMinInvocationsNonUniform:
4937 case glslang::EOpMaxInvocationsNonUniform:
4938 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004939 case glslang::EOpMinInvocationsInclusiveScan:
4940 case glslang::EOpMaxInvocationsInclusiveScan:
4941 case glslang::EOpAddInvocationsInclusiveScan:
4942 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4943 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4944 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4945 case glslang::EOpMinInvocationsExclusiveScan:
4946 case glslang::EOpMaxInvocationsExclusiveScan:
4947 case glslang::EOpAddInvocationsExclusiveScan:
4948 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4949 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4950 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004951#endif
Rex Xu51596642016-09-21 18:56:12 +08004952 {
4953 std::vector<spv::Id> operands;
4954 operands.push_back(operand);
4955 return createInvocationsOperation(op, typeId, operands, typeProxy);
4956 }
John Kessenich66011cb2018-03-06 16:12:04 -07004957 case glslang::EOpSubgroupAll:
4958 case glslang::EOpSubgroupAny:
4959 case glslang::EOpSubgroupAllEqual:
4960 case glslang::EOpSubgroupBroadcastFirst:
4961 case glslang::EOpSubgroupBallot:
4962 case glslang::EOpSubgroupInverseBallot:
4963 case glslang::EOpSubgroupBallotBitCount:
4964 case glslang::EOpSubgroupBallotInclusiveBitCount:
4965 case glslang::EOpSubgroupBallotExclusiveBitCount:
4966 case glslang::EOpSubgroupBallotFindLSB:
4967 case glslang::EOpSubgroupBallotFindMSB:
4968 case glslang::EOpSubgroupAdd:
4969 case glslang::EOpSubgroupMul:
4970 case glslang::EOpSubgroupMin:
4971 case glslang::EOpSubgroupMax:
4972 case glslang::EOpSubgroupAnd:
4973 case glslang::EOpSubgroupOr:
4974 case glslang::EOpSubgroupXor:
4975 case glslang::EOpSubgroupInclusiveAdd:
4976 case glslang::EOpSubgroupInclusiveMul:
4977 case glslang::EOpSubgroupInclusiveMin:
4978 case glslang::EOpSubgroupInclusiveMax:
4979 case glslang::EOpSubgroupInclusiveAnd:
4980 case glslang::EOpSubgroupInclusiveOr:
4981 case glslang::EOpSubgroupInclusiveXor:
4982 case glslang::EOpSubgroupExclusiveAdd:
4983 case glslang::EOpSubgroupExclusiveMul:
4984 case glslang::EOpSubgroupExclusiveMin:
4985 case glslang::EOpSubgroupExclusiveMax:
4986 case glslang::EOpSubgroupExclusiveAnd:
4987 case glslang::EOpSubgroupExclusiveOr:
4988 case glslang::EOpSubgroupExclusiveXor:
4989 case glslang::EOpSubgroupQuadSwapHorizontal:
4990 case glslang::EOpSubgroupQuadSwapVertical:
4991 case glslang::EOpSubgroupQuadSwapDiagonal: {
4992 std::vector<spv::Id> operands;
4993 operands.push_back(operand);
4994 return createSubgroupOperation(op, typeId, operands, typeProxy);
4995 }
Rex Xu9d93a232016-05-05 12:30:44 +08004996#ifdef AMD_EXTENSIONS
4997 case glslang::EOpMbcnt:
4998 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4999 libCall = spv::MbcntAMD;
5000 break;
5001
5002 case glslang::EOpCubeFaceIndex:
5003 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5004 libCall = spv::CubeFaceIndexAMD;
5005 break;
5006
5007 case glslang::EOpCubeFaceCoord:
5008 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5009 libCall = spv::CubeFaceCoordAMD;
5010 break;
5011#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005012#ifdef NV_EXTENSIONS
5013 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005014 unaryOp = spv::OpGroupNonUniformPartitionNV;
5015 break;
5016#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005017 default:
5018 return 0;
5019 }
5020
5021 spv::Id id;
5022 if (libCall >= 0) {
5023 std::vector<spv::Id> args;
5024 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005025 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005026 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005027 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005028 }
John Kessenich140f3df2015-06-26 16:58:36 -06005029
John Kessenichead86222018-03-28 18:01:20 -06005030 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005031 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005032 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005033}
5034
John Kessenich7a53f762016-01-20 11:19:27 -07005035// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005036spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5037 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005038{
5039 // Handle unary operations vector by vector.
5040 // The result type is the same type as the original type.
5041 // The algorithm is to:
5042 // - break the matrix into vectors
5043 // - apply the operation to each vector
5044 // - make a matrix out the vector results
5045
5046 // get the types sorted out
5047 int numCols = builder.getNumColumns(operand);
5048 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005049 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5050 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005051 std::vector<spv::Id> results;
5052
5053 // do each vector op
5054 for (int c = 0; c < numCols; ++c) {
5055 std::vector<unsigned int> indexes;
5056 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005057 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5058 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005059 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005060 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005061 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005062 }
5063
5064 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005065 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005066 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005067 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005068}
5069
John Kessenichad7645f2018-06-04 19:11:25 -06005070// For converting integers where both the bitwidth and the signedness could
5071// change, but only do the width change here. The caller is still responsible
5072// for the signedness conversion.
5073spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005074{
John Kessenichad7645f2018-06-04 19:11:25 -06005075 // Get the result type width, based on the type to convert to.
5076 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005077 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005078 case glslang::EOpConvInt16ToUint8:
5079 case glslang::EOpConvIntToUint8:
5080 case glslang::EOpConvInt64ToUint8:
5081 case glslang::EOpConvUint16ToInt8:
5082 case glslang::EOpConvUintToInt8:
5083 case glslang::EOpConvUint64ToInt8:
5084 width = 8;
5085 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005086 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005087 case glslang::EOpConvIntToUint16:
5088 case glslang::EOpConvInt64ToUint16:
5089 case glslang::EOpConvUint8ToInt16:
5090 case glslang::EOpConvUintToInt16:
5091 case glslang::EOpConvUint64ToInt16:
5092 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005093 break;
5094 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005095 case glslang::EOpConvInt16ToUint:
5096 case glslang::EOpConvInt64ToUint:
5097 case glslang::EOpConvUint8ToInt:
5098 case glslang::EOpConvUint16ToInt:
5099 case glslang::EOpConvUint64ToInt:
5100 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005101 break;
5102 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005103 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005104 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005105 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005106 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005107 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005108 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005109 break;
5110
5111 default:
5112 assert(false && "Default missing");
5113 break;
5114 }
5115
John Kessenichad7645f2018-06-04 19:11:25 -06005116 // Get the conversion operation and result type,
5117 // based on the target width, but the source type.
5118 spv::Id type = spv::NoType;
5119 spv::Op convOp = spv::OpNop;
5120 switch(op) {
5121 case glslang::EOpConvInt8ToUint16:
5122 case glslang::EOpConvInt8ToUint:
5123 case glslang::EOpConvInt8ToUint64:
5124 case glslang::EOpConvInt16ToUint8:
5125 case glslang::EOpConvInt16ToUint:
5126 case glslang::EOpConvInt16ToUint64:
5127 case glslang::EOpConvIntToUint8:
5128 case glslang::EOpConvIntToUint16:
5129 case glslang::EOpConvIntToUint64:
5130 case glslang::EOpConvInt64ToUint8:
5131 case glslang::EOpConvInt64ToUint16:
5132 case glslang::EOpConvInt64ToUint:
5133 convOp = spv::OpSConvert;
5134 type = builder.makeIntType(width);
5135 break;
5136 default:
5137 convOp = spv::OpUConvert;
5138 type = builder.makeUintType(width);
5139 break;
5140 }
5141
John Kessenich66011cb2018-03-06 16:12:04 -07005142 if (vectorSize > 0)
5143 type = builder.makeVectorType(type, vectorSize);
5144
John Kessenichad7645f2018-06-04 19:11:25 -06005145 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005146}
5147
John Kessenichead86222018-03-28 18:01:20 -06005148spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5149 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005150{
5151 spv::Op convOp = spv::OpNop;
5152 spv::Id zero = 0;
5153 spv::Id one = 0;
5154
5155 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5156
5157 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005158 case glslang::EOpConvInt8ToBool:
5159 case glslang::EOpConvUint8ToBool:
5160 zero = builder.makeUint8Constant(0);
5161 zero = makeSmearedConstant(zero, vectorSize);
5162 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005163 case glslang::EOpConvInt16ToBool:
5164 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005165 zero = builder.makeUint16Constant(0);
5166 zero = makeSmearedConstant(zero, vectorSize);
5167 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5168 case glslang::EOpConvIntToBool:
5169 case glslang::EOpConvUintToBool:
5170 zero = builder.makeUintConstant(0);
5171 zero = makeSmearedConstant(zero, vectorSize);
5172 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5173 case glslang::EOpConvInt64ToBool:
5174 case glslang::EOpConvUint64ToBool:
5175 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005176 zero = makeSmearedConstant(zero, vectorSize);
5177 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5178
5179 case glslang::EOpConvFloatToBool:
5180 zero = builder.makeFloatConstant(0.0F);
5181 zero = makeSmearedConstant(zero, vectorSize);
5182 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5183
5184 case glslang::EOpConvDoubleToBool:
5185 zero = builder.makeDoubleConstant(0.0);
5186 zero = makeSmearedConstant(zero, vectorSize);
5187 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5188
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005189 case glslang::EOpConvFloat16ToBool:
5190 zero = builder.makeFloat16Constant(0.0F);
5191 zero = makeSmearedConstant(zero, vectorSize);
5192 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005193
John Kessenich140f3df2015-06-26 16:58:36 -06005194 case glslang::EOpConvBoolToFloat:
5195 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005196 zero = builder.makeFloatConstant(0.0F);
5197 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005198 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005199
John Kessenich140f3df2015-06-26 16:58:36 -06005200 case glslang::EOpConvBoolToDouble:
5201 convOp = spv::OpSelect;
5202 zero = builder.makeDoubleConstant(0.0);
5203 one = builder.makeDoubleConstant(1.0);
5204 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005205
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005206 case glslang::EOpConvBoolToFloat16:
5207 convOp = spv::OpSelect;
5208 zero = builder.makeFloat16Constant(0.0F);
5209 one = builder.makeFloat16Constant(1.0F);
5210 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005211
5212 case glslang::EOpConvBoolToInt8:
5213 zero = builder.makeInt8Constant(0);
5214 one = builder.makeInt8Constant(1);
5215 convOp = spv::OpSelect;
5216 break;
5217
5218 case glslang::EOpConvBoolToUint8:
5219 zero = builder.makeUint8Constant(0);
5220 one = builder.makeUint8Constant(1);
5221 convOp = spv::OpSelect;
5222 break;
5223
5224 case glslang::EOpConvBoolToInt16:
5225 zero = builder.makeInt16Constant(0);
5226 one = builder.makeInt16Constant(1);
5227 convOp = spv::OpSelect;
5228 break;
5229
5230 case glslang::EOpConvBoolToUint16:
5231 zero = builder.makeUint16Constant(0);
5232 one = builder.makeUint16Constant(1);
5233 convOp = spv::OpSelect;
5234 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005235
John Kessenich140f3df2015-06-26 16:58:36 -06005236 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005237 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005238 if (op == glslang::EOpConvBoolToInt64)
5239 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005240 else
5241 zero = builder.makeIntConstant(0);
5242
5243 if (op == glslang::EOpConvBoolToInt64)
5244 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005245 else
5246 one = builder.makeIntConstant(1);
5247
John Kessenich140f3df2015-06-26 16:58:36 -06005248 convOp = spv::OpSelect;
5249 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005250
John Kessenich140f3df2015-06-26 16:58:36 -06005251 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005252 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005253 if (op == glslang::EOpConvBoolToUint64)
5254 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005255 else
5256 zero = builder.makeUintConstant(0);
5257
5258 if (op == glslang::EOpConvBoolToUint64)
5259 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005260 else
5261 one = builder.makeUintConstant(1);
5262
John Kessenich140f3df2015-06-26 16:58:36 -06005263 convOp = spv::OpSelect;
5264 break;
5265
John Kessenich66011cb2018-03-06 16:12:04 -07005266 case glslang::EOpConvInt8ToFloat16:
5267 case glslang::EOpConvInt8ToFloat:
5268 case glslang::EOpConvInt8ToDouble:
5269 case glslang::EOpConvInt16ToFloat16:
5270 case glslang::EOpConvInt16ToFloat:
5271 case glslang::EOpConvInt16ToDouble:
5272 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005273 case glslang::EOpConvIntToFloat:
5274 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005275 case glslang::EOpConvInt64ToFloat:
5276 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005277 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005278 convOp = spv::OpConvertSToF;
5279 break;
5280
John Kessenich66011cb2018-03-06 16:12:04 -07005281 case glslang::EOpConvUint8ToFloat16:
5282 case glslang::EOpConvUint8ToFloat:
5283 case glslang::EOpConvUint8ToDouble:
5284 case glslang::EOpConvUint16ToFloat16:
5285 case glslang::EOpConvUint16ToFloat:
5286 case glslang::EOpConvUint16ToDouble:
5287 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005288 case glslang::EOpConvUintToFloat:
5289 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005290 case glslang::EOpConvUint64ToFloat:
5291 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005292 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005293 convOp = spv::OpConvertUToF;
5294 break;
5295
5296 case glslang::EOpConvDoubleToFloat:
5297 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005298 case glslang::EOpConvDoubleToFloat16:
5299 case glslang::EOpConvFloat16ToDouble:
5300 case glslang::EOpConvFloatToFloat16:
5301 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005302 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005303 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005304 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005305 break;
5306
John Kessenich66011cb2018-03-06 16:12:04 -07005307 case glslang::EOpConvFloat16ToInt8:
5308 case glslang::EOpConvFloatToInt8:
5309 case glslang::EOpConvDoubleToInt8:
5310 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005311 case glslang::EOpConvFloatToInt16:
5312 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005313 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005314 case glslang::EOpConvFloatToInt:
5315 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005316 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005317 case glslang::EOpConvFloatToInt64:
5318 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005319 convOp = spv::OpConvertFToS;
5320 break;
5321
John Kessenich66011cb2018-03-06 16:12:04 -07005322 case glslang::EOpConvUint8ToInt8:
5323 case glslang::EOpConvInt8ToUint8:
5324 case glslang::EOpConvUint16ToInt16:
5325 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005326 case glslang::EOpConvUintToInt:
5327 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005328 case glslang::EOpConvUint64ToInt64:
5329 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005330 if (builder.isInSpecConstCodeGenMode()) {
5331 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005332 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5333 zero = builder.makeUint8Constant(0);
5334 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005335 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005336 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5337 zero = builder.makeUint64Constant(0);
5338 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005339 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005340 }
qining189b2032016-04-12 23:16:20 -04005341 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005342 // Use OpIAdd, instead of OpBitcast to do the conversion when
5343 // generating for OpSpecConstantOp instruction.
5344 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5345 }
5346 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005347 convOp = spv::OpBitcast;
5348 break;
5349
John Kessenich66011cb2018-03-06 16:12:04 -07005350 case glslang::EOpConvFloat16ToUint8:
5351 case glslang::EOpConvFloatToUint8:
5352 case glslang::EOpConvDoubleToUint8:
5353 case glslang::EOpConvFloat16ToUint16:
5354 case glslang::EOpConvFloatToUint16:
5355 case glslang::EOpConvDoubleToUint16:
5356 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005357 case glslang::EOpConvFloatToUint:
5358 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005359 case glslang::EOpConvFloatToUint64:
5360 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005361 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005362 convOp = spv::OpConvertFToU;
5363 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005364
John Kessenich66011cb2018-03-06 16:12:04 -07005365 case glslang::EOpConvInt8ToInt16:
5366 case glslang::EOpConvInt8ToInt:
5367 case glslang::EOpConvInt8ToInt64:
5368 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005369 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005370 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005371 case glslang::EOpConvIntToInt8:
5372 case glslang::EOpConvIntToInt16:
5373 case glslang::EOpConvIntToInt64:
5374 case glslang::EOpConvInt64ToInt8:
5375 case glslang::EOpConvInt64ToInt16:
5376 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005377 convOp = spv::OpSConvert;
5378 break;
5379
John Kessenich66011cb2018-03-06 16:12:04 -07005380 case glslang::EOpConvUint8ToUint16:
5381 case glslang::EOpConvUint8ToUint:
5382 case glslang::EOpConvUint8ToUint64:
5383 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005384 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005385 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005386 case glslang::EOpConvUintToUint8:
5387 case glslang::EOpConvUintToUint16:
5388 case glslang::EOpConvUintToUint64:
5389 case glslang::EOpConvUint64ToUint8:
5390 case glslang::EOpConvUint64ToUint16:
5391 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005392 convOp = spv::OpUConvert;
5393 break;
5394
John Kessenich66011cb2018-03-06 16:12:04 -07005395 case glslang::EOpConvInt8ToUint16:
5396 case glslang::EOpConvInt8ToUint:
5397 case glslang::EOpConvInt8ToUint64:
5398 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005399 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005400 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005401 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005402 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005403 case glslang::EOpConvIntToUint64:
5404 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005405 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005406 case glslang::EOpConvInt64ToUint:
5407 case glslang::EOpConvUint8ToInt16:
5408 case glslang::EOpConvUint8ToInt:
5409 case glslang::EOpConvUint8ToInt64:
5410 case glslang::EOpConvUint16ToInt8:
5411 case glslang::EOpConvUint16ToInt:
5412 case glslang::EOpConvUint16ToInt64:
5413 case glslang::EOpConvUintToInt8:
5414 case glslang::EOpConvUintToInt16:
5415 case glslang::EOpConvUintToInt64:
5416 case glslang::EOpConvUint64ToInt8:
5417 case glslang::EOpConvUint64ToInt16:
5418 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005419 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005420 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005421
5422 if (builder.isInSpecConstCodeGenMode()) {
5423 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005424 switch(op) {
5425 case glslang::EOpConvInt16ToUint8:
5426 case glslang::EOpConvIntToUint8:
5427 case glslang::EOpConvInt64ToUint8:
5428 case glslang::EOpConvUint16ToInt8:
5429 case glslang::EOpConvUintToInt8:
5430 case glslang::EOpConvUint64ToInt8:
5431 zero = builder.makeUint8Constant(0);
5432 break;
5433 case glslang::EOpConvInt8ToUint16:
5434 case glslang::EOpConvIntToUint16:
5435 case glslang::EOpConvInt64ToUint16:
5436 case glslang::EOpConvUint8ToInt16:
5437 case glslang::EOpConvUintToInt16:
5438 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005439 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005440 break;
5441 case glslang::EOpConvInt8ToUint:
5442 case glslang::EOpConvInt16ToUint:
5443 case glslang::EOpConvInt64ToUint:
5444 case glslang::EOpConvUint8ToInt:
5445 case glslang::EOpConvUint16ToInt:
5446 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005447 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005448 break;
5449 case glslang::EOpConvInt8ToUint64:
5450 case glslang::EOpConvInt16ToUint64:
5451 case glslang::EOpConvIntToUint64:
5452 case glslang::EOpConvUint8ToInt64:
5453 case glslang::EOpConvUint16ToInt64:
5454 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005455 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005456 break;
5457 default:
5458 assert(false && "Default missing");
5459 break;
5460 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005461 zero = makeSmearedConstant(zero, vectorSize);
5462 // Use OpIAdd, instead of OpBitcast to do the conversion when
5463 // generating for OpSpecConstantOp instruction.
5464 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5465 }
5466 // For normal run-time conversion instruction, use OpBitcast.
5467 convOp = spv::OpBitcast;
5468 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005469 default:
5470 break;
5471 }
5472
5473 spv::Id result = 0;
5474 if (convOp == spv::OpNop)
5475 return result;
5476
5477 if (convOp == spv::OpSelect) {
5478 zero = makeSmearedConstant(zero, vectorSize);
5479 one = makeSmearedConstant(one, vectorSize);
5480 result = builder.createTriOp(convOp, destType, operand, one, zero);
5481 } else
5482 result = builder.createUnaryOp(convOp, destType, operand);
5483
John Kessenichead86222018-03-28 18:01:20 -06005484 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005485 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005486 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005487}
5488
5489spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5490{
5491 if (vectorSize == 0)
5492 return constant;
5493
5494 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5495 std::vector<spv::Id> components;
5496 for (int c = 0; c < vectorSize; ++c)
5497 components.push_back(constant);
5498 return builder.makeCompositeConstant(vectorTypeId, components);
5499}
5500
John Kessenich426394d2015-07-23 10:22:48 -06005501// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005502spv::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 -06005503{
5504 spv::Op opCode = spv::OpNop;
5505
5506 switch (op) {
5507 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005508 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005509 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005510 opCode = spv::OpAtomicIAdd;
5511 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005512 case glslang::EOpAtomicCounterSubtract:
5513 opCode = spv::OpAtomicISub;
5514 break;
John Kessenich426394d2015-07-23 10:22:48 -06005515 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005516 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005517 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005518 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005519 break;
5520 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005521 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005522 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005523 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005524 break;
5525 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005526 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005527 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005528 opCode = spv::OpAtomicAnd;
5529 break;
5530 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005531 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005532 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005533 opCode = spv::OpAtomicOr;
5534 break;
5535 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005536 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005537 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005538 opCode = spv::OpAtomicXor;
5539 break;
5540 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005541 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005542 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005543 opCode = spv::OpAtomicExchange;
5544 break;
5545 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005546 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005547 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005548 opCode = spv::OpAtomicCompareExchange;
5549 break;
5550 case glslang::EOpAtomicCounterIncrement:
5551 opCode = spv::OpAtomicIIncrement;
5552 break;
5553 case glslang::EOpAtomicCounterDecrement:
5554 opCode = spv::OpAtomicIDecrement;
5555 break;
5556 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005557 case glslang::EOpImageAtomicLoad:
5558 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005559 opCode = spv::OpAtomicLoad;
5560 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005561 case glslang::EOpAtomicStore:
5562 case glslang::EOpImageAtomicStore:
5563 opCode = spv::OpAtomicStore;
5564 break;
John Kessenich426394d2015-07-23 10:22:48 -06005565 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005566 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005567 break;
5568 }
5569
Rex Xue8fe8b02017-09-26 15:42:56 +08005570 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5571 builder.addCapability(spv::CapabilityInt64Atomics);
5572
John Kessenich426394d2015-07-23 10:22:48 -06005573 // Sort out the operands
5574 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005575 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005576 // - compare-exchange swaps the value and comparator
5577 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005578 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005579 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5580 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5581 spv::Id scopeId;
5582 if (glslangIntermediate->usingVulkanMemoryModel()) {
5583 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5584 } else {
5585 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5586 }
5587 // semantics default to relaxed
5588 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5589 spv::Id semanticsId2 = semanticsId;
5590
5591 pointerId = operands[0];
5592 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5593 // no additional operands
5594 } else if (opCode == spv::OpAtomicCompareExchange) {
5595 compareId = operands[1];
5596 valueId = operands[2];
5597 if (operands.size() > 3) {
5598 scopeId = operands[3];
5599 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5600 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5601 }
5602 } else if (opCode == spv::OpAtomicLoad) {
5603 if (operands.size() > 1) {
5604 scopeId = operands[1];
5605 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5606 }
5607 } else {
5608 // atomic store or RMW
5609 valueId = operands[1];
5610 if (operands.size() > 2) {
5611 scopeId = operands[2];
5612 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5613 }
Rex Xu04db3f52015-09-16 11:44:02 +08005614 }
John Kessenich426394d2015-07-23 10:22:48 -06005615
Jeff Bolz36831c92018-09-05 10:11:41 -05005616 // Check for capabilities
5617 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5618 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5619 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5620 }
John Kessenich426394d2015-07-23 10:22:48 -06005621
Jeff Bolz36831c92018-09-05 10:11:41 -05005622 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5623 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5624 }
John Kessenich48d6e792017-10-06 21:21:48 -06005625
Jeff Bolz36831c92018-09-05 10:11:41 -05005626 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5627 spvAtomicOperands.push_back(pointerId);
5628 spvAtomicOperands.push_back(scopeId);
5629 spvAtomicOperands.push_back(semanticsId);
5630 if (opCode == spv::OpAtomicCompareExchange) {
5631 spvAtomicOperands.push_back(semanticsId2);
5632 spvAtomicOperands.push_back(valueId);
5633 spvAtomicOperands.push_back(compareId);
5634 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5635 spvAtomicOperands.push_back(valueId);
5636 }
John Kessenich48d6e792017-10-06 21:21:48 -06005637
Jeff Bolz36831c92018-09-05 10:11:41 -05005638 if (opCode == spv::OpAtomicStore) {
5639 builder.createNoResultOp(opCode, spvAtomicOperands);
5640 return 0;
5641 } else {
5642 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5643
5644 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5645 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5646 if (op == glslang::EOpAtomicCounterDecrement)
5647 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5648
5649 return resultId;
5650 }
John Kessenich426394d2015-07-23 10:22:48 -06005651}
5652
John Kessenich91cef522016-05-05 16:45:40 -06005653// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005654spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005655{
Corentin Walleze7061422018-08-08 15:20:15 +02005656#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005657 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5658 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005659#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005660
Rex Xu51596642016-09-21 18:56:12 +08005661 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005662 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005663 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5664
chaocf200da82016-12-20 12:44:35 -08005665 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5666 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005667 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5668 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005669 } else if (op == glslang::EOpAnyInvocation ||
5670 op == glslang::EOpAllInvocations ||
5671 op == glslang::EOpAllInvocationsEqual) {
5672 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5673 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005674 } else {
5675 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005676#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005677 if (op == glslang::EOpMinInvocationsNonUniform ||
5678 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005679 op == glslang::EOpAddInvocationsNonUniform ||
5680 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5681 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5682 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5683 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5684 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5685 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005686 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005687#endif
Rex Xu51596642016-09-21 18:56:12 +08005688
Rex Xu9d93a232016-05-05 12:30:44 +08005689#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005690 switch (op) {
5691 case glslang::EOpMinInvocations:
5692 case glslang::EOpMaxInvocations:
5693 case glslang::EOpAddInvocations:
5694 case glslang::EOpMinInvocationsNonUniform:
5695 case glslang::EOpMaxInvocationsNonUniform:
5696 case glslang::EOpAddInvocationsNonUniform:
5697 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005698 break;
5699 case glslang::EOpMinInvocationsInclusiveScan:
5700 case glslang::EOpMaxInvocationsInclusiveScan:
5701 case glslang::EOpAddInvocationsInclusiveScan:
5702 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5703 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5704 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5705 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005706 break;
5707 case glslang::EOpMinInvocationsExclusiveScan:
5708 case glslang::EOpMaxInvocationsExclusiveScan:
5709 case glslang::EOpAddInvocationsExclusiveScan:
5710 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5711 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5712 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5713 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005714 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005715 default:
5716 break;
Rex Xu430ef402016-10-14 17:22:23 +08005717 }
John Kessenich149afc32018-08-14 13:31:43 -06005718 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5719 spvGroupOperands.push_back(scope);
5720 if (groupOperation != spv::GroupOperationMax) {
5721 spv::IdImmediate groupOp = { false, groupOperation };
5722 spvGroupOperands.push_back(groupOp);
5723 }
Rex Xu9d93a232016-05-05 12:30:44 +08005724#endif
Rex Xu51596642016-09-21 18:56:12 +08005725 }
5726
John Kessenich149afc32018-08-14 13:31:43 -06005727 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5728 spv::IdImmediate op = { true, *opIt };
5729 spvGroupOperands.push_back(op);
5730 }
John Kessenich91cef522016-05-05 16:45:40 -06005731
5732 switch (op) {
5733 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005734 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005735 break;
John Kessenich91cef522016-05-05 16:45:40 -06005736 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005737 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005738 break;
John Kessenich91cef522016-05-05 16:45:40 -06005739 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005740 opCode = spv::OpSubgroupAllEqualKHR;
5741 break;
Rex Xu51596642016-09-21 18:56:12 +08005742 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005743 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005744 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005745 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005746 break;
5747 case glslang::EOpReadFirstInvocation:
5748 opCode = spv::OpSubgroupFirstInvocationKHR;
5749 break;
5750 case glslang::EOpBallot:
5751 {
5752 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5753 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5754 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5755 //
5756 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5757 //
5758 spv::Id uintType = builder.makeUintType(32);
5759 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5760 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5761
5762 std::vector<spv::Id> components;
5763 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5764 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5765
5766 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5767 return builder.createUnaryOp(spv::OpBitcast, typeId,
5768 builder.createCompositeConstruct(uvec2Type, components));
5769 }
5770
Rex Xu9d93a232016-05-05 12:30:44 +08005771#ifdef AMD_EXTENSIONS
5772 case glslang::EOpMinInvocations:
5773 case glslang::EOpMaxInvocations:
5774 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005775 case glslang::EOpMinInvocationsInclusiveScan:
5776 case glslang::EOpMaxInvocationsInclusiveScan:
5777 case glslang::EOpAddInvocationsInclusiveScan:
5778 case glslang::EOpMinInvocationsExclusiveScan:
5779 case glslang::EOpMaxInvocationsExclusiveScan:
5780 case glslang::EOpAddInvocationsExclusiveScan:
5781 if (op == glslang::EOpMinInvocations ||
5782 op == glslang::EOpMinInvocationsInclusiveScan ||
5783 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005784 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005785 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005786 else {
5787 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005788 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005789 else
Rex Xu51596642016-09-21 18:56:12 +08005790 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005791 }
Rex Xu430ef402016-10-14 17:22:23 +08005792 } else if (op == glslang::EOpMaxInvocations ||
5793 op == glslang::EOpMaxInvocationsInclusiveScan ||
5794 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005795 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005796 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005797 else {
5798 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005799 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005800 else
Rex Xu51596642016-09-21 18:56:12 +08005801 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005802 }
5803 } else {
5804 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005805 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005806 else
Rex Xu51596642016-09-21 18:56:12 +08005807 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005808 }
5809
Rex Xu2bbbe062016-08-23 15:41:05 +08005810 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005811 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005812
5813 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005814 case glslang::EOpMinInvocationsNonUniform:
5815 case glslang::EOpMaxInvocationsNonUniform:
5816 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005817 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5818 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5819 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5820 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5821 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5822 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5823 if (op == glslang::EOpMinInvocationsNonUniform ||
5824 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5825 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005826 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005827 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005828 else {
5829 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005830 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005831 else
Rex Xu51596642016-09-21 18:56:12 +08005832 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005833 }
5834 }
Rex Xu430ef402016-10-14 17:22:23 +08005835 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5836 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5837 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005838 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005839 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005840 else {
5841 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005842 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005843 else
Rex Xu51596642016-09-21 18:56:12 +08005844 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005845 }
5846 }
5847 else {
5848 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005849 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005850 else
Rex Xu51596642016-09-21 18:56:12 +08005851 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005852 }
5853
Rex Xu2bbbe062016-08-23 15:41:05 +08005854 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005855 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005856
5857 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005858#endif
John Kessenich91cef522016-05-05 16:45:40 -06005859 default:
5860 logger->missingFunctionality("invocation operation");
5861 return spv::NoResult;
5862 }
Rex Xu51596642016-09-21 18:56:12 +08005863
5864 assert(opCode != spv::OpNop);
5865 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005866}
5867
Rex Xu2bbbe062016-08-23 15:41:05 +08005868// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005869spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5870 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005871{
Rex Xub7072052016-09-26 15:53:40 +08005872#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005873 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5874 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005875 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005876 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005877 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5878 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5879 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005880#else
5881 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5882 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005883 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5884 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005885#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005886
5887 // Handle group invocation operations scalar by scalar.
5888 // The result type is the same type as the original type.
5889 // The algorithm is to:
5890 // - break the vector into scalars
5891 // - apply the operation to each scalar
5892 // - make a vector out the scalar results
5893
5894 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005895 int numComponents = builder.getNumComponents(operands[0]);
5896 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005897 std::vector<spv::Id> results;
5898
5899 // do each scalar op
5900 for (int comp = 0; comp < numComponents; ++comp) {
5901 std::vector<unsigned int> indexes;
5902 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06005903 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
5904 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005905 if (op == spv::OpSubgroupReadInvocationKHR) {
5906 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005907 spv::IdImmediate operand = { true, operands[1] };
5908 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08005909 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06005910 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5911 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08005912 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005913 spv::IdImmediate operand = { true, operands[1] };
5914 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08005915 } else {
John Kessenich149afc32018-08-14 13:31:43 -06005916 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5917 spvGroupOperands.push_back(scope);
5918 spv::IdImmediate groupOp = { false, groupOperation };
5919 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08005920 spvGroupOperands.push_back(scalar);
5921 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005922
Rex Xub7072052016-09-26 15:53:40 +08005923 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005924 }
5925
5926 // put the pieces together
5927 return builder.createCompositeConstruct(typeId, results);
5928}
Rex Xu2bbbe062016-08-23 15:41:05 +08005929
John Kessenich66011cb2018-03-06 16:12:04 -07005930// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06005931spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
5932 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07005933{
5934 // Add the required capabilities.
5935 switch (op) {
5936 case glslang::EOpSubgroupElect:
5937 builder.addCapability(spv::CapabilityGroupNonUniform);
5938 break;
5939 case glslang::EOpSubgroupAll:
5940 case glslang::EOpSubgroupAny:
5941 case glslang::EOpSubgroupAllEqual:
5942 builder.addCapability(spv::CapabilityGroupNonUniform);
5943 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5944 break;
5945 case glslang::EOpSubgroupBroadcast:
5946 case glslang::EOpSubgroupBroadcastFirst:
5947 case glslang::EOpSubgroupBallot:
5948 case glslang::EOpSubgroupInverseBallot:
5949 case glslang::EOpSubgroupBallotBitExtract:
5950 case glslang::EOpSubgroupBallotBitCount:
5951 case glslang::EOpSubgroupBallotInclusiveBitCount:
5952 case glslang::EOpSubgroupBallotExclusiveBitCount:
5953 case glslang::EOpSubgroupBallotFindLSB:
5954 case glslang::EOpSubgroupBallotFindMSB:
5955 builder.addCapability(spv::CapabilityGroupNonUniform);
5956 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5957 break;
5958 case glslang::EOpSubgroupShuffle:
5959 case glslang::EOpSubgroupShuffleXor:
5960 builder.addCapability(spv::CapabilityGroupNonUniform);
5961 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5962 break;
5963 case glslang::EOpSubgroupShuffleUp:
5964 case glslang::EOpSubgroupShuffleDown:
5965 builder.addCapability(spv::CapabilityGroupNonUniform);
5966 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5967 break;
5968 case glslang::EOpSubgroupAdd:
5969 case glslang::EOpSubgroupMul:
5970 case glslang::EOpSubgroupMin:
5971 case glslang::EOpSubgroupMax:
5972 case glslang::EOpSubgroupAnd:
5973 case glslang::EOpSubgroupOr:
5974 case glslang::EOpSubgroupXor:
5975 case glslang::EOpSubgroupInclusiveAdd:
5976 case glslang::EOpSubgroupInclusiveMul:
5977 case glslang::EOpSubgroupInclusiveMin:
5978 case glslang::EOpSubgroupInclusiveMax:
5979 case glslang::EOpSubgroupInclusiveAnd:
5980 case glslang::EOpSubgroupInclusiveOr:
5981 case glslang::EOpSubgroupInclusiveXor:
5982 case glslang::EOpSubgroupExclusiveAdd:
5983 case glslang::EOpSubgroupExclusiveMul:
5984 case glslang::EOpSubgroupExclusiveMin:
5985 case glslang::EOpSubgroupExclusiveMax:
5986 case glslang::EOpSubgroupExclusiveAnd:
5987 case glslang::EOpSubgroupExclusiveOr:
5988 case glslang::EOpSubgroupExclusiveXor:
5989 builder.addCapability(spv::CapabilityGroupNonUniform);
5990 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5991 break;
5992 case glslang::EOpSubgroupClusteredAdd:
5993 case glslang::EOpSubgroupClusteredMul:
5994 case glslang::EOpSubgroupClusteredMin:
5995 case glslang::EOpSubgroupClusteredMax:
5996 case glslang::EOpSubgroupClusteredAnd:
5997 case glslang::EOpSubgroupClusteredOr:
5998 case glslang::EOpSubgroupClusteredXor:
5999 builder.addCapability(spv::CapabilityGroupNonUniform);
6000 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6001 break;
6002 case glslang::EOpSubgroupQuadBroadcast:
6003 case glslang::EOpSubgroupQuadSwapHorizontal:
6004 case glslang::EOpSubgroupQuadSwapVertical:
6005 case glslang::EOpSubgroupQuadSwapDiagonal:
6006 builder.addCapability(spv::CapabilityGroupNonUniform);
6007 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6008 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006009#ifdef NV_EXTENSIONS
6010 case glslang::EOpSubgroupPartitionedAdd:
6011 case glslang::EOpSubgroupPartitionedMul:
6012 case glslang::EOpSubgroupPartitionedMin:
6013 case glslang::EOpSubgroupPartitionedMax:
6014 case glslang::EOpSubgroupPartitionedAnd:
6015 case glslang::EOpSubgroupPartitionedOr:
6016 case glslang::EOpSubgroupPartitionedXor:
6017 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6018 case glslang::EOpSubgroupPartitionedInclusiveMul:
6019 case glslang::EOpSubgroupPartitionedInclusiveMin:
6020 case glslang::EOpSubgroupPartitionedInclusiveMax:
6021 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6022 case glslang::EOpSubgroupPartitionedInclusiveOr:
6023 case glslang::EOpSubgroupPartitionedInclusiveXor:
6024 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6025 case glslang::EOpSubgroupPartitionedExclusiveMul:
6026 case glslang::EOpSubgroupPartitionedExclusiveMin:
6027 case glslang::EOpSubgroupPartitionedExclusiveMax:
6028 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6029 case glslang::EOpSubgroupPartitionedExclusiveOr:
6030 case glslang::EOpSubgroupPartitionedExclusiveXor:
6031 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6032 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6033 break;
6034#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006035 default: assert(0 && "Unhandled subgroup operation!");
6036 }
6037
6038 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6039 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6040 const bool isBool = typeProxy == glslang::EbtBool;
6041
6042 spv::Op opCode = spv::OpNop;
6043
6044 // Figure out which opcode to use.
6045 switch (op) {
6046 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6047 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6048 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6049 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6050 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6051 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6052 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6053 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6054 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6055 case glslang::EOpSubgroupBallotBitCount:
6056 case glslang::EOpSubgroupBallotInclusiveBitCount:
6057 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6058 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6059 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6060 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6061 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6062 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6063 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6064 case glslang::EOpSubgroupAdd:
6065 case glslang::EOpSubgroupInclusiveAdd:
6066 case glslang::EOpSubgroupExclusiveAdd:
6067 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006068#ifdef NV_EXTENSIONS
6069 case glslang::EOpSubgroupPartitionedAdd:
6070 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6071 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6072#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006073 if (isFloat) {
6074 opCode = spv::OpGroupNonUniformFAdd;
6075 } else {
6076 opCode = spv::OpGroupNonUniformIAdd;
6077 }
6078 break;
6079 case glslang::EOpSubgroupMul:
6080 case glslang::EOpSubgroupInclusiveMul:
6081 case glslang::EOpSubgroupExclusiveMul:
6082 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006083#ifdef NV_EXTENSIONS
6084 case glslang::EOpSubgroupPartitionedMul:
6085 case glslang::EOpSubgroupPartitionedInclusiveMul:
6086 case glslang::EOpSubgroupPartitionedExclusiveMul:
6087#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006088 if (isFloat) {
6089 opCode = spv::OpGroupNonUniformFMul;
6090 } else {
6091 opCode = spv::OpGroupNonUniformIMul;
6092 }
6093 break;
6094 case glslang::EOpSubgroupMin:
6095 case glslang::EOpSubgroupInclusiveMin:
6096 case glslang::EOpSubgroupExclusiveMin:
6097 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006098#ifdef NV_EXTENSIONS
6099 case glslang::EOpSubgroupPartitionedMin:
6100 case glslang::EOpSubgroupPartitionedInclusiveMin:
6101 case glslang::EOpSubgroupPartitionedExclusiveMin:
6102#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006103 if (isFloat) {
6104 opCode = spv::OpGroupNonUniformFMin;
6105 } else if (isUnsigned) {
6106 opCode = spv::OpGroupNonUniformUMin;
6107 } else {
6108 opCode = spv::OpGroupNonUniformSMin;
6109 }
6110 break;
6111 case glslang::EOpSubgroupMax:
6112 case glslang::EOpSubgroupInclusiveMax:
6113 case glslang::EOpSubgroupExclusiveMax:
6114 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006115#ifdef NV_EXTENSIONS
6116 case glslang::EOpSubgroupPartitionedMax:
6117 case glslang::EOpSubgroupPartitionedInclusiveMax:
6118 case glslang::EOpSubgroupPartitionedExclusiveMax:
6119#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006120 if (isFloat) {
6121 opCode = spv::OpGroupNonUniformFMax;
6122 } else if (isUnsigned) {
6123 opCode = spv::OpGroupNonUniformUMax;
6124 } else {
6125 opCode = spv::OpGroupNonUniformSMax;
6126 }
6127 break;
6128 case glslang::EOpSubgroupAnd:
6129 case glslang::EOpSubgroupInclusiveAnd:
6130 case glslang::EOpSubgroupExclusiveAnd:
6131 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006132#ifdef NV_EXTENSIONS
6133 case glslang::EOpSubgroupPartitionedAnd:
6134 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6135 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6136#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006137 if (isBool) {
6138 opCode = spv::OpGroupNonUniformLogicalAnd;
6139 } else {
6140 opCode = spv::OpGroupNonUniformBitwiseAnd;
6141 }
6142 break;
6143 case glslang::EOpSubgroupOr:
6144 case glslang::EOpSubgroupInclusiveOr:
6145 case glslang::EOpSubgroupExclusiveOr:
6146 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006147#ifdef NV_EXTENSIONS
6148 case glslang::EOpSubgroupPartitionedOr:
6149 case glslang::EOpSubgroupPartitionedInclusiveOr:
6150 case glslang::EOpSubgroupPartitionedExclusiveOr:
6151#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006152 if (isBool) {
6153 opCode = spv::OpGroupNonUniformLogicalOr;
6154 } else {
6155 opCode = spv::OpGroupNonUniformBitwiseOr;
6156 }
6157 break;
6158 case glslang::EOpSubgroupXor:
6159 case glslang::EOpSubgroupInclusiveXor:
6160 case glslang::EOpSubgroupExclusiveXor:
6161 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006162#ifdef NV_EXTENSIONS
6163 case glslang::EOpSubgroupPartitionedXor:
6164 case glslang::EOpSubgroupPartitionedInclusiveXor:
6165 case glslang::EOpSubgroupPartitionedExclusiveXor:
6166#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006167 if (isBool) {
6168 opCode = spv::OpGroupNonUniformLogicalXor;
6169 } else {
6170 opCode = spv::OpGroupNonUniformBitwiseXor;
6171 }
6172 break;
6173 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6174 case glslang::EOpSubgroupQuadSwapHorizontal:
6175 case glslang::EOpSubgroupQuadSwapVertical:
6176 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6177 default: assert(0 && "Unhandled subgroup operation!");
6178 }
6179
John Kessenich149afc32018-08-14 13:31:43 -06006180 // get the right Group Operation
6181 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006182 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006183 default:
6184 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006185 case glslang::EOpSubgroupBallotBitCount:
6186 case glslang::EOpSubgroupAdd:
6187 case glslang::EOpSubgroupMul:
6188 case glslang::EOpSubgroupMin:
6189 case glslang::EOpSubgroupMax:
6190 case glslang::EOpSubgroupAnd:
6191 case glslang::EOpSubgroupOr:
6192 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006193 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006194 break;
6195 case glslang::EOpSubgroupBallotInclusiveBitCount:
6196 case glslang::EOpSubgroupInclusiveAdd:
6197 case glslang::EOpSubgroupInclusiveMul:
6198 case glslang::EOpSubgroupInclusiveMin:
6199 case glslang::EOpSubgroupInclusiveMax:
6200 case glslang::EOpSubgroupInclusiveAnd:
6201 case glslang::EOpSubgroupInclusiveOr:
6202 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006203 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006204 break;
6205 case glslang::EOpSubgroupBallotExclusiveBitCount:
6206 case glslang::EOpSubgroupExclusiveAdd:
6207 case glslang::EOpSubgroupExclusiveMul:
6208 case glslang::EOpSubgroupExclusiveMin:
6209 case glslang::EOpSubgroupExclusiveMax:
6210 case glslang::EOpSubgroupExclusiveAnd:
6211 case glslang::EOpSubgroupExclusiveOr:
6212 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006213 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006214 break;
6215 case glslang::EOpSubgroupClusteredAdd:
6216 case glslang::EOpSubgroupClusteredMul:
6217 case glslang::EOpSubgroupClusteredMin:
6218 case glslang::EOpSubgroupClusteredMax:
6219 case glslang::EOpSubgroupClusteredAnd:
6220 case glslang::EOpSubgroupClusteredOr:
6221 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006222 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006223 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006224#ifdef NV_EXTENSIONS
6225 case glslang::EOpSubgroupPartitionedAdd:
6226 case glslang::EOpSubgroupPartitionedMul:
6227 case glslang::EOpSubgroupPartitionedMin:
6228 case glslang::EOpSubgroupPartitionedMax:
6229 case glslang::EOpSubgroupPartitionedAnd:
6230 case glslang::EOpSubgroupPartitionedOr:
6231 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006232 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006233 break;
6234 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6235 case glslang::EOpSubgroupPartitionedInclusiveMul:
6236 case glslang::EOpSubgroupPartitionedInclusiveMin:
6237 case glslang::EOpSubgroupPartitionedInclusiveMax:
6238 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6239 case glslang::EOpSubgroupPartitionedInclusiveOr:
6240 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006241 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006242 break;
6243 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6244 case glslang::EOpSubgroupPartitionedExclusiveMul:
6245 case glslang::EOpSubgroupPartitionedExclusiveMin:
6246 case glslang::EOpSubgroupPartitionedExclusiveMax:
6247 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6248 case glslang::EOpSubgroupPartitionedExclusiveOr:
6249 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006250 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006251 break;
6252#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006253 }
6254
John Kessenich149afc32018-08-14 13:31:43 -06006255 // build the instruction
6256 std::vector<spv::IdImmediate> spvGroupOperands;
6257
6258 // Every operation begins with the Execution Scope operand.
6259 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6260 spvGroupOperands.push_back(executionScope);
6261
6262 // Next, for all operations that use a Group Operation, push that as an operand.
6263 if (groupOperation != spv::GroupOperationMax) {
6264 spv::IdImmediate groupOperand = { false, groupOperation };
6265 spvGroupOperands.push_back(groupOperand);
6266 }
6267
John Kessenich66011cb2018-03-06 16:12:04 -07006268 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006269 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6270 spv::IdImmediate operand = { true, *opIt };
6271 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006272 }
6273
6274 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006275 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006276 switch (op) {
6277 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006278 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6279 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6280 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6281 }
6282 if (directionId != spv::NoResult) {
6283 spv::IdImmediate direction = { true, directionId };
6284 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006285 }
6286
6287 return builder.createOp(opCode, typeId, spvGroupOperands);
6288}
6289
John Kessenich5e4b1242015-08-06 22:53:06 -06006290spv::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 -06006291{
John Kessenich66011cb2018-03-06 16:12:04 -07006292 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6293 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006294
John Kessenich140f3df2015-06-26 16:58:36 -06006295 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006296 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006297 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006298 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006299 spv::Id typeId0 = 0;
6300 if (consumedOperands > 0)
6301 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006302 spv::Id typeId1 = 0;
6303 if (consumedOperands > 1)
6304 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006305 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006306
6307 switch (op) {
6308 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006309 if (isFloat)
6310 libCall = spv::GLSLstd450FMin;
6311 else if (isUnsigned)
6312 libCall = spv::GLSLstd450UMin;
6313 else
6314 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006315 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006316 break;
6317 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006318 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006319 break;
6320 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006321 if (isFloat)
6322 libCall = spv::GLSLstd450FMax;
6323 else if (isUnsigned)
6324 libCall = spv::GLSLstd450UMax;
6325 else
6326 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006327 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006328 break;
6329 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006330 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006331 break;
6332 case glslang::EOpDot:
6333 opCode = spv::OpDot;
6334 break;
6335 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006336 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006337 break;
6338
6339 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006340 if (isFloat)
6341 libCall = spv::GLSLstd450FClamp;
6342 else if (isUnsigned)
6343 libCall = spv::GLSLstd450UClamp;
6344 else
6345 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006346 builder.promoteScalar(precision, operands.front(), operands[1]);
6347 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006348 break;
6349 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006350 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6351 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006352 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006353 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006354 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006355 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006356 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006357 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006358 break;
6359 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006360 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006361 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006362 break;
6363 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006364 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006365 builder.promoteScalar(precision, operands[0], operands[2]);
6366 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006367 break;
6368
6369 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006370 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006371 break;
6372 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006373 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006374 break;
6375 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006376 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006377 break;
6378 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006379 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006380 break;
6381 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006382 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006383 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006384 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006385#ifdef AMD_EXTENSIONS
6386 if (typeProxy == glslang::EbtFloat16)
6387 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6388#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006389 libCall = spv::GLSLstd450InterpolateAtSample;
6390 break;
6391 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006392#ifdef AMD_EXTENSIONS
6393 if (typeProxy == glslang::EbtFloat16)
6394 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6395#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006396 libCall = spv::GLSLstd450InterpolateAtOffset;
6397 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006398 case glslang::EOpAddCarry:
6399 opCode = spv::OpIAddCarry;
6400 typeId = builder.makeStructResultType(typeId0, typeId0);
6401 consumedOperands = 2;
6402 break;
6403 case glslang::EOpSubBorrow:
6404 opCode = spv::OpISubBorrow;
6405 typeId = builder.makeStructResultType(typeId0, typeId0);
6406 consumedOperands = 2;
6407 break;
6408 case glslang::EOpUMulExtended:
6409 opCode = spv::OpUMulExtended;
6410 typeId = builder.makeStructResultType(typeId0, typeId0);
6411 consumedOperands = 2;
6412 break;
6413 case glslang::EOpIMulExtended:
6414 opCode = spv::OpSMulExtended;
6415 typeId = builder.makeStructResultType(typeId0, typeId0);
6416 consumedOperands = 2;
6417 break;
6418 case glslang::EOpBitfieldExtract:
6419 if (isUnsigned)
6420 opCode = spv::OpBitFieldUExtract;
6421 else
6422 opCode = spv::OpBitFieldSExtract;
6423 break;
6424 case glslang::EOpBitfieldInsert:
6425 opCode = spv::OpBitFieldInsert;
6426 break;
6427
6428 case glslang::EOpFma:
6429 libCall = spv::GLSLstd450Fma;
6430 break;
6431 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006432 {
6433 libCall = spv::GLSLstd450FrexpStruct;
6434 assert(builder.isPointerType(typeId1));
6435 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006436 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006437#ifdef AMD_EXTENSIONS
6438 if (width == 16)
6439 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6440 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6441#endif
Rex Xu470026f2017-03-29 17:12:40 +08006442 if (builder.getNumComponents(operands[0]) == 1)
6443 frexpIntType = builder.makeIntegerType(width, true);
6444 else
6445 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6446 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6447 consumedOperands = 1;
6448 }
John Kessenich55e7d112015-11-15 21:33:39 -07006449 break;
6450 case glslang::EOpLdexp:
6451 libCall = spv::GLSLstd450Ldexp;
6452 break;
6453
Rex Xu574ab042016-04-14 16:53:07 +08006454 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006455 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006456
John Kessenich66011cb2018-03-06 16:12:04 -07006457 case glslang::EOpSubgroupBroadcast:
6458 case glslang::EOpSubgroupBallotBitExtract:
6459 case glslang::EOpSubgroupShuffle:
6460 case glslang::EOpSubgroupShuffleXor:
6461 case glslang::EOpSubgroupShuffleUp:
6462 case glslang::EOpSubgroupShuffleDown:
6463 case glslang::EOpSubgroupClusteredAdd:
6464 case glslang::EOpSubgroupClusteredMul:
6465 case glslang::EOpSubgroupClusteredMin:
6466 case glslang::EOpSubgroupClusteredMax:
6467 case glslang::EOpSubgroupClusteredAnd:
6468 case glslang::EOpSubgroupClusteredOr:
6469 case glslang::EOpSubgroupClusteredXor:
6470 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006471#ifdef NV_EXTENSIONS
6472 case glslang::EOpSubgroupPartitionedAdd:
6473 case glslang::EOpSubgroupPartitionedMul:
6474 case glslang::EOpSubgroupPartitionedMin:
6475 case glslang::EOpSubgroupPartitionedMax:
6476 case glslang::EOpSubgroupPartitionedAnd:
6477 case glslang::EOpSubgroupPartitionedOr:
6478 case glslang::EOpSubgroupPartitionedXor:
6479 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6480 case glslang::EOpSubgroupPartitionedInclusiveMul:
6481 case glslang::EOpSubgroupPartitionedInclusiveMin:
6482 case glslang::EOpSubgroupPartitionedInclusiveMax:
6483 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6484 case glslang::EOpSubgroupPartitionedInclusiveOr:
6485 case glslang::EOpSubgroupPartitionedInclusiveXor:
6486 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6487 case glslang::EOpSubgroupPartitionedExclusiveMul:
6488 case glslang::EOpSubgroupPartitionedExclusiveMin:
6489 case glslang::EOpSubgroupPartitionedExclusiveMax:
6490 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6491 case glslang::EOpSubgroupPartitionedExclusiveOr:
6492 case glslang::EOpSubgroupPartitionedExclusiveXor:
6493#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006494 return createSubgroupOperation(op, typeId, operands, typeProxy);
6495
Rex Xu9d93a232016-05-05 12:30:44 +08006496#ifdef AMD_EXTENSIONS
6497 case glslang::EOpSwizzleInvocations:
6498 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6499 libCall = spv::SwizzleInvocationsAMD;
6500 break;
6501 case glslang::EOpSwizzleInvocationsMasked:
6502 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6503 libCall = spv::SwizzleInvocationsMaskedAMD;
6504 break;
6505 case glslang::EOpWriteInvocation:
6506 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6507 libCall = spv::WriteInvocationAMD;
6508 break;
6509
6510 case glslang::EOpMin3:
6511 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6512 if (isFloat)
6513 libCall = spv::FMin3AMD;
6514 else {
6515 if (isUnsigned)
6516 libCall = spv::UMin3AMD;
6517 else
6518 libCall = spv::SMin3AMD;
6519 }
6520 break;
6521 case glslang::EOpMax3:
6522 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6523 if (isFloat)
6524 libCall = spv::FMax3AMD;
6525 else {
6526 if (isUnsigned)
6527 libCall = spv::UMax3AMD;
6528 else
6529 libCall = spv::SMax3AMD;
6530 }
6531 break;
6532 case glslang::EOpMid3:
6533 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6534 if (isFloat)
6535 libCall = spv::FMid3AMD;
6536 else {
6537 if (isUnsigned)
6538 libCall = spv::UMid3AMD;
6539 else
6540 libCall = spv::SMid3AMD;
6541 }
6542 break;
6543
6544 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006545 if (typeProxy == glslang::EbtFloat16)
6546 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006547 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6548 libCall = spv::InterpolateAtVertexAMD;
6549 break;
6550#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006551 case glslang::EOpBarrier:
6552 {
6553 // This is for the extended controlBarrier function, with four operands.
6554 // The unextended barrier() goes through createNoArgOperation.
6555 assert(operands.size() == 4);
6556 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6557 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6558 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6559 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6560 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6561 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6562 }
6563 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6564 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6565 }
6566 return 0;
6567 }
6568 break;
6569 case glslang::EOpMemoryBarrier:
6570 {
6571 // This is for the extended memoryBarrier function, with three operands.
6572 // The unextended memoryBarrier() goes through createNoArgOperation.
6573 assert(operands.size() == 3);
6574 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6575 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6576 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6577 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6578 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6579 }
6580 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6581 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6582 }
6583 return 0;
6584 }
6585 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006586 default:
6587 return 0;
6588 }
6589
6590 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006591 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006592 // Use an extended instruction from the standard library.
6593 // Construct the call arguments, without modifying the original operands vector.
6594 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6595 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006596 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006597 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006598 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006599 case 0:
6600 // should all be handled by visitAggregate and createNoArgOperation
6601 assert(0);
6602 return 0;
6603 case 1:
6604 // should all be handled by createUnaryOperation
6605 assert(0);
6606 return 0;
6607 case 2:
6608 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6609 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006610 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006611 // anything 3 or over doesn't have l-value operands, so all should be consumed
6612 assert(consumedOperands == operands.size());
6613 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006614 break;
6615 }
6616 }
6617
John Kessenich55e7d112015-11-15 21:33:39 -07006618 // Decode the return types that were structures
6619 switch (op) {
6620 case glslang::EOpAddCarry:
6621 case glslang::EOpSubBorrow:
6622 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6623 id = builder.createCompositeExtract(id, typeId0, 0);
6624 break;
6625 case glslang::EOpUMulExtended:
6626 case glslang::EOpIMulExtended:
6627 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6628 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6629 break;
6630 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006631 {
6632 assert(operands.size() == 2);
6633 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6634 // "exp" is floating-point type (from HLSL intrinsic)
6635 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6636 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6637 builder.createStore(member1, operands[1]);
6638 } else
6639 // "exp" is integer type (from GLSL built-in function)
6640 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6641 id = builder.createCompositeExtract(id, typeId0, 0);
6642 }
John Kessenich55e7d112015-11-15 21:33:39 -07006643 break;
6644 default:
6645 break;
6646 }
6647
John Kessenich32cfd492016-02-02 12:37:46 -07006648 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006649}
6650
Rex Xu9d93a232016-05-05 12:30:44 +08006651// Intrinsics with no arguments (or no return value, and no precision).
6652spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006653{
Jeff Bolz36831c92018-09-05 10:11:41 -05006654 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6655 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006656
6657 switch (op) {
6658 case glslang::EOpEmitVertex:
6659 builder.createNoResultOp(spv::OpEmitVertex);
6660 return 0;
6661 case glslang::EOpEndPrimitive:
6662 builder.createNoResultOp(spv::OpEndPrimitive);
6663 return 0;
6664 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006665 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006666 if (glslangIntermediate->usingVulkanMemoryModel()) {
6667 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6668 spv::MemorySemanticsOutputMemoryKHRMask |
6669 spv::MemorySemanticsAcquireReleaseMask);
6670 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6671 } else {
6672 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6673 }
John Kessenich82979362017-12-11 04:02:24 -07006674 } else {
6675 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6676 spv::MemorySemanticsWorkgroupMemoryMask |
6677 spv::MemorySemanticsAcquireReleaseMask);
6678 }
John Kessenich140f3df2015-06-26 16:58:36 -06006679 return 0;
6680 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006681 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6682 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006683 return 0;
6684 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006685 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6686 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006687 return 0;
6688 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006689 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6690 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006691 return 0;
6692 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006693 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6694 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006695 return 0;
6696 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006697 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6698 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006699 return 0;
6700 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006701 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6702 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006703 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006704 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006705 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006706 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006707 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006708 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006709 case glslang::EOpDeviceMemoryBarrier:
6710 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6711 spv::MemorySemanticsImageMemoryMask |
6712 spv::MemorySemanticsAcquireReleaseMask);
6713 return 0;
6714 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6715 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6716 spv::MemorySemanticsImageMemoryMask |
6717 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006718 return 0;
6719 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006720 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6721 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006722 return 0;
6723 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006724 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6725 spv::MemorySemanticsWorkgroupMemoryMask |
6726 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006727 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006728 case glslang::EOpSubgroupBarrier:
6729 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6730 spv::MemorySemanticsAcquireReleaseMask);
6731 return spv::NoResult;
6732 case glslang::EOpSubgroupMemoryBarrier:
6733 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6734 spv::MemorySemanticsAcquireReleaseMask);
6735 return spv::NoResult;
6736 case glslang::EOpSubgroupMemoryBarrierBuffer:
6737 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6738 spv::MemorySemanticsAcquireReleaseMask);
6739 return spv::NoResult;
6740 case glslang::EOpSubgroupMemoryBarrierImage:
6741 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6742 spv::MemorySemanticsAcquireReleaseMask);
6743 return spv::NoResult;
6744 case glslang::EOpSubgroupMemoryBarrierShared:
6745 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6746 spv::MemorySemanticsAcquireReleaseMask);
6747 return spv::NoResult;
6748 case glslang::EOpSubgroupElect: {
6749 std::vector<spv::Id> operands;
6750 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6751 }
Rex Xu9d93a232016-05-05 12:30:44 +08006752#ifdef AMD_EXTENSIONS
6753 case glslang::EOpTime:
6754 {
6755 std::vector<spv::Id> args; // Dummy arguments
6756 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6757 return builder.setPrecision(id, precision);
6758 }
6759#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006760 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006761 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006762 return 0;
6763 }
6764}
6765
6766spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6767{
John Kessenich2f273362015-07-18 22:34:27 -06006768 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006769 spv::Id id;
6770 if (symbolValues.end() != iter) {
6771 id = iter->second;
6772 return id;
6773 }
6774
6775 // it was not found, create it
6776 id = createSpvVariable(symbol);
6777 symbolValues[symbol->getId()] = id;
6778
Rex Xuc884b4a2016-06-29 15:03:44 +08006779 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006780 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6781 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6782 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006783 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006784 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006785 if (symbol->getQualifier().hasIndex())
6786 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6787 if (symbol->getQualifier().hasComponent())
6788 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006789 // atomic counters use this:
6790 if (symbol->getQualifier().hasOffset())
6791 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006792 }
6793
scygan2c864272016-05-18 18:09:17 +02006794 if (symbol->getQualifier().hasLocation())
6795 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006796 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006797 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006798 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006799 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006800 }
John Kessenich140f3df2015-06-26 16:58:36 -06006801 if (symbol->getQualifier().hasSet())
6802 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006803 else if (IsDescriptorResource(symbol->getType())) {
6804 // default to 0
6805 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6806 }
John Kessenich140f3df2015-06-26 16:58:36 -06006807 if (symbol->getQualifier().hasBinding())
6808 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006809 if (symbol->getQualifier().hasAttachment())
6810 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006811 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006812 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006813 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006814 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006815 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006816 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006817 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6818 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6819 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6820 }
6821 if (symbol->getQualifier().hasXfbOffset())
6822 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006823 }
6824
Rex Xu1da878f2016-02-21 20:59:01 +08006825 if (symbol->getType().isImage()) {
6826 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05006827 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08006828 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006829 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006830 }
6831
John Kessenich140f3df2015-06-26 16:58:36 -06006832 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006833 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006834 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006835 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006836
John Kessenich5611c6d2018-04-05 11:25:02 -06006837 // nonuniform
6838 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6839
John Kessenichecba76f2017-01-06 00:34:48 -07006840#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006841 if (builtIn == spv::BuiltInSampleMask) {
6842 spv::Decoration decoration;
6843 // GL_NV_sample_mask_override_coverage extension
6844 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006845 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006846 else
6847 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006848 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006849 if (decoration != spv::DecorationMax) {
6850 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6851 }
6852 }
chaoc771d89f2017-01-13 01:10:53 -08006853 else if (builtIn == spv::BuiltInLayer) {
6854 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006855 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006856 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006857 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6858 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6859 }
John Kessenichb41bff62017-08-11 13:07:17 -06006860 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006861 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6862 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6864 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6865 }
6866 }
6867
chaoc6e5acae2016-12-20 13:28:52 -08006868 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006869 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006870 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006871 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6872 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006873#endif
6874
John Kessenich5d610ee2018-03-07 18:05:55 -07006875 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6876 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6877 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6878 symbol->getType().getQualifier().semanticName);
6879 }
6880
John Kessenich140f3df2015-06-26 16:58:36 -06006881 return id;
6882}
6883
John Kessenich55e7d112015-11-15 21:33:39 -07006884// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006885// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006886//
6887// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6888//
6889// Recursively walk the nodes. The nodes form a tree whose leaves are
6890// regular constants, which themselves are trees that createSpvConstant()
6891// recursively walks. So, this function walks the "top" of the tree:
6892// - emit specialization constant-building instructions for specConstant
6893// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006894spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006895{
John Kessenich7cc0e282016-03-20 00:46:02 -06006896 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006897
qining4f4bb812016-04-03 23:55:17 -04006898 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006899 if (! node.getQualifier().specConstant) {
6900 // hand off to the non-spec-constant path
6901 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6902 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006903 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006904 nextConst, false);
6905 }
6906
6907 // We now know we have a specialization constant to build
6908
John Kessenichd94c0032016-05-30 19:29:40 -06006909 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006910 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6911 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6912 std::vector<spv::Id> dimConstId;
6913 for (int dim = 0; dim < 3; ++dim) {
6914 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6915 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006916 if (specConst) {
6917 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6918 glslangIntermediate->getLocalSizeSpecId(dim));
6919 }
qining4f4bb812016-04-03 23:55:17 -04006920 }
6921 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6922 }
6923
6924 // An AST node labelled as specialization constant should be a symbol node.
6925 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6926 if (auto* sn = node.getAsSymbolNode()) {
6927 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006928 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6929 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6930 // will set the builder into spec constant op instruction generating mode.
6931 sub_tree->traverse(this);
6932 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006933 } else if (auto* const_union_array = &sn->getConstArray()){
6934 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006935 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6936 builder.addName(id, sn->getName().c_str());
6937 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006938 }
6939 }
qining4f4bb812016-04-03 23:55:17 -04006940
6941 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6942 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006943 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006944 exit(1);
6945 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006946}
6947
John Kessenich140f3df2015-06-26 16:58:36 -06006948// Use 'consts' as the flattened glslang source of scalar constants to recursively
6949// build the aggregate SPIR-V constant.
6950//
6951// If there are not enough elements present in 'consts', 0 will be substituted;
6952// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6953//
qining08408382016-03-21 09:51:37 -04006954spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006955{
6956 // vector of constants for SPIR-V
6957 std::vector<spv::Id> spvConsts;
6958
6959 // Type is used for struct and array constants
6960 spv::Id typeId = convertGlslangToSpvType(glslangType);
6961
6962 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006963 glslang::TType elementType(glslangType, 0);
6964 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006965 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006966 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006967 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006968 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006969 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006970 } else if (glslangType.getStruct()) {
6971 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6972 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006973 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006974 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006975 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6976 bool zero = nextConst >= consts.size();
6977 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006978 case glslang::EbtInt8:
6979 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6980 break;
6981 case glslang::EbtUint8:
6982 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6983 break;
6984 case glslang::EbtInt16:
6985 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6986 break;
6987 case glslang::EbtUint16:
6988 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6989 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006990 case glslang::EbtInt:
6991 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6992 break;
6993 case glslang::EbtUint:
6994 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6995 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006996 case glslang::EbtInt64:
6997 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6998 break;
6999 case glslang::EbtUint64:
7000 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7001 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007002 case glslang::EbtFloat:
7003 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7004 break;
7005 case glslang::EbtDouble:
7006 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7007 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007008 case glslang::EbtFloat16:
7009 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7010 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007011 case glslang::EbtBool:
7012 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7013 break;
7014 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007015 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007016 break;
7017 }
7018 ++nextConst;
7019 }
7020 } else {
7021 // we have a non-aggregate (scalar) constant
7022 bool zero = nextConst >= consts.size();
7023 spv::Id scalar = 0;
7024 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007025 case glslang::EbtInt8:
7026 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7027 break;
7028 case glslang::EbtUint8:
7029 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7030 break;
7031 case glslang::EbtInt16:
7032 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7033 break;
7034 case glslang::EbtUint16:
7035 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7036 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007037 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007038 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007039 break;
7040 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007041 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007042 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007043 case glslang::EbtInt64:
7044 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7045 break;
7046 case glslang::EbtUint64:
7047 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7048 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007049 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007050 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007051 break;
7052 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007053 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007054 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007055 case glslang::EbtFloat16:
7056 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7057 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007058 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007059 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007060 break;
7061 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007062 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007063 break;
7064 }
7065 ++nextConst;
7066 return scalar;
7067 }
7068
7069 return builder.makeCompositeConstant(typeId, spvConsts);
7070}
7071
John Kessenich7c1aa102015-10-15 13:29:11 -06007072// Return true if the node is a constant or symbol whose reading has no
7073// non-trivial observable cost or effect.
7074bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7075{
7076 // don't know what this is
7077 if (node == nullptr)
7078 return false;
7079
7080 // a constant is safe
7081 if (node->getAsConstantUnion() != nullptr)
7082 return true;
7083
7084 // not a symbol means non-trivial
7085 if (node->getAsSymbolNode() == nullptr)
7086 return false;
7087
7088 // a symbol, depends on what's being read
7089 switch (node->getType().getQualifier().storage) {
7090 case glslang::EvqTemporary:
7091 case glslang::EvqGlobal:
7092 case glslang::EvqIn:
7093 case glslang::EvqInOut:
7094 case glslang::EvqConst:
7095 case glslang::EvqConstReadOnly:
7096 case glslang::EvqUniform:
7097 return true;
7098 default:
7099 return false;
7100 }
qining25262b32016-05-06 17:25:16 -04007101}
John Kessenich7c1aa102015-10-15 13:29:11 -06007102
7103// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007104// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007105// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007106// Return true if trivial.
7107bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7108{
7109 if (node == nullptr)
7110 return false;
7111
John Kessenich84cc15f2017-05-24 16:44:47 -06007112 // count non scalars as trivial, as well as anything coming from HLSL
7113 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007114 return true;
7115
John Kessenich7c1aa102015-10-15 13:29:11 -06007116 // symbols and constants are trivial
7117 if (isTrivialLeaf(node))
7118 return true;
7119
7120 // otherwise, it needs to be a simple operation or one or two leaf nodes
7121
7122 // not a simple operation
7123 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7124 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7125 if (binaryNode == nullptr && unaryNode == nullptr)
7126 return false;
7127
7128 // not on leaf nodes
7129 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7130 return false;
7131
7132 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7133 return false;
7134 }
7135
7136 switch (node->getAsOperator()->getOp()) {
7137 case glslang::EOpLogicalNot:
7138 case glslang::EOpConvIntToBool:
7139 case glslang::EOpConvUintToBool:
7140 case glslang::EOpConvFloatToBool:
7141 case glslang::EOpConvDoubleToBool:
7142 case glslang::EOpEqual:
7143 case glslang::EOpNotEqual:
7144 case glslang::EOpLessThan:
7145 case glslang::EOpGreaterThan:
7146 case glslang::EOpLessThanEqual:
7147 case glslang::EOpGreaterThanEqual:
7148 case glslang::EOpIndexDirect:
7149 case glslang::EOpIndexDirectStruct:
7150 case glslang::EOpLogicalXor:
7151 case glslang::EOpAny:
7152 case glslang::EOpAll:
7153 return true;
7154 default:
7155 return false;
7156 }
7157}
7158
7159// Emit short-circuiting code, where 'right' is never evaluated unless
7160// the left side is true (for &&) or false (for ||).
7161spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7162{
7163 spv::Id boolTypeId = builder.makeBoolType();
7164
7165 // emit left operand
7166 builder.clearAccessChain();
7167 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007168 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007169
7170 // Operands to accumulate OpPhi operands
7171 std::vector<spv::Id> phiOperands;
7172 // accumulate left operand's phi information
7173 phiOperands.push_back(leftId);
7174 phiOperands.push_back(builder.getBuildPoint()->getId());
7175
7176 // Make the two kinds of operation symmetric with a "!"
7177 // || => emit "if (! left) result = right"
7178 // && => emit "if ( left) result = right"
7179 //
7180 // TODO: this runtime "not" for || could be avoided by adding functionality
7181 // to 'builder' to have an "else" without an "then"
7182 if (op == glslang::EOpLogicalOr)
7183 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7184
7185 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007186 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007187
7188 // emit right operand as the "then" part of the "if"
7189 builder.clearAccessChain();
7190 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007191 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007192
7193 // accumulate left operand's phi information
7194 phiOperands.push_back(rightId);
7195 phiOperands.push_back(builder.getBuildPoint()->getId());
7196
7197 // finish the "if"
7198 ifBuilder.makeEndIf();
7199
7200 // phi together the two results
7201 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7202}
7203
Frank Henigman541f7bb2018-01-16 00:18:26 -05007204#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007205// Return type Id of the imported set of extended instructions corresponds to the name.
7206// Import this set if it has not been imported yet.
7207spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7208{
7209 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7210 return extBuiltinMap[name];
7211 else {
Rex Xu51596642016-09-21 18:56:12 +08007212 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007213 spv::Id extBuiltins = builder.import(name);
7214 extBuiltinMap[name] = extBuiltins;
7215 return extBuiltins;
7216 }
7217}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007218#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007219
John Kessenich140f3df2015-06-26 16:58:36 -06007220}; // end anonymous namespace
7221
7222namespace glslang {
7223
John Kessenich68d78fd2015-07-12 19:28:10 -06007224void GetSpirvVersion(std::string& version)
7225{
John Kessenich9e55f632015-07-15 10:03:39 -06007226 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007227 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007228 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007229 version = buf;
7230}
7231
John Kessenicha372a3e2017-11-02 22:32:14 -06007232// For low-order part of the generator's magic number. Bump up
7233// when there is a change in the style (e.g., if SSA form changes,
7234// or a different instruction sequence to do something gets used).
7235int GetSpirvGeneratorVersion()
7236{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007237 // return 1; // start
7238 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007239 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007240 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007241 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007242 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7243 // versions 4 and 6 each generate OpArrayLength as it has long been done
7244 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007245}
7246
John Kessenich140f3df2015-06-26 16:58:36 -06007247// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007248void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007249{
7250 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007251 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007252 if (out.fail())
7253 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007254 for (int i = 0; i < (int)spirv.size(); ++i) {
7255 unsigned int word = spirv[i];
7256 out.write((const char*)&word, 4);
7257 }
7258 out.close();
7259}
7260
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007261// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007262void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007263{
7264 std::ofstream out;
7265 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007266 if (out.fail())
7267 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007268 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007269 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007270 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007271 if (varName != nullptr) {
7272 out << "\t #pragma once" << std::endl;
7273 out << "const uint32_t " << varName << "[] = {" << std::endl;
7274 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007275 const int WORDS_PER_LINE = 8;
7276 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7277 out << "\t";
7278 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7279 const unsigned int word = spirv[i + j];
7280 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7281 if (i + j + 1 < (int)spirv.size()) {
7282 out << ",";
7283 }
7284 }
7285 out << std::endl;
7286 }
Flavio15017db2017-02-15 14:29:33 -08007287 if (varName != nullptr) {
7288 out << "};";
7289 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007290 out.close();
7291}
7292
John Kessenich140f3df2015-06-26 16:58:36 -06007293//
7294// Set up the glslang traversal
7295//
John Kessenich4e11b612018-08-30 16:56:59 -06007296void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007297{
Lei Zhang17535f72016-05-04 15:55:59 -04007298 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007299 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007300}
7301
John Kessenich4e11b612018-08-30 16:56:59 -06007302void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007303 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007304{
John Kessenich140f3df2015-06-26 16:58:36 -06007305 TIntermNode* root = intermediate.getTreeRoot();
7306
7307 if (root == 0)
7308 return;
7309
John Kessenich4e11b612018-08-30 16:56:59 -06007310 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007311 if (options == nullptr)
7312 options = &defaultOptions;
7313
John Kessenich4e11b612018-08-30 16:56:59 -06007314 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007315
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007316 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007317 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007318 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007319 it.dumpSpv(spirv);
7320
GregFfb03a552018-03-29 11:49:14 -06007321#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007322 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7323 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007324 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007325 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007326
John Kessenich4e11b612018-08-30 16:56:59 -06007327 if (options->validate)
7328 SpirvToolsValidate(intermediate, spirv, logger);
7329
John Kessenich717c80a2018-08-23 15:17:10 -06007330 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007331 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007332
GregFcd1f1692017-09-21 18:40:22 -06007333#endif
7334
John Kessenich4e11b612018-08-30 16:56:59 -06007335 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007336}
7337
7338}; // end namespace glslang