blob: 55b0ec6f2f6657aa740e79718a11c6618cb8e77b [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.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 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);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600150 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
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);
Chao Chen3c366992018-09-19 11:41:59 -0700197#ifdef NV_EXTENSIONS
198 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
199#endif
qining08408382016-03-21 09:51:37 -0400200 spv::Id createSpvConstant(const glslang::TIntermTyped&);
201 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600202 bool isTrivialLeaf(const glslang::TIntermTyped* node);
203 bool isTrivial(const glslang::TIntermTyped* node);
204 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800206 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700208 void addPre13Extension(const char* ext)
209 {
210 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
211 builder.addExtension(ext);
212 }
John Kessenich140f3df2015-06-26 16:58:36 -0600213
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600214 unsigned int getBufferReferenceAlignment(const glslang::TType &type) const {
215 if (type.getBasicType() == glslang::EbtReference) {
216 return type.getReferentType()->getQualifier().hasBufferReferenceAlign() ?
217 (1u << type.getReferentType()->getQualifier().layoutBufferReferenceAlign) : 16u;
218 } else {
219 return 0;
220 }
221 }
222
John Kessenich121853f2017-05-31 17:11:16 -0600223 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600224 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600225 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700226 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 int sequenceDepth;
228
Lei Zhang17535f72016-05-04 15:55:59 -0400229 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400230
John Kessenich140f3df2015-06-26 16:58:36 -0600231 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
232 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700233 bool inEntryPoint;
234 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700235 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 -0700236 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600237 const glslang::TIntermediate* glslangIntermediate;
238 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800239 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600240
John Kessenich2f273362015-07-18 22:34:27 -0600241 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600242 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600243 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700244 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700245 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
246 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600247 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700248 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600249 // Map pointee types for EbtReference to their forward pointers
250 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600251};
252
253//
254// Helper functions for translating glslang representations to SPIR-V enumerants.
255//
256
257// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700258spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600259{
John Kessenich66e2faf2016-03-12 18:34:36 -0700260 switch (source) {
261 case glslang::EShSourceGlsl:
262 switch (profile) {
263 case ENoProfile:
264 case ECoreProfile:
265 case ECompatibilityProfile:
266 return spv::SourceLanguageGLSL;
267 case EEsProfile:
268 return spv::SourceLanguageESSL;
269 default:
270 return spv::SourceLanguageUnknown;
271 }
272 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600273 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::SourceLanguageUnknown;
276 }
277}
278
279// Translate glslang language (stage) to SPIR-V execution model.
280spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
281{
282 switch (stage) {
283 case EShLangVertex: return spv::ExecutionModelVertex;
284 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
285 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
286 case EShLangGeometry: return spv::ExecutionModelGeometry;
287 case EShLangFragment: return spv::ExecutionModelFragment;
288 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700289#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700290 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
291 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
292 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
293 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
294 case EShLangMissNV: return spv::ExecutionModelMissNV;
295 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700296 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
297 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
298#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600299 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700300 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600301 return spv::ExecutionModelFragment;
302 }
303}
304
John Kessenich140f3df2015-06-26 16:58:36 -0600305// Translate glslang sampler type to SPIR-V dimensionality.
306spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
307{
308 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700309 case glslang::Esd1D: return spv::Dim1D;
310 case glslang::Esd2D: return spv::Dim2D;
311 case glslang::Esd3D: return spv::Dim3D;
312 case glslang::EsdCube: return spv::DimCube;
313 case glslang::EsdRect: return spv::DimRect;
314 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700315 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600316 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600318 return spv::Dim2D;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang precision to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600324{
John Kessenichf6640762016-08-01 19:44:00 -0600325 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700326 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600327 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 default:
329 return spv::NoPrecision;
330 }
331}
332
John Kessenichf6640762016-08-01 19:44:00 -0600333// Translate glslang type to SPIR-V precision decorations.
334spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
335{
336 return TranslatePrecisionDecoration(type.getQualifier().precision);
337}
338
John Kessenich140f3df2015-06-26 16:58:36 -0600339// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600340spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600341{
342 if (type.getBasicType() == glslang::EbtBlock) {
343 switch (type.getQualifier().storage) {
344 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600345 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 case glslang::EvqVaryingIn: return spv::DecorationBlock;
347 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700348#ifdef NV_EXTENSIONS
349 case glslang::EvqPayloadNV: return spv::DecorationBlock;
350 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
351 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700352 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
353 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700354#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600355 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700356 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600357 break;
358 }
359 }
360
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362}
363
Rex Xu1da878f2016-02-21 20:59:01 +0800364// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500365void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800366{
Jeff Bolz36831c92018-09-05 10:11:41 -0500367 if (!useVulkanMemoryModel) {
368 if (qualifier.coherent)
369 memory.push_back(spv::DecorationCoherent);
370 if (qualifier.volatil) {
371 memory.push_back(spv::DecorationVolatile);
372 memory.push_back(spv::DecorationCoherent);
373 }
John Kessenich14b85d32018-06-04 15:36:03 -0600374 }
Rex Xu1da878f2016-02-21 20:59:01 +0800375 if (qualifier.restrict)
376 memory.push_back(spv::DecorationRestrict);
377 if (qualifier.readonly)
378 memory.push_back(spv::DecorationNonWritable);
379 if (qualifier.writeonly)
380 memory.push_back(spv::DecorationNonReadable);
381}
382
John Kessenich140f3df2015-06-26 16:58:36 -0600383// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700384spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600385{
386 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700387 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600388 case glslang::ElmRowMajor:
389 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700390 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700392 default:
393 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600394 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 }
396 } else {
397 switch (type.getBasicType()) {
398 default:
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600400 break;
401 case glslang::EbtBlock:
402 switch (type.getQualifier().storage) {
403 case glslang::EvqUniform:
404 case glslang::EvqBuffer:
405 switch (type.getQualifier().layoutPacking) {
406 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
408 default:
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600410 }
411 case glslang::EvqVaryingIn:
412 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700413 if (type.getQualifier().isTaskMemory()) {
414 switch (type.getQualifier().layoutPacking) {
415 case glslang::ElpShared: return spv::DecorationGLSLShared;
416 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
417 default: break;
418 }
419 } else {
420 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
421 }
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700423#ifdef NV_EXTENSIONS
424 case glslang::EvqPayloadNV:
425 case glslang::EvqPayloadInNV:
426 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700427 case glslang::EvqCallableDataNV:
428 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700429 return spv::DecorationMax;
430#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600431 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700432 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600433 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600434 }
435 }
436 }
437}
438
439// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600440// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700441// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800442spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600443{
Rex Xubbceed72016-05-21 09:40:44 +0800444 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700445 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600446 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800447 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700448 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700449 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600450 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800451#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800452 else if (qualifier.explicitInterp) {
453 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800454 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800455 }
Rex Xu9d93a232016-05-05 12:30:44 +0800456#endif
Rex Xubbceed72016-05-21 09:40:44 +0800457 else
John Kessenich4016e382016-07-15 11:53:56 -0600458 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800459}
460
461// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600462// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800463// should be applied.
464spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
465{
466 if (qualifier.patch)
467 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700468 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600469 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700470 else if (qualifier.sample) {
471 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600472 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700473 } else
John Kessenich4016e382016-07-15 11:53:56 -0600474 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600475}
476
John Kessenich92187592016-02-01 13:45:25 -0700477// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700478spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600479{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700480 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600481 return spv::DecorationInvariant;
482 else
John Kessenich4016e382016-07-15 11:53:56 -0600483 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600484}
485
qining9220dbb2016-05-04 17:34:38 -0400486// If glslang type is noContraction, return SPIR-V NoContraction decoration.
487spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
488{
489 if (qualifier.noContraction)
490 return spv::DecorationNoContraction;
491 else
John Kessenich4016e382016-07-15 11:53:56 -0600492 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400493}
494
John Kessenich5611c6d2018-04-05 11:25:02 -0600495// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
496spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
497{
498 if (qualifier.isNonUniform()) {
499 builder.addExtension("SPV_EXT_descriptor_indexing");
500 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
501 return spv::DecorationNonUniformEXT;
502 } else
503 return spv::DecorationMax;
504}
505
Jeff Bolz36831c92018-09-05 10:11:41 -0500506spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
507{
508 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
509 return spv::MemoryAccessMaskNone;
510 }
511 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
512 if (coherentFlags.volatil ||
513 coherentFlags.coherent ||
514 coherentFlags.devicecoherent ||
515 coherentFlags.queuefamilycoherent ||
516 coherentFlags.workgroupcoherent ||
517 coherentFlags.subgroupcoherent) {
518 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
519 spv::MemoryAccessMakePointerVisibleKHRMask;
520 }
521 if (coherentFlags.nonprivate) {
522 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
523 }
524 if (coherentFlags.volatil) {
525 mask = mask | spv::MemoryAccessVolatileMask;
526 }
527 if (mask != spv::MemoryAccessMaskNone) {
528 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
529 }
530 return mask;
531}
532
533spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
534{
535 if (!glslangIntermediate->usingVulkanMemoryModel()) {
536 return spv::ImageOperandsMaskNone;
537 }
538 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
539 if (coherentFlags.volatil ||
540 coherentFlags.coherent ||
541 coherentFlags.devicecoherent ||
542 coherentFlags.queuefamilycoherent ||
543 coherentFlags.workgroupcoherent ||
544 coherentFlags.subgroupcoherent) {
545 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
546 spv::ImageOperandsMakeTexelVisibleKHRMask;
547 }
548 if (coherentFlags.nonprivate) {
549 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
550 }
551 if (coherentFlags.volatil) {
552 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
553 }
554 if (mask != spv::ImageOperandsMaskNone) {
555 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
556 }
557 return mask;
558}
559
560spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
561{
562 spv::Builder::AccessChain::CoherentFlags flags;
563 flags.coherent = type.getQualifier().coherent;
564 flags.devicecoherent = type.getQualifier().devicecoherent;
565 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
566 // shared variables are implicitly workgroupcoherent in GLSL.
567 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
568 type.getQualifier().storage == glslang::EvqShared;
569 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
570 // *coherent variables are implicitly nonprivate in GLSL
571 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500572 flags.subgroupcoherent ||
573 flags.workgroupcoherent ||
574 flags.queuefamilycoherent ||
575 flags.devicecoherent ||
576 flags.coherent;
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 flags.volatil = type.getQualifier().volatil;
578 flags.isImage = type.getBasicType() == glslang::EbtSampler;
579 return flags;
580}
581
582spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
583{
584 spv::Scope scope;
585 if (coherentFlags.coherent) {
586 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
587 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
588 } else if (coherentFlags.devicecoherent) {
589 scope = spv::ScopeDevice;
590 } else if (coherentFlags.queuefamilycoherent) {
591 scope = spv::ScopeQueueFamilyKHR;
592 } else if (coherentFlags.workgroupcoherent) {
593 scope = spv::ScopeWorkgroup;
594 } else if (coherentFlags.subgroupcoherent) {
595 scope = spv::ScopeSubgroup;
596 } else {
597 scope = spv::ScopeMax;
598 }
599 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
600 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
601 }
602 return scope;
603}
604
David Netoa901ffe2016-06-08 14:11:40 +0100605// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
606// associated capabilities when required. For some built-in variables, a capability
607// is generated only when using the variable in an executable instruction, but not when
608// just declaring a struct member variable with it. This is true for PointSize,
609// ClipDistance, and CullDistance.
610spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600611{
612 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700613 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600614 // Defer adding the capability until the built-in is actually used.
615 if (! memberDeclaration) {
616 switch (glslangIntermediate->getStage()) {
617 case EShLangGeometry:
618 builder.addCapability(spv::CapabilityGeometryPointSize);
619 break;
620 case EShLangTessControl:
621 case EShLangTessEvaluation:
622 builder.addCapability(spv::CapabilityTessellationPointSize);
623 break;
624 default:
625 break;
626 }
John Kessenich92187592016-02-01 13:45:25 -0700627 }
628 return spv::BuiltInPointSize;
629
John Kessenichebb50532016-05-16 19:22:05 -0600630 // These *Distance capabilities logically belong here, but if the member is declared and
631 // then never used, consumers of SPIR-V prefer the capability not be declared.
632 // They are now generated when used, rather than here when declared.
633 // Potentially, the specification should be more clear what the minimum
634 // use needed is to trigger the capability.
635 //
John Kessenich92187592016-02-01 13:45:25 -0700636 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100637 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800638 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700639 return spv::BuiltInClipDistance;
640
641 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100642 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800643 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700644 return spv::BuiltInCullDistance;
645
646 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600647 builder.addCapability(spv::CapabilityMultiViewport);
648 if (glslangIntermediate->getStage() == EShLangVertex ||
649 glslangIntermediate->getStage() == EShLangTessControl ||
650 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800651
John Kessenichba6a3c22017-09-13 13:22:50 -0600652 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
653 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800654 }
John Kessenich92187592016-02-01 13:45:25 -0700655 return spv::BuiltInViewportIndex;
656
John Kessenich5e801132016-02-15 11:09:46 -0700657 case glslang::EbvSampleId:
658 builder.addCapability(spv::CapabilitySampleRateShading);
659 return spv::BuiltInSampleId;
660
661 case glslang::EbvSamplePosition:
662 builder.addCapability(spv::CapabilitySampleRateShading);
663 return spv::BuiltInSamplePosition;
664
665 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700666 return spv::BuiltInSampleMask;
667
John Kessenich78a45572016-07-08 14:05:15 -0600668 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700669#ifdef NV_EXTENSIONS
670 if (glslangIntermediate->getStage() == EShLangMeshNV) {
671 return spv::BuiltInLayer;
672 }
673#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600674 builder.addCapability(spv::CapabilityGeometry);
675 if (glslangIntermediate->getStage() == EShLangVertex ||
676 glslangIntermediate->getStage() == EShLangTessControl ||
677 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800678
John Kessenichba6a3c22017-09-13 13:22:50 -0600679 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
680 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800681 }
John Kessenich78a45572016-07-08 14:05:15 -0600682 return spv::BuiltInLayer;
683
John Kessenich140f3df2015-06-26 16:58:36 -0600684 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600685 case glslang::EbvVertexId: return spv::BuiltInVertexId;
686 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700687 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
688 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInBaseVertex;
694
John Kessenichda581a22015-10-14 14:10:30 -0600695 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700696 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800697 builder.addCapability(spv::CapabilityDrawParameters);
698 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200699
John Kessenichda581a22015-10-14 14:10:30 -0600700 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700701 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800702 builder.addCapability(spv::CapabilityDrawParameters);
703 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200704
705 case glslang::EbvPrimitiveId:
706 if (glslangIntermediate->getStage() == EShLangFragment)
707 builder.addCapability(spv::CapabilityGeometry);
708 return spv::BuiltInPrimitiveId;
709
Rex Xu37cdcee2017-06-29 17:46:34 +0800710 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800711 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
712 builder.addCapability(spv::CapabilityStencilExportEXT);
713 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800714
John Kessenich140f3df2015-06-26 16:58:36 -0600715 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600716 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
717 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
718 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
719 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
720 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
721 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
722 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600723 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
724 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
725 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
726 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
727 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
728 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
729 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
730 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupSize;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupLocalInvocationId;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupEqMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupGeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupGtMaskKHR;
756
Rex Xu574ab042016-04-14 16:53:07 +0800757 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800758 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
759 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
760 return spv::BuiltInSubgroupLeMaskKHR;
761
Rex Xu574ab042016-04-14 16:53:07 +0800762 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800763 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
764 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
765 return spv::BuiltInSubgroupLtMaskKHR;
766
John Kessenich66011cb2018-03-06 16:12:04 -0700767 case glslang::EbvNumSubgroups:
768 builder.addCapability(spv::CapabilityGroupNonUniform);
769 return spv::BuiltInNumSubgroups;
770
771 case glslang::EbvSubgroupID:
772 builder.addCapability(spv::CapabilityGroupNonUniform);
773 return spv::BuiltInSubgroupId;
774
775 case glslang::EbvSubgroupSize2:
776 builder.addCapability(spv::CapabilityGroupNonUniform);
777 return spv::BuiltInSubgroupSize;
778
779 case glslang::EbvSubgroupInvocation2:
780 builder.addCapability(spv::CapabilityGroupNonUniform);
781 return spv::BuiltInSubgroupLocalInvocationId;
782
783 case glslang::EbvSubgroupEqMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupEqMask;
787
788 case glslang::EbvSubgroupGeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupGeMask;
792
793 case glslang::EbvSubgroupGtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupGtMask;
797
798 case glslang::EbvSubgroupLeMask2:
799 builder.addCapability(spv::CapabilityGroupNonUniform);
800 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
801 return spv::BuiltInSubgroupLeMask;
802
803 case glslang::EbvSubgroupLtMask2:
804 builder.addCapability(spv::CapabilityGroupNonUniform);
805 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
806 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800807#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800808 case glslang::EbvBaryCoordNoPersp:
809 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
810 return spv::BuiltInBaryCoordNoPerspAMD;
811
812 case glslang::EbvBaryCoordNoPerspCentroid:
813 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
814 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
815
816 case glslang::EbvBaryCoordNoPerspSample:
817 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
818 return spv::BuiltInBaryCoordNoPerspSampleAMD;
819
820 case glslang::EbvBaryCoordSmooth:
821 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
822 return spv::BuiltInBaryCoordSmoothAMD;
823
824 case glslang::EbvBaryCoordSmoothCentroid:
825 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
826 return spv::BuiltInBaryCoordSmoothCentroidAMD;
827
828 case glslang::EbvBaryCoordSmoothSample:
829 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
830 return spv::BuiltInBaryCoordSmoothSampleAMD;
831
832 case glslang::EbvBaryCoordPullModel:
833 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
834 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800835#endif
chaoc771d89f2017-01-13 01:10:53 -0800836
John Kessenich6c8aaac2017-02-27 01:20:51 -0700837 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700838 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700839 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700840 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700841
842 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700843 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700844 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700845 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700846
Daniel Koch5154db52018-11-26 10:01:58 -0500847 case glslang::EbvFragSizeEXT:
848 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
849 builder.addCapability(spv::CapabilityFragmentDensityEXT);
850 return spv::BuiltInFragSizeEXT;
851
852 case glslang::EbvFragInvocationCountEXT:
853 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
854 builder.addCapability(spv::CapabilityFragmentDensityEXT);
855 return spv::BuiltInFragInvocationCountEXT;
856
chaoc771d89f2017-01-13 01:10:53 -0800857#ifdef NV_EXTENSIONS
858 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800859 if (!memberDeclaration) {
860 builder.addExtension(spv::E_SPV_NV_viewport_array2);
861 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
862 }
chaoc771d89f2017-01-13 01:10:53 -0800863 return spv::BuiltInViewportMaskNV;
864 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800865 if (!memberDeclaration) {
866 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
867 builder.addCapability(spv::CapabilityShaderStereoViewNV);
868 }
chaoc771d89f2017-01-13 01:10:53 -0800869 return spv::BuiltInSecondaryPositionNV;
870 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800871 if (!memberDeclaration) {
872 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
873 builder.addCapability(spv::CapabilityShaderStereoViewNV);
874 }
chaoc771d89f2017-01-13 01:10:53 -0800875 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800876 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800877 if (!memberDeclaration) {
878 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
879 builder.addCapability(spv::CapabilityPerViewAttributesNV);
880 }
chaocdf3956c2017-02-14 14:52:34 -0800881 return spv::BuiltInPositionPerViewNV;
882 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800883 if (!memberDeclaration) {
884 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
885 builder.addCapability(spv::CapabilityPerViewAttributesNV);
886 }
chaocdf3956c2017-02-14 14:52:34 -0800887 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700888 case glslang::EbvFragFullyCoveredNV:
889 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
890 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
891 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700892 case glslang::EbvFragmentSizeNV:
893 builder.addExtension(spv::E_SPV_NV_shading_rate);
894 builder.addCapability(spv::CapabilityShadingRateNV);
895 return spv::BuiltInFragmentSizeNV;
896 case glslang::EbvInvocationsPerPixelNV:
897 builder.addExtension(spv::E_SPV_NV_shading_rate);
898 builder.addCapability(spv::CapabilityShadingRateNV);
899 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900
901 // raytracing
902 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700918 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700919 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700920 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700921 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700922 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700923 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700924 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700925 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700926 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700927 return spv::BuiltInWorldToObjectNV;
928 case glslang::EbvIncomingRayFlagsNV:
929 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700930 case glslang::EbvBaryCoordNV:
931 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
932 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
933 return spv::BuiltInBaryCoordNV;
934 case glslang::EbvBaryCoordNoPerspNV:
935 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
936 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
937 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700938 case glslang::EbvTaskCountNV:
939 return spv::BuiltInTaskCountNV;
940 case glslang::EbvPrimitiveCountNV:
941 return spv::BuiltInPrimitiveCountNV;
942 case glslang::EbvPrimitiveIndicesNV:
943 return spv::BuiltInPrimitiveIndicesNV;
944 case glslang::EbvClipDistancePerViewNV:
945 return spv::BuiltInClipDistancePerViewNV;
946 case glslang::EbvCullDistancePerViewNV:
947 return spv::BuiltInCullDistancePerViewNV;
948 case glslang::EbvLayerPerViewNV:
949 return spv::BuiltInLayerPerViewNV;
950 case glslang::EbvMeshViewCountNV:
951 return spv::BuiltInMeshViewCountNV;
952 case glslang::EbvMeshViewIndicesNV:
953 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800954#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800955 default:
956 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600957 }
958}
959
Rex Xufc618912015-09-09 16:42:49 +0800960// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700961spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800962{
963 assert(type.getBasicType() == glslang::EbtSampler);
964
John Kessenich5d0fa972016-02-15 11:57:00 -0700965 // Check for capabilities
966 switch (type.getQualifier().layoutFormat) {
967 case glslang::ElfRg32f:
968 case glslang::ElfRg16f:
969 case glslang::ElfR11fG11fB10f:
970 case glslang::ElfR16f:
971 case glslang::ElfRgba16:
972 case glslang::ElfRgb10A2:
973 case glslang::ElfRg16:
974 case glslang::ElfRg8:
975 case glslang::ElfR16:
976 case glslang::ElfR8:
977 case glslang::ElfRgba16Snorm:
978 case glslang::ElfRg16Snorm:
979 case glslang::ElfRg8Snorm:
980 case glslang::ElfR16Snorm:
981 case glslang::ElfR8Snorm:
982
983 case glslang::ElfRg32i:
984 case glslang::ElfRg16i:
985 case glslang::ElfRg8i:
986 case glslang::ElfR16i:
987 case glslang::ElfR8i:
988
989 case glslang::ElfRgb10a2ui:
990 case glslang::ElfRg32ui:
991 case glslang::ElfRg16ui:
992 case glslang::ElfRg8ui:
993 case glslang::ElfR16ui:
994 case glslang::ElfR8ui:
995 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
996 break;
997
998 default:
999 break;
1000 }
1001
1002 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001003 switch (type.getQualifier().layoutFormat) {
1004 case glslang::ElfNone: return spv::ImageFormatUnknown;
1005 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1006 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1007 case glslang::ElfR32f: return spv::ImageFormatR32f;
1008 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1009 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1010 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1011 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1012 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1013 case glslang::ElfR16f: return spv::ImageFormatR16f;
1014 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1015 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1016 case glslang::ElfRg16: return spv::ImageFormatRg16;
1017 case glslang::ElfRg8: return spv::ImageFormatRg8;
1018 case glslang::ElfR16: return spv::ImageFormatR16;
1019 case glslang::ElfR8: return spv::ImageFormatR8;
1020 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1021 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1022 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1023 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1024 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1025 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1026 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1027 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1028 case glslang::ElfR32i: return spv::ImageFormatR32i;
1029 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1030 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1031 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1032 case glslang::ElfR16i: return spv::ImageFormatR16i;
1033 case glslang::ElfR8i: return spv::ImageFormatR8i;
1034 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1035 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1036 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1037 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1038 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1039 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1040 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1041 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1042 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1043 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001044 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001045 }
1046}
1047
John Kesseniche18fd202018-01-30 11:01:39 -07001048spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001049{
John Kesseniche18fd202018-01-30 11:01:39 -07001050 if (selectionNode.getFlatten())
1051 return spv::SelectionControlFlattenMask;
1052 if (selectionNode.getDontFlatten())
1053 return spv::SelectionControlDontFlattenMask;
1054 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001055}
1056
John Kesseniche18fd202018-01-30 11:01:39 -07001057spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001058{
John Kesseniche18fd202018-01-30 11:01:39 -07001059 if (switchNode.getFlatten())
1060 return spv::SelectionControlFlattenMask;
1061 if (switchNode.getDontFlatten())
1062 return spv::SelectionControlDontFlattenMask;
1063 return spv::SelectionControlMaskNone;
1064}
1065
John Kessenicha2858d92018-01-31 08:11:18 -07001066// return a non-0 dependency if the dependency argument must be set
1067spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1068 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001069{
1070 spv::LoopControlMask control = spv::LoopControlMaskNone;
1071
1072 if (loopNode.getDontUnroll())
1073 control = control | spv::LoopControlDontUnrollMask;
1074 if (loopNode.getUnroll())
1075 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001076 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001077 control = control | spv::LoopControlDependencyInfiniteMask;
1078 else if (loopNode.getLoopDependency() > 0) {
1079 control = control | spv::LoopControlDependencyLengthMask;
1080 dependencyLength = loopNode.getLoopDependency();
1081 }
John Kesseniche18fd202018-01-30 11:01:39 -07001082
1083 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001084}
1085
John Kessenicha5c5fb62017-05-05 05:09:58 -06001086// Translate glslang type to SPIR-V storage class.
1087spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1088{
1089 if (type.getQualifier().isPipeInput())
1090 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001091 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001092 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001093
1094 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1095 type.getQualifier().storage == glslang::EvqUniform) {
1096 if (type.getBasicType() == glslang::EbtAtomicUint)
1097 return spv::StorageClassAtomicCounter;
1098 if (type.containsOpaque())
1099 return spv::StorageClassUniformConstant;
1100 }
1101
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001102#ifdef NV_EXTENSIONS
1103 if (type.getQualifier().isUniformOrBuffer() &&
1104 type.getQualifier().layoutShaderRecordNV) {
1105 return spv::StorageClassShaderRecordBufferNV;
1106 }
1107#endif
1108
John Kessenichbed4e4f2017-09-08 02:38:07 -06001109 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001110 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001111 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001112 }
1113
1114 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001115 if (type.getQualifier().layoutPushConstant)
1116 return spv::StorageClassPushConstant;
1117 if (type.getBasicType() == glslang::EbtBlock)
1118 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001119 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001120 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001121
1122 switch (type.getQualifier().storage) {
1123 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1124 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1125 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1126 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001127#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001128 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1129 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1130 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1131 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1132 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001133#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001134 default:
1135 assert(0);
1136 break;
1137 }
1138
1139 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001140}
1141
John Kessenich5611c6d2018-04-05 11:25:02 -06001142// Add capabilities pertaining to how an array is indexed.
1143void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1144 const glslang::TType& indexType)
1145{
1146 if (indexType.getQualifier().isNonUniform()) {
1147 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001148 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001149 if (baseType.getBasicType() == glslang::EbtSampler) {
1150 if (baseType.getQualifier().hasAttachment())
1151 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1152 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1153 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1154 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1155 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1156 else if (baseType.isImage())
1157 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1158 else if (baseType.isTexture())
1159 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1160 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1161 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1162 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1163 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1164 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1165 }
1166 } else {
1167 // assume a dynamically uniform index
1168 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001169 if (baseType.getQualifier().hasAttachment()) {
1170 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001171 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001172 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1173 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001174 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001175 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1176 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001177 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001178 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001179 }
1180 }
1181}
1182
qining25262b32016-05-06 17:25:16 -04001183// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001184// descriptor set.
1185bool IsDescriptorResource(const glslang::TType& type)
1186{
John Kessenichf7497e22016-03-08 21:36:22 -07001187 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001188 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001189 return type.getQualifier().isUniformOrBuffer() &&
1190#ifdef NV_EXTENSIONS
1191 ! type.getQualifier().layoutShaderRecordNV &&
1192#endif
1193 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001194
1195 // non block...
1196 // basically samplerXXX/subpass/sampler/texture are all included
1197 // if they are the global-scope-class, not the function parameter
1198 // (or local, if they ever exist) class.
1199 if (type.getBasicType() == glslang::EbtSampler)
1200 return type.getQualifier().isUniformOrBuffer();
1201
1202 // None of the above.
1203 return false;
1204}
1205
John Kesseniche0b6cad2015-12-24 10:30:13 -07001206void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1207{
1208 if (child.layoutMatrix == glslang::ElmNone)
1209 child.layoutMatrix = parent.layoutMatrix;
1210
1211 if (parent.invariant)
1212 child.invariant = true;
1213 if (parent.nopersp)
1214 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001215#ifdef AMD_EXTENSIONS
1216 if (parent.explicitInterp)
1217 child.explicitInterp = true;
1218#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001219 if (parent.flat)
1220 child.flat = true;
1221 if (parent.centroid)
1222 child.centroid = true;
1223 if (parent.patch)
1224 child.patch = true;
1225 if (parent.sample)
1226 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001227 if (parent.coherent)
1228 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001229 if (parent.devicecoherent)
1230 child.devicecoherent = true;
1231 if (parent.queuefamilycoherent)
1232 child.queuefamilycoherent = true;
1233 if (parent.workgroupcoherent)
1234 child.workgroupcoherent = true;
1235 if (parent.subgroupcoherent)
1236 child.subgroupcoherent = true;
1237 if (parent.nonprivate)
1238 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001239 if (parent.volatil)
1240 child.volatil = true;
1241 if (parent.restrict)
1242 child.restrict = true;
1243 if (parent.readonly)
1244 child.readonly = true;
1245 if (parent.writeonly)
1246 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001247#ifdef NV_EXTENSIONS
1248 if (parent.perPrimitiveNV)
1249 child.perPrimitiveNV = true;
1250 if (parent.perViewNV)
1251 child.perViewNV = true;
1252 if (parent.perTaskNV)
1253 child.perTaskNV = true;
1254#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001255}
1256
John Kessenichf2b7f332016-09-01 17:05:23 -06001257bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001258{
John Kessenich7b9fa252016-01-21 18:56:57 -07001259 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001260 // - struct members might inherit from a struct declaration
1261 // (note that non-block structs don't explicitly inherit,
1262 // only implicitly, meaning no decoration involved)
1263 // - affect decorations on the struct members
1264 // (note smooth does not, and expecting something like volatile
1265 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001266 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001267 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001268}
1269
John Kessenich140f3df2015-06-26 16:58:36 -06001270//
1271// Implement the TGlslangToSpvTraverser class.
1272//
1273
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001274TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001275 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1276 : TIntermTraverser(true, false, true),
1277 options(options),
1278 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001279 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001280 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001281 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001282 glslangIntermediate(glslangIntermediate)
1283{
1284 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1285
1286 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001287 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1288 glslangIntermediate->getVersion());
1289
John Kessenich121853f2017-05-31 17:11:16 -06001290 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001291 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001292 builder.setSourceFile(glslangIntermediate->getSourceFile());
1293
1294 // Set the source shader's text. If for SPV version 1.0, include
1295 // a preamble in comments stating the OpModuleProcessed instructions.
1296 // Otherwise, emit those as actual instructions.
1297 std::string text;
1298 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1299 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001300 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001301 text.append("// OpModuleProcessed ");
1302 text.append(processes[p]);
1303 text.append("\n");
1304 } else
1305 builder.addModuleProcessed(processes[p]);
1306 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001307 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001308 text.append("#line 1\n");
1309 text.append(glslangIntermediate->getSourceText());
1310 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001311 // Pass name and text for all included files
1312 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1313 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1314 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001315 }
John Kessenich140f3df2015-06-26 16:58:36 -06001316 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001317
1318 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1319 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1320
1321 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1322 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1323 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1324 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1325 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001326 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001327 memoryModel = spv::MemoryModelVulkanKHR;
1328 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001329 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001331 builder.setMemoryModel(addressingModel, memoryModel);
1332
John Kessenicheee9d532016-09-19 18:09:30 -06001333 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1334 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001335
1336 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001337 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1338 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001339 builder.addSourceExtension(it->c_str());
1340
1341 // Add the top-level modes for this shader.
1342
John Kessenich92187592016-02-01 13:45:25 -07001343 if (glslangIntermediate->getXfbMode()) {
1344 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001345 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001346 }
John Kessenich140f3df2015-06-26 16:58:36 -06001347
1348 unsigned int mode;
1349 switch (glslangIntermediate->getStage()) {
1350 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001351 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001352 break;
1353
steve-lunarge7412492017-03-23 11:56:07 -06001354 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001355 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001356 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001357
steve-lunarge7412492017-03-23 11:56:07 -06001358 glslang::TLayoutGeometry primitive;
1359
1360 if (glslangIntermediate->getStage() == EShLangTessControl) {
1361 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1362 primitive = glslangIntermediate->getOutputPrimitive();
1363 } else {
1364 primitive = glslangIntermediate->getInputPrimitive();
1365 }
1366
1367 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001368 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1369 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1370 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001371 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001372 }
John Kessenich4016e382016-07-15 11:53:56 -06001373 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001374 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1375
John Kesseniche6903322015-10-13 16:29:02 -06001376 switch (glslangIntermediate->getVertexSpacing()) {
1377 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1378 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1379 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001380 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001381 }
John Kessenich4016e382016-07-15 11:53:56 -06001382 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001383 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1384
1385 switch (glslangIntermediate->getVertexOrder()) {
1386 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1387 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001388 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001389 }
John Kessenich4016e382016-07-15 11:53:56 -06001390 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001391 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1392
1393 if (glslangIntermediate->getPointMode())
1394 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001395 break;
1396
1397 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001398 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001399 switch (glslangIntermediate->getInputPrimitive()) {
1400 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1401 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1402 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001403 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001404 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001405 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001406 }
John Kessenich4016e382016-07-15 11:53:56 -06001407 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001408 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001409
John Kessenich140f3df2015-06-26 16:58:36 -06001410 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1411
1412 switch (glslangIntermediate->getOutputPrimitive()) {
1413 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1414 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1415 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001416 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001417 }
John Kessenich4016e382016-07-15 11:53:56 -06001418 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001419 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1420 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1421 break;
1422
1423 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001424 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001425 if (glslangIntermediate->getPixelCenterInteger())
1426 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001427
John Kessenich140f3df2015-06-26 16:58:36 -06001428 if (glslangIntermediate->getOriginUpperLeft())
1429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001430 else
1431 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001432
1433 if (glslangIntermediate->getEarlyFragmentTests())
1434 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1435
chaocc1204522017-06-30 17:14:30 -07001436 if (glslangIntermediate->getPostDepthCoverage()) {
1437 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1438 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1439 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1440 }
1441
John Kesseniche6903322015-10-13 16:29:02 -06001442 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001443 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1444 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001445 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001446 }
John Kessenich4016e382016-07-15 11:53:56 -06001447 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001448 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1449
1450 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1451 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001452 break;
1453
1454 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001455 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001456 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1457 glslangIntermediate->getLocalSize(1),
1458 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001459#ifdef NV_EXTENSIONS
1460 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1461 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1462 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1463 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1464 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1465 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1466 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1467 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1468 }
1469#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001470 break;
1471
Chao Chen3c366992018-09-19 11:41:59 -07001472#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001473 case EShLangRayGenNV:
1474 case EShLangIntersectNV:
1475 case EShLangAnyHitNV:
1476 case EShLangClosestHitNV:
1477 case EShLangMissNV:
1478 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001479 builder.addCapability(spv::CapabilityRayTracingNV);
1480 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001481 break;
Chao Chen3c366992018-09-19 11:41:59 -07001482 case EShLangTaskNV:
1483 case EShLangMeshNV:
1484 builder.addCapability(spv::CapabilityMeshShadingNV);
1485 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1486 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1487 glslangIntermediate->getLocalSize(1),
1488 glslangIntermediate->getLocalSize(2));
1489 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1490 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1491 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1492
1493 switch (glslangIntermediate->getOutputPrimitive()) {
1494 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1495 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1496 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1497 default: mode = spv::ExecutionModeMax; break;
1498 }
1499 if (mode != spv::ExecutionModeMax)
1500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1501 }
1502 break;
1503#endif
1504
John Kessenich140f3df2015-06-26 16:58:36 -06001505 default:
1506 break;
1507 }
John Kessenich140f3df2015-06-26 16:58:36 -06001508}
1509
John Kessenichfca82622016-11-26 13:23:20 -07001510// Finish creating SPV, after the traversal is complete.
1511void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001512{
John Kessenichf04c51b2018-08-03 15:56:12 -06001513 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001514 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001515 builder.setBuildPoint(shaderEntry->getLastBlock());
1516 builder.leaveFunction();
1517 }
1518
John Kessenich7ba63412015-12-20 17:37:07 -07001519 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001520 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1521 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001522
John Kessenichf04c51b2018-08-03 15:56:12 -06001523 // Add capabilities, extensions, remove unneeded decorations, etc.,
1524 // based on the resulting SPIR-V.
1525 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001526}
1527
John Kessenichfca82622016-11-26 13:23:20 -07001528// Write the SPV into 'out'.
1529void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001530{
John Kessenichfca82622016-11-26 13:23:20 -07001531 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001532}
1533
1534//
1535// Implement the traversal functions.
1536//
1537// Return true from interior nodes to have the external traversal
1538// continue on to children. Return false if children were
1539// already processed.
1540//
1541
1542//
qining25262b32016-05-06 17:25:16 -04001543// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001544// - uniform/input reads
1545// - output writes
1546// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1547// - something simple that degenerates into the last bullet
1548//
1549void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1550{
qining75d1d802016-04-06 14:42:01 -04001551 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1552 if (symbol->getType().getQualifier().isSpecConstant())
1553 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1554
John Kessenich140f3df2015-06-26 16:58:36 -06001555 // getSymbolId() will set up all the IO decorations on the first call.
1556 // Formal function parameters were mapped during makeFunctions().
1557 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001558
1559 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1560 if (builder.isPointer(id)) {
1561 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001562 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1563 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1564 iOSet.insert(id);
1565 }
John Kessenich7ba63412015-12-20 17:37:07 -07001566 }
1567
1568 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001569 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001570 // Prepare to generate code for the access
1571
1572 // L-value chains will be computed left to right. We're on the symbol now,
1573 // which is the left-most part of the access chain, so now is "clear" time,
1574 // followed by setting the base.
1575 builder.clearAccessChain();
1576
1577 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001578 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001579 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001580 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001581 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001582 // These are also pure R-values.
1583 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001584 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001585 builder.setAccessChainRValue(id);
1586 else
1587 builder.setAccessChainLValue(id);
1588 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001589
1590 // Process linkage-only nodes for any special additional interface work.
1591 if (linkageOnly) {
1592 if (glslangIntermediate->getHlslFunctionality1()) {
1593 // Map implicit counter buffers to their originating buffers, which should have been
1594 // seen by now, given earlier pruning of unused counters, and preservation of order
1595 // of declaration.
1596 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1597 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1598 // Save possible originating buffers for counter buffers, keyed by
1599 // making the potential counter-buffer name.
1600 std::string keyName = symbol->getName().c_str();
1601 keyName = glslangIntermediate->addCounterBufferName(keyName);
1602 counterOriginator[keyName] = symbol;
1603 } else {
1604 // Handle a counter buffer, by finding the saved originating buffer.
1605 std::string keyName = symbol->getName().c_str();
1606 auto it = counterOriginator.find(keyName);
1607 if (it != counterOriginator.end()) {
1608 id = getSymbolId(it->second);
1609 if (id != spv::NoResult) {
1610 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001611 if (counterId != spv::NoResult) {
1612 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001613 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001614 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001615 }
1616 }
1617 }
1618 }
1619 }
1620 }
John Kessenich140f3df2015-06-26 16:58:36 -06001621}
1622
1623bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1624{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001625 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001626
qining40887662016-04-03 22:20:42 -04001627 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1628 if (node->getType().getQualifier().isSpecConstant())
1629 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1630
John Kessenich140f3df2015-06-26 16:58:36 -06001631 // First, handle special cases
1632 switch (node->getOp()) {
1633 case glslang::EOpAssign:
1634 case glslang::EOpAddAssign:
1635 case glslang::EOpSubAssign:
1636 case glslang::EOpMulAssign:
1637 case glslang::EOpVectorTimesMatrixAssign:
1638 case glslang::EOpVectorTimesScalarAssign:
1639 case glslang::EOpMatrixTimesScalarAssign:
1640 case glslang::EOpMatrixTimesMatrixAssign:
1641 case glslang::EOpDivAssign:
1642 case glslang::EOpModAssign:
1643 case glslang::EOpAndAssign:
1644 case glslang::EOpInclusiveOrAssign:
1645 case glslang::EOpExclusiveOrAssign:
1646 case glslang::EOpLeftShiftAssign:
1647 case glslang::EOpRightShiftAssign:
1648 // A bin-op assign "a += b" means the same thing as "a = a + b"
1649 // where a is evaluated before b. For a simple assignment, GLSL
1650 // says to evaluate the left before the right. So, always, left
1651 // node then right node.
1652 {
1653 // get the left l-value, save it away
1654 builder.clearAccessChain();
1655 node->getLeft()->traverse(this);
1656 spv::Builder::AccessChain lValue = builder.getAccessChain();
1657
1658 // evaluate the right
1659 builder.clearAccessChain();
1660 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001661 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001662
1663 if (node->getOp() != glslang::EOpAssign) {
1664 // the left is also an r-value
1665 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001666 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001667
1668 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001669 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001670 TranslateNoContractionDecoration(node->getType().getQualifier()),
1671 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001672 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001673 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1674 node->getType().getBasicType());
1675
1676 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001677 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001678 }
1679
1680 // store the result
1681 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001682 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001683
1684 // assignments are expressions having an rValue after they are evaluated...
1685 builder.clearAccessChain();
1686 builder.setAccessChainRValue(rValue);
1687 }
1688 return false;
1689 case glslang::EOpIndexDirect:
1690 case glslang::EOpIndexDirectStruct:
1691 {
1692 // Get the left part of the access chain.
1693 node->getLeft()->traverse(this);
1694
1695 // Add the next element in the chain
1696
David Netoa901ffe2016-06-08 14:11:40 +01001697 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001698 if (! node->getLeft()->getType().isArray() &&
1699 node->getLeft()->getType().isVector() &&
1700 node->getOp() == glslang::EOpIndexDirect) {
1701 // This is essentially a hard-coded vector swizzle of size 1,
1702 // so short circuit the access-chain stuff with a swizzle.
1703 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001704 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001705 int dummySize;
1706 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1707 TranslateCoherent(node->getLeft()->getType()),
1708 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001709 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001710
1711 // Load through a block reference is performed with a dot operator that
1712 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1713 // do a load and reset the access chain.
1714 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1715 !node->getLeft()->getType().isArray() &&
1716 node->getOp() == glslang::EOpIndexDirectStruct)
1717 {
1718 spv::Id left = accessChainLoad(node->getLeft()->getType());
1719 builder.clearAccessChain();
1720 builder.setAccessChainLValue(left);
1721 }
1722
David Netoa901ffe2016-06-08 14:11:40 +01001723 int spvIndex = glslangIndex;
1724 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1725 node->getOp() == glslang::EOpIndexDirectStruct)
1726 {
1727 // This may be, e.g., an anonymous block-member selection, which generally need
1728 // index remapping due to hidden members in anonymous blocks.
1729 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1730 assert(remapper.size() > 0);
1731 spvIndex = remapper[glslangIndex];
1732 }
John Kessenichebb50532016-05-16 19:22:05 -06001733
David Netoa901ffe2016-06-08 14:11:40 +01001734 // normal case for indexing array or structure or block
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001735 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001736
1737 // Add capabilities here for accessing PointSize and clip/cull distance.
1738 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001739 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001740 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001741 }
1742 }
1743 return false;
1744 case glslang::EOpIndexIndirect:
1745 {
1746 // Structure or array or vector indirection.
1747 // Will use native SPIR-V access-chain for struct and array indirection;
1748 // matrices are arrays of vectors, so will also work for a matrix.
1749 // Will use the access chain's 'component' for variable index into a vector.
1750
1751 // This adapter is building access chains left to right.
1752 // Set up the access chain to the left.
1753 node->getLeft()->traverse(this);
1754
1755 // save it so that computing the right side doesn't trash it
1756 spv::Builder::AccessChain partial = builder.getAccessChain();
1757
1758 // compute the next index in the chain
1759 builder.clearAccessChain();
1760 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001761 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001762
John Kessenich5611c6d2018-04-05 11:25:02 -06001763 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1764
John Kessenich140f3df2015-06-26 16:58:36 -06001765 // restore the saved access chain
1766 builder.setAccessChain(partial);
1767
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001768 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1769 int dummySize;
1770 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1771 TranslateCoherent(node->getLeft()->getType()),
1772 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1773 } else
1774 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001775 }
1776 return false;
1777 case glslang::EOpVectorSwizzle:
1778 {
1779 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001780 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001781 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001782 int dummySize;
1783 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1784 TranslateCoherent(node->getLeft()->getType()),
1785 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001786 }
1787 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001788 case glslang::EOpMatrixSwizzle:
1789 logger->missingFunctionality("matrix swizzle");
1790 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001791 case glslang::EOpLogicalOr:
1792 case glslang::EOpLogicalAnd:
1793 {
1794
1795 // These may require short circuiting, but can sometimes be done as straight
1796 // binary operations. The right operand must be short circuited if it has
1797 // side effects, and should probably be if it is complex.
1798 if (isTrivial(node->getRight()->getAsTyped()))
1799 break; // handle below as a normal binary operation
1800 // otherwise, we need to do dynamic short circuiting on the right operand
1801 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1802 builder.clearAccessChain();
1803 builder.setAccessChainRValue(result);
1804 }
1805 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001806 default:
1807 break;
1808 }
1809
1810 // Assume generic binary op...
1811
John Kessenich32cfd492016-02-02 12:37:46 -07001812 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001813 builder.clearAccessChain();
1814 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001815 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001816
John Kessenich32cfd492016-02-02 12:37:46 -07001817 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001818 builder.clearAccessChain();
1819 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001820 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001821
John Kessenich32cfd492016-02-02 12:37:46 -07001822 // get result
John Kessenichead86222018-03-28 18:01:20 -06001823 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001824 TranslateNoContractionDecoration(node->getType().getQualifier()),
1825 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001826 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001827 convertGlslangToSpvType(node->getType()), left, right,
1828 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001829
John Kessenich50e57562015-12-21 21:21:11 -07001830 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001831 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001832 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001833 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001834 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001835 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001836 return false;
1837 }
John Kessenich140f3df2015-06-26 16:58:36 -06001838}
1839
1840bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1841{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001842 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001843
qining40887662016-04-03 22:20:42 -04001844 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1845 if (node->getType().getQualifier().isSpecConstant())
1846 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1847
John Kessenichfc51d282015-08-19 13:34:18 -06001848 spv::Id result = spv::NoResult;
1849
1850 // try texturing first
1851 result = createImageTextureFunctionCall(node);
1852 if (result != spv::NoResult) {
1853 builder.clearAccessChain();
1854 builder.setAccessChainRValue(result);
1855
1856 return false; // done with this node
1857 }
1858
1859 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001860
1861 if (node->getOp() == glslang::EOpArrayLength) {
1862 // Quite special; won't want to evaluate the operand.
1863
John Kessenich5611c6d2018-04-05 11:25:02 -06001864 // Currently, the front-end does not allow .length() on an array until it is sized,
1865 // except for the last block membeor of an SSBO.
1866 // TODO: If this changes, link-time sized arrays might show up here, and need their
1867 // size extracted.
1868
John Kessenichc9a80832015-09-12 12:17:44 -06001869 // Normal .length() would have been constant folded by the front-end.
1870 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001871 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001872
John Kessenichc9a80832015-09-12 12:17:44 -06001873 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1874 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001875 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1876 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001877
John Kessenich8c869672018-11-28 07:01:37 -07001878 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1879 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1880 // AST expectation of a signed result.
1881 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl)
1882 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1883
John Kessenichc9a80832015-09-12 12:17:44 -06001884 builder.clearAccessChain();
1885 builder.setAccessChainRValue(length);
1886
1887 return false;
1888 }
1889
John Kessenichfc51d282015-08-19 13:34:18 -06001890 // Start by evaluating the operand
1891
John Kessenich8c8505c2016-07-26 12:50:38 -06001892 // Does it need a swizzle inversion? If so, evaluation is inverted;
1893 // operate first on the swizzle base, then apply the swizzle.
1894 spv::Id invertedType = spv::NoType;
1895 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1896 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1897 invertedType = getInvertedSwizzleType(*node->getOperand());
1898
John Kessenich140f3df2015-06-26 16:58:36 -06001899 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001900 if (invertedType != spv::NoType)
1901 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1902 else
1903 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001904
Rex Xufc618912015-09-09 16:42:49 +08001905 spv::Id operand = spv::NoResult;
1906
1907 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1908 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001909 node->getOp() == glslang::EOpAtomicCounter ||
1910 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001911 operand = builder.accessChainGetLValue(); // Special case l-value operands
1912 else
John Kessenich32cfd492016-02-02 12:37:46 -07001913 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001914
John Kessenichead86222018-03-28 18:01:20 -06001915 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001916 TranslateNoContractionDecoration(node->getType().getQualifier()),
1917 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001918
1919 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001920 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001921 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001922
1923 // if not, then possibly an operation
1924 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001925 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001926
1927 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001928 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001929 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001930 builder.addDecoration(result, decorations.nonUniform);
1931 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001932
John Kessenich140f3df2015-06-26 16:58:36 -06001933 builder.clearAccessChain();
1934 builder.setAccessChainRValue(result);
1935
1936 return false; // done with this node
1937 }
1938
1939 // it must be a special case, check...
1940 switch (node->getOp()) {
1941 case glslang::EOpPostIncrement:
1942 case glslang::EOpPostDecrement:
1943 case glslang::EOpPreIncrement:
1944 case glslang::EOpPreDecrement:
1945 {
1946 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001947 spv::Id one = 0;
1948 if (node->getBasicType() == glslang::EbtFloat)
1949 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001950 else if (node->getBasicType() == glslang::EbtDouble)
1951 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001952 else if (node->getBasicType() == glslang::EbtFloat16)
1953 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001954 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1955 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001956 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1957 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001958 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1959 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001960 else
1961 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001962 glslang::TOperator op;
1963 if (node->getOp() == glslang::EOpPreIncrement ||
1964 node->getOp() == glslang::EOpPostIncrement)
1965 op = glslang::EOpAdd;
1966 else
1967 op = glslang::EOpSub;
1968
John Kessenichead86222018-03-28 18:01:20 -06001969 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001970 convertGlslangToSpvType(node->getType()), operand, one,
1971 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001972 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001973
1974 // The result of operation is always stored, but conditionally the
1975 // consumed result. The consumed result is always an r-value.
1976 builder.accessChainStore(result);
1977 builder.clearAccessChain();
1978 if (node->getOp() == glslang::EOpPreIncrement ||
1979 node->getOp() == glslang::EOpPreDecrement)
1980 builder.setAccessChainRValue(result);
1981 else
1982 builder.setAccessChainRValue(operand);
1983 }
1984
1985 return false;
1986
1987 case glslang::EOpEmitStreamVertex:
1988 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1989 return false;
1990 case glslang::EOpEndStreamPrimitive:
1991 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1992 return false;
1993
1994 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001995 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001996 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001997 }
John Kessenich140f3df2015-06-26 16:58:36 -06001998}
1999
2000bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2001{
qining27e04a02016-04-14 16:40:20 -04002002 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2003 if (node->getType().getQualifier().isSpecConstant())
2004 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2005
John Kessenichfc51d282015-08-19 13:34:18 -06002006 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002007 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2008 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002009
2010 // try texturing
2011 result = createImageTextureFunctionCall(node);
2012 if (result != spv::NoResult) {
2013 builder.clearAccessChain();
2014 builder.setAccessChainRValue(result);
2015
2016 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002017 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002018#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002019 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002020#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002021 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002022 // "imageStore" is a special case, which has no result
2023 return false;
2024 }
John Kessenichfc51d282015-08-19 13:34:18 -06002025
John Kessenich140f3df2015-06-26 16:58:36 -06002026 glslang::TOperator binOp = glslang::EOpNull;
2027 bool reduceComparison = true;
2028 bool isMatrix = false;
2029 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002030 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002031
2032 assert(node->getOp());
2033
John Kessenichf6640762016-08-01 19:44:00 -06002034 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002035
2036 switch (node->getOp()) {
2037 case glslang::EOpSequence:
2038 {
2039 if (preVisit)
2040 ++sequenceDepth;
2041 else
2042 --sequenceDepth;
2043
2044 if (sequenceDepth == 1) {
2045 // If this is the parent node of all the functions, we want to see them
2046 // early, so all call points have actual SPIR-V functions to reference.
2047 // In all cases, still let the traverser visit the children for us.
2048 makeFunctions(node->getAsAggregate()->getSequence());
2049
John Kessenich6fccb3c2016-09-19 16:01:41 -06002050 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002051 // anything else gets there, so visit out of order, doing them all now.
2052 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2053
John Kessenich6a60c2f2016-12-08 21:01:59 -07002054 // 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 -06002055 // so do them manually.
2056 visitFunctions(node->getAsAggregate()->getSequence());
2057
2058 return false;
2059 }
2060
2061 return true;
2062 }
2063 case glslang::EOpLinkerObjects:
2064 {
2065 if (visit == glslang::EvPreVisit)
2066 linkageOnly = true;
2067 else
2068 linkageOnly = false;
2069
2070 return true;
2071 }
2072 case glslang::EOpComma:
2073 {
2074 // processing from left to right naturally leaves the right-most
2075 // lying around in the access chain
2076 glslang::TIntermSequence& glslangOperands = node->getSequence();
2077 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2078 glslangOperands[i]->traverse(this);
2079
2080 return false;
2081 }
2082 case glslang::EOpFunction:
2083 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002084 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002085 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002086 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002087 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002088 } else {
2089 handleFunctionEntry(node);
2090 }
2091 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002092 if (inEntryPoint)
2093 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002094 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002095 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002096 }
2097
2098 return true;
2099 case glslang::EOpParameters:
2100 // Parameters will have been consumed by EOpFunction processing, but not
2101 // the body, so we still visited the function node's children, making this
2102 // child redundant.
2103 return false;
2104 case glslang::EOpFunctionCall:
2105 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002106 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002107 if (node->isUserDefined())
2108 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002109 // 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 -07002110 if (result) {
2111 builder.clearAccessChain();
2112 builder.setAccessChainRValue(result);
2113 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002114 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002115
2116 return false;
2117 }
2118 case glslang::EOpConstructMat2x2:
2119 case glslang::EOpConstructMat2x3:
2120 case glslang::EOpConstructMat2x4:
2121 case glslang::EOpConstructMat3x2:
2122 case glslang::EOpConstructMat3x3:
2123 case glslang::EOpConstructMat3x4:
2124 case glslang::EOpConstructMat4x2:
2125 case glslang::EOpConstructMat4x3:
2126 case glslang::EOpConstructMat4x4:
2127 case glslang::EOpConstructDMat2x2:
2128 case glslang::EOpConstructDMat2x3:
2129 case glslang::EOpConstructDMat2x4:
2130 case glslang::EOpConstructDMat3x2:
2131 case glslang::EOpConstructDMat3x3:
2132 case glslang::EOpConstructDMat3x4:
2133 case glslang::EOpConstructDMat4x2:
2134 case glslang::EOpConstructDMat4x3:
2135 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002136 case glslang::EOpConstructIMat2x2:
2137 case glslang::EOpConstructIMat2x3:
2138 case glslang::EOpConstructIMat2x4:
2139 case glslang::EOpConstructIMat3x2:
2140 case glslang::EOpConstructIMat3x3:
2141 case glslang::EOpConstructIMat3x4:
2142 case glslang::EOpConstructIMat4x2:
2143 case glslang::EOpConstructIMat4x3:
2144 case glslang::EOpConstructIMat4x4:
2145 case glslang::EOpConstructUMat2x2:
2146 case glslang::EOpConstructUMat2x3:
2147 case glslang::EOpConstructUMat2x4:
2148 case glslang::EOpConstructUMat3x2:
2149 case glslang::EOpConstructUMat3x3:
2150 case glslang::EOpConstructUMat3x4:
2151 case glslang::EOpConstructUMat4x2:
2152 case glslang::EOpConstructUMat4x3:
2153 case glslang::EOpConstructUMat4x4:
2154 case glslang::EOpConstructBMat2x2:
2155 case glslang::EOpConstructBMat2x3:
2156 case glslang::EOpConstructBMat2x4:
2157 case glslang::EOpConstructBMat3x2:
2158 case glslang::EOpConstructBMat3x3:
2159 case glslang::EOpConstructBMat3x4:
2160 case glslang::EOpConstructBMat4x2:
2161 case glslang::EOpConstructBMat4x3:
2162 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002163 case glslang::EOpConstructF16Mat2x2:
2164 case glslang::EOpConstructF16Mat2x3:
2165 case glslang::EOpConstructF16Mat2x4:
2166 case glslang::EOpConstructF16Mat3x2:
2167 case glslang::EOpConstructF16Mat3x3:
2168 case glslang::EOpConstructF16Mat3x4:
2169 case glslang::EOpConstructF16Mat4x2:
2170 case glslang::EOpConstructF16Mat4x3:
2171 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002172 isMatrix = true;
2173 // fall through
2174 case glslang::EOpConstructFloat:
2175 case glslang::EOpConstructVec2:
2176 case glslang::EOpConstructVec3:
2177 case glslang::EOpConstructVec4:
2178 case glslang::EOpConstructDouble:
2179 case glslang::EOpConstructDVec2:
2180 case glslang::EOpConstructDVec3:
2181 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002182 case glslang::EOpConstructFloat16:
2183 case glslang::EOpConstructF16Vec2:
2184 case glslang::EOpConstructF16Vec3:
2185 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002186 case glslang::EOpConstructBool:
2187 case glslang::EOpConstructBVec2:
2188 case glslang::EOpConstructBVec3:
2189 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002190 case glslang::EOpConstructInt8:
2191 case glslang::EOpConstructI8Vec2:
2192 case glslang::EOpConstructI8Vec3:
2193 case glslang::EOpConstructI8Vec4:
2194 case glslang::EOpConstructUint8:
2195 case glslang::EOpConstructU8Vec2:
2196 case glslang::EOpConstructU8Vec3:
2197 case glslang::EOpConstructU8Vec4:
2198 case glslang::EOpConstructInt16:
2199 case glslang::EOpConstructI16Vec2:
2200 case glslang::EOpConstructI16Vec3:
2201 case glslang::EOpConstructI16Vec4:
2202 case glslang::EOpConstructUint16:
2203 case glslang::EOpConstructU16Vec2:
2204 case glslang::EOpConstructU16Vec3:
2205 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002206 case glslang::EOpConstructInt:
2207 case glslang::EOpConstructIVec2:
2208 case glslang::EOpConstructIVec3:
2209 case glslang::EOpConstructIVec4:
2210 case glslang::EOpConstructUint:
2211 case glslang::EOpConstructUVec2:
2212 case glslang::EOpConstructUVec3:
2213 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002214 case glslang::EOpConstructInt64:
2215 case glslang::EOpConstructI64Vec2:
2216 case glslang::EOpConstructI64Vec3:
2217 case glslang::EOpConstructI64Vec4:
2218 case glslang::EOpConstructUint64:
2219 case glslang::EOpConstructU64Vec2:
2220 case glslang::EOpConstructU64Vec3:
2221 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002222 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002223 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002224 case glslang::EOpConstructReference:
John Kessenich140f3df2015-06-26 16:58:36 -06002225 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002226 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002227 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002228 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002229 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002230 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002231 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002232 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002233 std::vector<spv::Id> constituents;
2234 for (int c = 0; c < (int)arguments.size(); ++c)
2235 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002236 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002237 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002238 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002239 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002240 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002241
2242 builder.clearAccessChain();
2243 builder.setAccessChainRValue(constructed);
2244
2245 return false;
2246 }
2247
2248 // These six are component-wise compares with component-wise results.
2249 // Forward on to createBinaryOperation(), requesting a vector result.
2250 case glslang::EOpLessThan:
2251 case glslang::EOpGreaterThan:
2252 case glslang::EOpLessThanEqual:
2253 case glslang::EOpGreaterThanEqual:
2254 case glslang::EOpVectorEqual:
2255 case glslang::EOpVectorNotEqual:
2256 {
2257 // Map the operation to a binary
2258 binOp = node->getOp();
2259 reduceComparison = false;
2260 switch (node->getOp()) {
2261 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2262 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2263 default: binOp = node->getOp(); break;
2264 }
2265
2266 break;
2267 }
2268 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002269 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002270 binOp = glslang::EOpMul;
2271 break;
2272 case glslang::EOpOuterProduct:
2273 // two vectors multiplied to make a matrix
2274 binOp = glslang::EOpOuterProduct;
2275 break;
2276 case glslang::EOpDot:
2277 {
qining25262b32016-05-06 17:25:16 -04002278 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002279 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002280 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002281 binOp = glslang::EOpMul;
2282 break;
2283 }
2284 case glslang::EOpMod:
2285 // when an aggregate, this is the floating-point mod built-in function,
2286 // which can be emitted by the one in createBinaryOperation()
2287 binOp = glslang::EOpMod;
2288 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002289 case glslang::EOpEmitVertex:
2290 case glslang::EOpEndPrimitive:
2291 case glslang::EOpBarrier:
2292 case glslang::EOpMemoryBarrier:
2293 case glslang::EOpMemoryBarrierAtomicCounter:
2294 case glslang::EOpMemoryBarrierBuffer:
2295 case glslang::EOpMemoryBarrierImage:
2296 case glslang::EOpMemoryBarrierShared:
2297 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002298 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002299 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002300 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002301 case glslang::EOpWorkgroupMemoryBarrier:
2302 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002303 case glslang::EOpSubgroupBarrier:
2304 case glslang::EOpSubgroupMemoryBarrier:
2305 case glslang::EOpSubgroupMemoryBarrierBuffer:
2306 case glslang::EOpSubgroupMemoryBarrierImage:
2307 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002308 noReturnValue = true;
2309 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2310 break;
2311
Jeff Bolz36831c92018-09-05 10:11:41 -05002312 case glslang::EOpAtomicStore:
2313 noReturnValue = true;
2314 // fallthrough
2315 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002316 case glslang::EOpAtomicAdd:
2317 case glslang::EOpAtomicMin:
2318 case glslang::EOpAtomicMax:
2319 case glslang::EOpAtomicAnd:
2320 case glslang::EOpAtomicOr:
2321 case glslang::EOpAtomicXor:
2322 case glslang::EOpAtomicExchange:
2323 case glslang::EOpAtomicCompSwap:
2324 atomic = true;
2325 break;
2326
John Kessenich0d0c6d32017-07-23 16:08:26 -06002327 case glslang::EOpAtomicCounterAdd:
2328 case glslang::EOpAtomicCounterSubtract:
2329 case glslang::EOpAtomicCounterMin:
2330 case glslang::EOpAtomicCounterMax:
2331 case glslang::EOpAtomicCounterAnd:
2332 case glslang::EOpAtomicCounterOr:
2333 case glslang::EOpAtomicCounterXor:
2334 case glslang::EOpAtomicCounterExchange:
2335 case glslang::EOpAtomicCounterCompSwap:
2336 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2337 builder.addCapability(spv::CapabilityAtomicStorageOps);
2338 atomic = true;
2339 break;
2340
Chao Chen3c366992018-09-19 11:41:59 -07002341#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002342 case glslang::EOpIgnoreIntersectionNV:
2343 case glslang::EOpTerminateRayNV:
2344 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002345 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002346 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2347 noReturnValue = true;
2348 break;
2349#endif
2350
John Kessenich140f3df2015-06-26 16:58:36 -06002351 default:
2352 break;
2353 }
2354
2355 //
2356 // See if it maps to a regular operation.
2357 //
John Kessenich140f3df2015-06-26 16:58:36 -06002358 if (binOp != glslang::EOpNull) {
2359 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2360 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2361 assert(left && right);
2362
2363 builder.clearAccessChain();
2364 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002365 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002366
2367 builder.clearAccessChain();
2368 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002369 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002370
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002371 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002372 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002373 TranslateNoContractionDecoration(node->getType().getQualifier()),
2374 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002375 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002376 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002377 left->getType().getBasicType(), reduceComparison);
2378
2379 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002380 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002381 builder.clearAccessChain();
2382 builder.setAccessChainRValue(result);
2383
2384 return false;
2385 }
2386
John Kessenich426394d2015-07-23 10:22:48 -06002387 //
2388 // Create the list of operands.
2389 //
John Kessenich140f3df2015-06-26 16:58:36 -06002390 glslang::TIntermSequence& glslangOperands = node->getSequence();
2391 std::vector<spv::Id> operands;
2392 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002393 // special case l-value operands; there are just a few
2394 bool lvalue = false;
2395 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002396 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002397 case glslang::EOpModf:
2398 if (arg == 1)
2399 lvalue = true;
2400 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002401 case glslang::EOpInterpolateAtSample:
2402 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002403#ifdef AMD_EXTENSIONS
2404 case glslang::EOpInterpolateAtVertex:
2405#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002406 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002407 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002408
2409 // Does it need a swizzle inversion? If so, evaluation is inverted;
2410 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002411 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002412 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2413 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2414 }
Rex Xu7a26c172015-12-08 17:12:09 +08002415 break;
Rex Xud4782c12015-09-06 16:30:11 +08002416 case glslang::EOpAtomicAdd:
2417 case glslang::EOpAtomicMin:
2418 case glslang::EOpAtomicMax:
2419 case glslang::EOpAtomicAnd:
2420 case glslang::EOpAtomicOr:
2421 case glslang::EOpAtomicXor:
2422 case glslang::EOpAtomicExchange:
2423 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002424 case glslang::EOpAtomicLoad:
2425 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002426 case glslang::EOpAtomicCounterAdd:
2427 case glslang::EOpAtomicCounterSubtract:
2428 case glslang::EOpAtomicCounterMin:
2429 case glslang::EOpAtomicCounterMax:
2430 case glslang::EOpAtomicCounterAnd:
2431 case glslang::EOpAtomicCounterOr:
2432 case glslang::EOpAtomicCounterXor:
2433 case glslang::EOpAtomicCounterExchange:
2434 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002435 if (arg == 0)
2436 lvalue = true;
2437 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002438 case glslang::EOpAddCarry:
2439 case glslang::EOpSubBorrow:
2440 if (arg == 2)
2441 lvalue = true;
2442 break;
2443 case glslang::EOpUMulExtended:
2444 case glslang::EOpIMulExtended:
2445 if (arg >= 2)
2446 lvalue = true;
2447 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002448 default:
2449 break;
2450 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002451 builder.clearAccessChain();
2452 if (invertedType != spv::NoType && arg == 0)
2453 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2454 else
2455 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002456 if (lvalue)
2457 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002458 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002459 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002460 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002461 }
John Kessenich140f3df2015-06-26 16:58:36 -06002462 }
John Kessenich426394d2015-07-23 10:22:48 -06002463
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002464 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich426394d2015-07-23 10:22:48 -06002465 if (atomic) {
2466 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002467 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002468 } else {
2469 // Pass through to generic operations.
2470 switch (glslangOperands.size()) {
2471 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002472 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002473 break;
2474 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002475 {
2476 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002477 TranslateNoContractionDecoration(node->getType().getQualifier()),
2478 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002479 result = createUnaryOperation(
2480 node->getOp(), decorations,
2481 resultType(), operands.front(),
2482 glslangOperands[0]->getAsTyped()->getBasicType());
2483 }
John Kessenich426394d2015-07-23 10:22:48 -06002484 break;
2485 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002486 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002487 break;
2488 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002489 if (invertedType)
2490 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002491 }
2492
2493 if (noReturnValue)
2494 return false;
2495
2496 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002497 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002498 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002499 } else {
2500 builder.clearAccessChain();
2501 builder.setAccessChainRValue(result);
2502 return false;
2503 }
2504}
2505
John Kessenich433e9ff2017-01-26 20:31:11 -07002506// This path handles both if-then-else and ?:
2507// The if-then-else has a node type of void, while
2508// ?: has either a void or a non-void node type
2509//
2510// Leaving the result, when not void:
2511// GLSL only has r-values as the result of a :?, but
2512// if we have an l-value, that can be more efficient if it will
2513// become the base of a complex r-value expression, because the
2514// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002515bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2516{
John Kessenich4bee5312018-02-20 21:29:05 -07002517 // See if it simple and safe, or required, to execute both sides.
2518 // Crucially, side effects must be either semantically required or avoided,
2519 // and there are performance trade-offs.
2520 // Return true if required or a good idea (and safe) to execute both sides,
2521 // false otherwise.
2522 const auto bothSidesPolicy = [&]() -> bool {
2523 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002524 if (node->getTrueBlock() == nullptr ||
2525 node->getFalseBlock() == nullptr)
2526 return false;
2527
John Kessenich4bee5312018-02-20 21:29:05 -07002528 // required? (unless we write additional code to look for side effects
2529 // and make performance trade-offs if none are present)
2530 if (!node->getShortCircuit())
2531 return true;
2532
2533 // if not required to execute both, decide based on performance/practicality...
2534
2535 // see if OpSelect can handle it
2536 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2537 node->getBasicType() == glslang::EbtVoid)
2538 return false;
2539
John Kessenich433e9ff2017-01-26 20:31:11 -07002540 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2541 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2542
2543 // return true if a single operand to ? : is okay for OpSelect
2544 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002545 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002546 };
2547
2548 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2549 operandOkay(node->getFalseBlock()->getAsTyped());
2550 };
2551
John Kessenich4bee5312018-02-20 21:29:05 -07002552 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2553 // emit the condition before doing anything with selection
2554 node->getCondition()->traverse(this);
2555 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2556
2557 // Find a way of executing both sides and selecting the right result.
2558 const auto executeBothSides = [&]() -> void {
2559 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002560 node->getTrueBlock()->traverse(this);
2561 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2562 node->getFalseBlock()->traverse(this);
2563 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2564
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002565 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002566
John Kessenich4bee5312018-02-20 21:29:05 -07002567 // done if void
2568 if (node->getBasicType() == glslang::EbtVoid)
2569 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002570
John Kessenich4bee5312018-02-20 21:29:05 -07002571 // emit code to select between trueValue and falseValue
2572
2573 // see if OpSelect can handle it
2574 if (node->getType().isScalar() || node->getType().isVector()) {
2575 // Emit OpSelect for this selection.
2576
2577 // smear condition to vector, if necessary (AST is always scalar)
2578 if (builder.isVector(trueValue))
2579 condition = builder.smearScalar(spv::NoPrecision, condition,
2580 builder.makeVectorType(builder.makeBoolType(),
2581 builder.getNumComponents(trueValue)));
2582
2583 // OpSelect
2584 result = builder.createTriOp(spv::OpSelect,
2585 convertGlslangToSpvType(node->getType()), condition,
2586 trueValue, falseValue);
2587
2588 builder.clearAccessChain();
2589 builder.setAccessChainRValue(result);
2590 } else {
2591 // We need control flow to select the result.
2592 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2593 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2594
2595 // Selection control:
2596 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2597
2598 // make an "if" based on the value created by the condition
2599 spv::Builder::If ifBuilder(condition, control, builder);
2600
2601 // emit the "then" statement
2602 builder.createStore(trueValue, result);
2603 ifBuilder.makeBeginElse();
2604 // emit the "else" statement
2605 builder.createStore(falseValue, result);
2606
2607 // finish off the control flow
2608 ifBuilder.makeEndIf();
2609
2610 builder.clearAccessChain();
2611 builder.setAccessChainLValue(result);
2612 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002613 };
2614
John Kessenich4bee5312018-02-20 21:29:05 -07002615 // Execute the one side needed, as per the condition
2616 const auto executeOneSide = [&]() {
2617 // Always emit control flow.
2618 if (node->getBasicType() != glslang::EbtVoid)
2619 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002620
John Kessenich4bee5312018-02-20 21:29:05 -07002621 // Selection control:
2622 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2623
2624 // make an "if" based on the value created by the condition
2625 spv::Builder::If ifBuilder(condition, control, builder);
2626
2627 // emit the "then" statement
2628 if (node->getTrueBlock() != nullptr) {
2629 node->getTrueBlock()->traverse(this);
2630 if (result != spv::NoResult)
2631 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2632 }
2633
2634 if (node->getFalseBlock() != nullptr) {
2635 ifBuilder.makeBeginElse();
2636 // emit the "else" statement
2637 node->getFalseBlock()->traverse(this);
2638 if (result != spv::NoResult)
2639 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2640 }
2641
2642 // finish off the control flow
2643 ifBuilder.makeEndIf();
2644
2645 if (result != spv::NoResult) {
2646 builder.clearAccessChain();
2647 builder.setAccessChainLValue(result);
2648 }
2649 };
2650
2651 // Try for OpSelect (or a requirement to execute both sides)
2652 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002653 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2654 if (node->getType().getQualifier().isSpecConstant())
2655 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002656 executeBothSides();
2657 } else
2658 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002659
2660 return false;
2661}
2662
2663bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2664{
2665 // emit and get the condition before doing anything with switch
2666 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002667 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002668
Rex Xu57e65922017-07-04 23:23:40 +08002669 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002670 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002671
John Kessenich140f3df2015-06-26 16:58:36 -06002672 // browse the children to sort out code segments
2673 int defaultSegment = -1;
2674 std::vector<TIntermNode*> codeSegments;
2675 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2676 std::vector<int> caseValues;
2677 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2678 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2679 TIntermNode* child = *c;
2680 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002681 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002682 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002683 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002684 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2685 } else
2686 codeSegments.push_back(child);
2687 }
2688
qining25262b32016-05-06 17:25:16 -04002689 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002690 // statements between the last case and the end of the switch statement
2691 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2692 (int)codeSegments.size() == defaultSegment)
2693 codeSegments.push_back(nullptr);
2694
2695 // make the switch statement
2696 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002697 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002698
2699 // emit all the code in the segments
2700 breakForLoop.push(false);
2701 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2702 builder.nextSwitchSegment(segmentBlocks, s);
2703 if (codeSegments[s])
2704 codeSegments[s]->traverse(this);
2705 else
2706 builder.addSwitchBreak();
2707 }
2708 breakForLoop.pop();
2709
2710 builder.endSwitch(segmentBlocks);
2711
2712 return false;
2713}
2714
2715void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2716{
2717 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002718 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002719
2720 builder.clearAccessChain();
2721 builder.setAccessChainRValue(constant);
2722}
2723
2724bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2725{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002726 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002727 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002728
2729 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002730 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2731 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002732
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002733 // Spec requires back edges to target header blocks, and every header block
2734 // must dominate its merge block. Make a header block first to ensure these
2735 // conditions are met. By definition, it will contain OpLoopMerge, followed
2736 // by a block-ending branch. But we don't want to put any other body/test
2737 // instructions in it, since the body/test may have arbitrary instructions,
2738 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002739 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002740 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002741 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002742 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002743 spv::Block& test = builder.makeNewBlock();
2744 builder.createBranch(&test);
2745
2746 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002747 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002748 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002749 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2750
2751 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002752 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002753 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002754 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002755 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002756 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002757
2758 builder.setBuildPoint(&blocks.continue_target);
2759 if (node->getTerminal())
2760 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002761 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002762 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002763 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002764 builder.createBranch(&blocks.body);
2765
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002766 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002767 builder.setBuildPoint(&blocks.body);
2768 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002769 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002770 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002771 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002772
2773 builder.setBuildPoint(&blocks.continue_target);
2774 if (node->getTerminal())
2775 node->getTerminal()->traverse(this);
2776 if (node->getTest()) {
2777 node->getTest()->traverse(this);
2778 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002779 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002780 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002781 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002782 // TODO: unless there was a break/return/discard instruction
2783 // somewhere in the body, this is an infinite loop, so we should
2784 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002785 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002786 }
John Kessenich140f3df2015-06-26 16:58:36 -06002787 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002788 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002789 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002790 return false;
2791}
2792
2793bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2794{
2795 if (node->getExpression())
2796 node->getExpression()->traverse(this);
2797
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002798 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002799
John Kessenich140f3df2015-06-26 16:58:36 -06002800 switch (node->getFlowOp()) {
2801 case glslang::EOpKill:
2802 builder.makeDiscard();
2803 break;
2804 case glslang::EOpBreak:
2805 if (breakForLoop.top())
2806 builder.createLoopExit();
2807 else
2808 builder.addSwitchBreak();
2809 break;
2810 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002811 builder.createLoopContinue();
2812 break;
2813 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002814 if (node->getExpression()) {
2815 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2816 spv::Id returnId = accessChainLoad(glslangReturnType);
2817 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2818 builder.clearAccessChain();
2819 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2820 builder.setAccessChainLValue(copyId);
2821 multiTypeStore(glslangReturnType, returnId);
2822 returnId = builder.createLoad(copyId);
2823 }
2824 builder.makeReturn(false, returnId);
2825 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002826 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002827
2828 builder.clearAccessChain();
2829 break;
2830
2831 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002832 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002833 break;
2834 }
2835
2836 return false;
2837}
2838
2839spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2840{
qining25262b32016-05-06 17:25:16 -04002841 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002842 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002843 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002844 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002845 spv::Id result = createSpvConstant(*node);
2846 if (result != spv::NoResult)
2847 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002848 }
2849
2850 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002851 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002852 spv::Id spvType = convertGlslangToSpvType(node->getType());
2853
Rex Xucabbb782017-03-24 13:41:14 +08002854 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2855 node->getType().containsBasicType(glslang::EbtInt16) ||
2856 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002857 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002858 switch (storageClass) {
2859 case spv::StorageClassInput:
2860 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002861 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002862 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002863 break;
2864 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002865 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002866 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002867 break;
2868 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002869 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002870 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2871 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002872 else
2873 builder.addCapability(spv::CapabilityStorageUniform16);
2874 break;
2875 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002876 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06002877 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2878 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2879 break;
2880 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06002881 if (node->getType().containsBasicType(glslang::EbtFloat16))
2882 builder.addCapability(spv::CapabilityFloat16);
2883 if (node->getType().containsBasicType(glslang::EbtInt16) ||
2884 node->getType().containsBasicType(glslang::EbtUint16))
2885 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06002886 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002887 }
2888 }
Rex Xuf89ad982017-04-07 23:22:33 +08002889
John Kessenich312dcfb2018-07-03 13:19:51 -06002890 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2891 node->getType().containsBasicType(glslang::EbtUint8);
2892 if (contains8BitType) {
2893 if (storageClass == spv::StorageClassPushConstant) {
2894 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2895 builder.addCapability(spv::CapabilityStoragePushConstant8);
2896 } else if (storageClass == spv::StorageClassUniform) {
2897 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2898 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002899 } else if (storageClass == spv::StorageClassStorageBuffer) {
2900 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2901 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06002902 } else {
2903 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06002904 }
2905 }
2906
John Kessenich140f3df2015-06-26 16:58:36 -06002907 const char* name = node->getName().c_str();
2908 if (glslang::IsAnonymous(name))
2909 name = "";
2910
2911 return builder.createVariable(storageClass, spvType, name);
2912}
2913
2914// Return type Id of the sampled type.
2915spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2916{
2917 switch (sampler.type) {
2918 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002919#ifdef AMD_EXTENSIONS
2920 case glslang::EbtFloat16:
2921 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2922 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2923 return builder.makeFloatType(16);
2924#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002925 case glslang::EbtInt: return builder.makeIntType(32);
2926 case glslang::EbtUint: return builder.makeUintType(32);
2927 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002928 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002929 return builder.makeFloatType(32);
2930 }
2931}
2932
John Kessenich8c8505c2016-07-26 12:50:38 -06002933// If node is a swizzle operation, return the type that should be used if
2934// the swizzle base is first consumed by another operation, before the swizzle
2935// is applied.
2936spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2937{
John Kessenichecba76f2017-01-06 00:34:48 -07002938 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002939 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2940 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2941 else
2942 return spv::NoType;
2943}
2944
2945// When inverting a swizzle with a parent op, this function
2946// will apply the swizzle operation to a completed parent operation.
2947spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2948{
2949 std::vector<unsigned> swizzle;
2950 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2951 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2952}
2953
John Kessenich8c8505c2016-07-26 12:50:38 -06002954// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2955void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2956{
2957 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2958 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2959 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2960}
2961
John Kessenich3ac051e2015-12-20 11:29:16 -07002962// Convert from a glslang type to an SPV type, by calling into a
2963// recursive version of this function. This establishes the inherited
2964// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002965spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002966{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002967 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06002968}
2969
2970// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002971// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002972// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002973spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002974 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
2975 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06002976{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002977 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002978
2979 switch (type.getBasicType()) {
2980 case glslang::EbtVoid:
2981 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002982 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002983 break;
2984 case glslang::EbtFloat:
2985 spvType = builder.makeFloatType(32);
2986 break;
2987 case glslang::EbtDouble:
2988 spvType = builder.makeFloatType(64);
2989 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002990 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002991 spvType = builder.makeFloatType(16);
2992 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002994 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2995 // a 32-bit int where non-0 means true.
2996 if (explicitLayout != glslang::ElpNone)
2997 spvType = builder.makeUintType(32);
2998 else
2999 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003000 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003001 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003002 spvType = builder.makeIntType(8);
3003 break;
3004 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003005 spvType = builder.makeUintType(8);
3006 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003007 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003008 spvType = builder.makeIntType(16);
3009 break;
3010 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003011 spvType = builder.makeUintType(16);
3012 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003013 case glslang::EbtInt:
3014 spvType = builder.makeIntType(32);
3015 break;
3016 case glslang::EbtUint:
3017 spvType = builder.makeUintType(32);
3018 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003019 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003020 spvType = builder.makeIntType(64);
3021 break;
3022 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003023 spvType = builder.makeUintType(64);
3024 break;
John Kessenich426394d2015-07-23 10:22:48 -06003025 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003026 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003027 spvType = builder.makeUintType(32);
3028 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003029#ifdef NV_EXTENSIONS
3030 case glslang::EbtAccStructNV:
3031 spvType = builder.makeAccelerationStructureNVType();
3032 break;
3033#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003034 case glslang::EbtSampler:
3035 {
3036 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003037 if (sampler.sampler) {
3038 // pure sampler
3039 spvType = builder.makeSamplerType();
3040 } else {
3041 // an image is present, make its type
3042 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3043 sampler.image ? 2 : 1, TranslateImageFormat(type));
3044 if (sampler.combined) {
3045 // already has both image and sampler, make the combined type
3046 spvType = builder.makeSampledImageType(spvType);
3047 }
John Kessenich55e7d112015-11-15 21:33:39 -07003048 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003049 }
John Kessenich140f3df2015-06-26 16:58:36 -06003050 break;
3051 case glslang::EbtStruct:
3052 case glslang::EbtBlock:
3053 {
3054 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003055 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003056
3057 // Try to share structs for different layouts, but not yet for other
3058 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003059 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003060 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003061 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003062 break;
3063
3064 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003065 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003066 memberRemapper[glslangMembers].resize(glslangMembers->size());
3067 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003068 }
3069 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003070 case glslang::EbtReference:
3071 {
3072 // Make the forward pointer, then recurse to convert the structure type, then
3073 // patch up the forward pointer with a real pointer type.
3074 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3075 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3076 forwardPointers[type.getReferentType()] = forwardId;
3077 }
3078 spvType = forwardPointers[type.getReferentType()];
3079 if (!forwardReferenceOnly) {
3080 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3081 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3082 forwardPointers[type.getReferentType()],
3083 referentType);
3084 }
3085 }
3086 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003088 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003089 break;
3090 }
3091
3092 if (type.isMatrix())
3093 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3094 else {
3095 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3096 if (type.getVectorSize() > 1)
3097 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3098 }
3099
3100 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003101 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3102
John Kessenichc9a80832015-09-12 12:17:44 -06003103 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003104 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003105 // We need to decorate array strides for types needing explicit layout, except blocks.
3106 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003107 // Use a dummy glslang type for querying internal strides of
3108 // arrays of arrays, but using just a one-dimensional array.
3109 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003110 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3111 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003112
3113 // Will compute the higher-order strides here, rather than making a whole
3114 // pile of types and doing repetitive recursion on their contents.
3115 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3116 }
John Kessenichf8842e52016-01-04 19:22:56 -07003117
3118 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003119 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003120 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003121 if (stride > 0)
3122 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003123 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003124 }
3125 } else {
3126 // single-dimensional array, and don't yet have stride
3127
John Kessenichf8842e52016-01-04 19:22:56 -07003128 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003129 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3130 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003131 }
John Kessenich31ed4832015-09-09 17:51:38 -06003132
John Kessenichead86222018-03-28 18:01:20 -06003133 // Do the outer dimension, which might not be known for a runtime-sized array.
3134 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3135 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003136 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003137 else {
3138 if (!lastBufferBlockMember) {
3139 builder.addExtension("SPV_EXT_descriptor_indexing");
3140 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3141 }
John Kessenichead86222018-03-28 18:01:20 -06003142 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003143 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003144 if (stride > 0)
3145 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003146 }
3147
3148 return spvType;
3149}
3150
John Kessenich0e737842017-03-24 18:38:16 -06003151// TODO: this functionality should exist at a higher level, in creating the AST
3152//
3153// Identify interface members that don't have their required extension turned on.
3154//
3155bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3156{
Chao Chen3c366992018-09-19 11:41:59 -07003157#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003158 auto& extensions = glslangIntermediate->getRequestedExtensions();
3159
Rex Xubcf291a2017-03-29 23:01:36 +08003160 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3161 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3162 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003163 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3164 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3165 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003166
3167 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3168 if (member.getFieldName() == "gl_ViewportMask" &&
3169 extensions.find("GL_NV_viewport_array2") == extensions.end())
3170 return true;
3171 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3172 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3173 return true;
3174 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3175 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3176 return true;
3177 }
3178#endif
John Kessenich0e737842017-03-24 18:38:16 -06003179
3180 return false;
3181};
3182
John Kessenich6090df02016-06-30 21:18:02 -06003183// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3184// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3185// Mutually recursive with convertGlslangToSpvType().
3186spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3187 const glslang::TTypeList* glslangMembers,
3188 glslang::TLayoutPacking explicitLayout,
3189 const glslang::TQualifier& qualifier)
3190{
3191 // Create a vector of struct types for SPIR-V to consume
3192 std::vector<spv::Id> spvMembers;
3193 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003194 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003195 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3196 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3197 if (glslangMember.hiddenMember()) {
3198 ++memberDelta;
3199 if (type.getBasicType() == glslang::EbtBlock)
3200 memberRemapper[glslangMembers][i] = -1;
3201 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003202 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003203 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003204 if (filterMember(glslangMember))
3205 continue;
3206 }
John Kessenich6090df02016-06-30 21:18:02 -06003207 // modify just this child's view of the qualifier
3208 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3209 InheritQualifiers(memberQualifier, qualifier);
3210
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003211 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003212 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003213 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003214
3215 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003216 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3217 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003218
3219 // Make forward pointers for any pointer members, and create a list of members to
3220 // convert to spirv types after creating the struct.
3221 if (glslangMember.getBasicType() == glslang::EbtReference) {
3222 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3223 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3224 }
3225 spvMembers.push_back(
3226 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3227 } else {
3228 spvMembers.push_back(
3229 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3230 }
John Kessenich6090df02016-06-30 21:18:02 -06003231 }
3232 }
3233
3234 // Make the SPIR-V type
3235 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003236 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003237 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3238
3239 // Decorate it
3240 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3241
John Kessenichd72f4882019-01-16 14:55:37 +07003242 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003243 auto it = deferredForwardPointers[i];
3244 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3245 }
3246
John Kessenich6090df02016-06-30 21:18:02 -06003247 return spvType;
3248}
3249
3250void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3251 const glslang::TTypeList* glslangMembers,
3252 glslang::TLayoutPacking explicitLayout,
3253 const glslang::TQualifier& qualifier,
3254 spv::Id spvType)
3255{
3256 // Name and decorate the non-hidden members
3257 int offset = -1;
3258 int locationOffset = 0; // for use within the members of this struct
3259 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3260 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3261 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003262 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003263 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003264 if (filterMember(glslangMember))
3265 continue;
3266 }
John Kessenich6090df02016-06-30 21:18:02 -06003267
3268 // modify just this child's view of the qualifier
3269 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3270 InheritQualifiers(memberQualifier, qualifier);
3271
3272 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003273 if (member < 0)
3274 continue;
3275
3276 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3277 builder.addMemberDecoration(spvType, member,
3278 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3279 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3280 // Add interpolation and auxiliary storage decorations only to
3281 // top-level members of Input and Output storage classes
3282 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3283 type.getQualifier().storage == glslang::EvqVaryingOut) {
3284 if (type.getBasicType() == glslang::EbtBlock ||
3285 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3286 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3287 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003288#ifdef NV_EXTENSIONS
3289 addMeshNVDecoration(spvType, member, memberQualifier);
3290#endif
John Kessenich6090df02016-06-30 21:18:02 -06003291 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003292 }
3293 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003294
John Kessenich5d610ee2018-03-07 18:05:55 -07003295 if (type.getBasicType() == glslang::EbtBlock &&
3296 qualifier.storage == glslang::EvqBuffer) {
3297 // Add memory decorations only to top-level members of shader storage block
3298 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003299 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003300 for (unsigned int i = 0; i < memory.size(); ++i)
3301 builder.addMemberDecoration(spvType, member, memory[i]);
3302 }
John Kessenich6090df02016-06-30 21:18:02 -06003303
John Kessenich5d610ee2018-03-07 18:05:55 -07003304 // Location assignment was already completed correctly by the front end,
3305 // just track whether a member needs to be decorated.
3306 // Ignore member locations if the container is an array, as that's
3307 // ill-specified and decisions have been made to not allow this.
3308 if (! type.isArray() && memberQualifier.hasLocation())
3309 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003310
John Kessenich5d610ee2018-03-07 18:05:55 -07003311 if (qualifier.hasLocation()) // track for upcoming inheritance
3312 locationOffset += glslangIntermediate->computeTypeLocationSize(
3313 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003314
John Kessenich5d610ee2018-03-07 18:05:55 -07003315 // component, XFB, others
3316 if (glslangMember.getQualifier().hasComponent())
3317 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3318 glslangMember.getQualifier().layoutComponent);
3319 if (glslangMember.getQualifier().hasXfbOffset())
3320 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3321 glslangMember.getQualifier().layoutXfbOffset);
3322 else if (explicitLayout != glslang::ElpNone) {
3323 // figure out what to do with offset, which is accumulating
3324 int nextOffset;
3325 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3326 if (offset >= 0)
3327 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3328 offset = nextOffset;
3329 }
John Kessenich6090df02016-06-30 21:18:02 -06003330
John Kessenich5d610ee2018-03-07 18:05:55 -07003331 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3332 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3333 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003334
John Kessenich5d610ee2018-03-07 18:05:55 -07003335 // built-in variable decorations
3336 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3337 if (builtIn != spv::BuiltInMax)
3338 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003339
John Kessenich5611c6d2018-04-05 11:25:02 -06003340 // nonuniform
3341 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3342
John Kessenichead86222018-03-28 18:01:20 -06003343 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3344 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3345 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3346 memberQualifier.semanticName);
3347 }
3348
chaoc771d89f2017-01-13 01:10:53 -08003349#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003350 if (builtIn == spv::BuiltInLayer) {
3351 // SPV_NV_viewport_array2 extension
3352 if (glslangMember.getQualifier().layoutViewportRelative){
3353 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3354 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3355 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003356 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003357 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3358 builder.addMemberDecoration(spvType, member,
3359 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3360 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3361 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3362 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003363 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003364 }
3365 if (glslangMember.getQualifier().layoutPassthrough) {
3366 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3367 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3368 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3369 }
chaoc771d89f2017-01-13 01:10:53 -08003370#endif
John Kessenich6090df02016-06-30 21:18:02 -06003371 }
3372
3373 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003374 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3375 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003376}
3377
John Kessenich6c292d32016-02-15 20:58:50 -07003378// Turn the expression forming the array size into an id.
3379// This is not quite trivial, because of specialization constants.
3380// Sometimes, a raw constant is turned into an Id, and sometimes
3381// a specialization constant expression is.
3382spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3383{
3384 // First, see if this is sized with a node, meaning a specialization constant:
3385 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3386 if (specNode != nullptr) {
3387 builder.clearAccessChain();
3388 specNode->traverse(this);
3389 return accessChainLoad(specNode->getAsTyped()->getType());
3390 }
qining25262b32016-05-06 17:25:16 -04003391
John Kessenich6c292d32016-02-15 20:58:50 -07003392 // Otherwise, need a compile-time (front end) size, get it:
3393 int size = arraySizes.getDimSize(dim);
3394 assert(size > 0);
3395 return builder.makeUintConstant(size);
3396}
3397
John Kessenich103bef92016-02-08 21:38:15 -07003398// Wrap the builder's accessChainLoad to:
3399// - localize handling of RelaxedPrecision
3400// - use the SPIR-V inferred type instead of another conversion of the glslang type
3401// (avoids unnecessary work and possible type punning for structures)
3402// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003403spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3404{
John Kessenich103bef92016-02-08 21:38:15 -07003405 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003406
3407 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3408 coherentFlags |= TranslateCoherent(type);
3409
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003410 unsigned int alignment = builder.getAccessChain().alignment;
3411 alignment |= getBufferReferenceAlignment(type);
3412
John Kessenich5611c6d2018-04-05 11:25:02 -06003413 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003414 TranslateNonUniformDecoration(type.getQualifier()),
3415 nominalTypeId,
3416 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003417 TranslateMemoryScope(coherentFlags),
3418 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003419
3420 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003421 if (type.getBasicType() == glslang::EbtBool) {
3422 if (builder.isScalarType(nominalTypeId)) {
3423 // Conversion for bool
3424 spv::Id boolType = builder.makeBoolType();
3425 if (nominalTypeId != boolType)
3426 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3427 } else if (builder.isVectorType(nominalTypeId)) {
3428 // Conversion for bvec
3429 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3430 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3431 if (nominalTypeId != bvecType)
3432 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3433 }
3434 }
John Kessenich103bef92016-02-08 21:38:15 -07003435
3436 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003437}
3438
Rex Xu27253232016-02-23 17:51:09 +08003439// Wrap the builder's accessChainStore to:
3440// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003441//
3442// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003443void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3444{
3445 // Need to convert to abstract types when necessary
3446 if (type.getBasicType() == glslang::EbtBool) {
3447 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3448
3449 if (builder.isScalarType(nominalTypeId)) {
3450 // Conversion for bool
3451 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003452 if (nominalTypeId != boolType) {
3453 // keep these outside arguments, for determinant order-of-evaluation
3454 spv::Id one = builder.makeUintConstant(1);
3455 spv::Id zero = builder.makeUintConstant(0);
3456 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3457 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003458 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003459 } else if (builder.isVectorType(nominalTypeId)) {
3460 // Conversion for bvec
3461 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3462 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003463 if (nominalTypeId != bvecType) {
3464 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003465 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3466 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3467 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003468 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003469 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3470 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003471 }
3472 }
3473
Jeff Bolz36831c92018-09-05 10:11:41 -05003474 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3475 coherentFlags |= TranslateCoherent(type);
3476
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003477 unsigned int alignment = builder.getAccessChain().alignment;
3478 alignment |= getBufferReferenceAlignment(type);
3479
Jeff Bolz36831c92018-09-05 10:11:41 -05003480 builder.accessChainStore(rvalue,
3481 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003482 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003483}
3484
John Kessenich4bf71552016-09-02 11:20:21 -06003485// For storing when types match at the glslang level, but not might match at the
3486// SPIR-V level.
3487//
3488// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003489// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003490// as in a member-decorated way.
3491//
3492// NOTE: This function can handle any store request; if it's not special it
3493// simplifies to a simple OpStore.
3494//
3495// Implicitly uses the existing builder.accessChain as the storage target.
3496void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3497{
John Kessenichb3e24e42016-09-11 12:33:43 -06003498 // we only do the complex path here if it's an aggregate
3499 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003500 accessChainStore(type, rValue);
3501 return;
3502 }
3503
John Kessenichb3e24e42016-09-11 12:33:43 -06003504 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003505 spv::Id rType = builder.getTypeId(rValue);
3506 spv::Id lValue = builder.accessChainGetLValue();
3507 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3508 if (lType == rType) {
3509 accessChainStore(type, rValue);
3510 return;
3511 }
3512
John Kessenichb3e24e42016-09-11 12:33:43 -06003513 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003514 // where the two types were the same type in GLSL. This requires member
3515 // by member copy, recursively.
3516
John Kessenichb3e24e42016-09-11 12:33:43 -06003517 // If an array, copy element by element.
3518 if (type.isArray()) {
3519 glslang::TType glslangElementType(type, 0);
3520 spv::Id elementRType = builder.getContainedTypeId(rType);
3521 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3522 // get the source member
3523 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003524
John Kessenichb3e24e42016-09-11 12:33:43 -06003525 // set up the target storage
3526 builder.clearAccessChain();
3527 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003528 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003529
John Kessenichb3e24e42016-09-11 12:33:43 -06003530 // store the member
3531 multiTypeStore(glslangElementType, elementRValue);
3532 }
3533 } else {
3534 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003535
John Kessenichb3e24e42016-09-11 12:33:43 -06003536 // loop over structure members
3537 const glslang::TTypeList& members = *type.getStruct();
3538 for (int m = 0; m < (int)members.size(); ++m) {
3539 const glslang::TType& glslangMemberType = *members[m].type;
3540
3541 // get the source member
3542 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3543 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3544
3545 // set up the target storage
3546 builder.clearAccessChain();
3547 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003548 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003549
3550 // store the member
3551 multiTypeStore(glslangMemberType, memberRValue);
3552 }
John Kessenich4bf71552016-09-02 11:20:21 -06003553 }
3554}
3555
John Kessenichf85e8062015-12-19 13:57:10 -07003556// Decide whether or not this type should be
3557// decorated with offsets and strides, and if so
3558// whether std140 or std430 rules should be applied.
3559glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003560{
John Kessenichf85e8062015-12-19 13:57:10 -07003561 // has to be a block
3562 if (type.getBasicType() != glslang::EbtBlock)
3563 return glslang::ElpNone;
3564
Chao Chen3c366992018-09-19 11:41:59 -07003565 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003566 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003567 type.getQualifier().storage != glslang::EvqBuffer &&
3568 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003569 return glslang::ElpNone;
3570
3571 // return the layout to use
3572 switch (type.getQualifier().layoutPacking) {
3573 case glslang::ElpStd140:
3574 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003575 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003576 return type.getQualifier().layoutPacking;
3577 default:
3578 return glslang::ElpNone;
3579 }
John Kessenich31ed4832015-09-09 17:51:38 -06003580}
3581
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003582// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003583int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003584{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003585 int size;
John Kessenich49987892015-12-29 17:11:44 -07003586 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003587 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003588
3589 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003590}
3591
John Kessenich49987892015-12-29 17:11:44 -07003592// 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 -07003593// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003594int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003595{
John Kessenich49987892015-12-29 17:11:44 -07003596 glslang::TType elementType;
3597 elementType.shallowCopy(matrixType);
3598 elementType.clearArraySizes();
3599
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003600 int size;
John Kessenich49987892015-12-29 17:11:44 -07003601 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003602 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003603
3604 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003605}
3606
John Kessenich5e4b1242015-08-06 22:53:06 -06003607// Given a member type of a struct, realign the current offset for it, and compute
3608// the next (not yet aligned) offset for the next member, which will get aligned
3609// on the next call.
3610// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3611// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3612// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003613void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003614 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003615{
3616 // this will get a positive value when deemed necessary
3617 nextOffset = -1;
3618
John Kessenich5e4b1242015-08-06 22:53:06 -06003619 // override anything in currentOffset with user-set offset
3620 if (memberType.getQualifier().hasOffset())
3621 currentOffset = memberType.getQualifier().layoutOffset;
3622
3623 // It could be that current linker usage in glslang updated all the layoutOffset,
3624 // in which case the following code does not matter. But, that's not quite right
3625 // once cross-compilation unit GLSL validation is done, as the original user
3626 // settings are needed in layoutOffset, and then the following will come into play.
3627
John Kessenichf85e8062015-12-19 13:57:10 -07003628 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003629 if (! memberType.getQualifier().hasOffset())
3630 currentOffset = -1;
3631
3632 return;
3633 }
3634
John Kessenichf85e8062015-12-19 13:57:10 -07003635 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003636 if (currentOffset < 0)
3637 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003638
John Kessenich5e4b1242015-08-06 22:53:06 -06003639 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3640 // but possibly not yet correctly aligned.
3641
3642 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003643 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003644 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003645
3646 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003647 // TODO: make this consistent in early phases of code:
3648 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3649 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3650 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003651 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003652 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003653 int dummySize;
3654 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3655 if (componentAlignment <= 4)
3656 memberAlignment = componentAlignment;
3657 }
3658
3659 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003660 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003661
3662 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003663 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003664 glslang::RoundToPow2(currentOffset, 16);
3665
John Kessenich5e4b1242015-08-06 22:53:06 -06003666 nextOffset = currentOffset + memberSize;
3667}
3668
David Netoa901ffe2016-06-08 14:11:40 +01003669void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003670{
David Netoa901ffe2016-06-08 14:11:40 +01003671 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3672 switch (glslangBuiltIn)
3673 {
3674 case glslang::EbvClipDistance:
3675 case glslang::EbvCullDistance:
3676 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003677#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003678 case glslang::EbvViewportMaskNV:
3679 case glslang::EbvSecondaryPositionNV:
3680 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003681 case glslang::EbvPositionPerViewNV:
3682 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003683 case glslang::EbvTaskCountNV:
3684 case glslang::EbvPrimitiveCountNV:
3685 case glslang::EbvPrimitiveIndicesNV:
3686 case glslang::EbvClipDistancePerViewNV:
3687 case glslang::EbvCullDistancePerViewNV:
3688 case glslang::EbvLayerPerViewNV:
3689 case glslang::EbvMeshViewCountNV:
3690 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003691#endif
David Netoa901ffe2016-06-08 14:11:40 +01003692 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3693 // Alternately, we could just call this for any glslang built-in, since the
3694 // capability already guards against duplicates.
3695 TranslateBuiltInDecoration(glslangBuiltIn, false);
3696 break;
3697 default:
3698 // Capabilities were already generated when the struct was declared.
3699 break;
3700 }
John Kessenichebb50532016-05-16 19:22:05 -06003701}
3702
John Kessenich6fccb3c2016-09-19 16:01:41 -06003703bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003704{
John Kessenicheee9d532016-09-19 18:09:30 -06003705 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003706}
3707
John Kessenichd41993d2017-09-10 15:21:05 -06003708// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003709// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3710// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003711bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003712{
John Kessenich6a14f782017-12-04 02:48:10 -07003713 assert(qualifier == glslang::EvqIn ||
3714 qualifier == glslang::EvqOut ||
3715 qualifier == glslang::EvqInOut ||
3716 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003717 return qualifier != glslang::EvqConstReadOnly;
3718}
3719
3720// Is parameter pass-by-original?
3721bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3722 bool implicitThisParam)
3723{
3724 if (implicitThisParam) // implicit this
3725 return true;
3726 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003727 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003728 return paramType.containsOpaque() || // sampler, etc.
3729 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3730}
3731
John Kessenich140f3df2015-06-26 16:58:36 -06003732// Make all the functions, skeletally, without actually visiting their bodies.
3733void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3734{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003735 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003736 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3737 if (paramPrecision != spv::NoPrecision)
3738 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003739 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003740 if (type.getBasicType() == glslang::EbtReference) {
3741 // Original and non-writable params pass the pointer directly and
3742 // use restrict/aliased, others are stored to a pointer in Function
3743 // memory and use RestrictPointer/AliasedPointer.
3744 if (originalParam(type.getQualifier().storage, type, false) ||
3745 !writableParam(type.getQualifier().storage)) {
3746 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3747 } else {
3748 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3749 }
3750 }
John Kessenichfad62972017-07-18 02:35:46 -06003751 };
3752
John Kessenich140f3df2015-06-26 16:58:36 -06003753 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3754 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003755 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003756 continue;
3757
3758 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003759 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003760 //
qining25262b32016-05-06 17:25:16 -04003761 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003762 // function. What it is an address of varies:
3763 //
John Kessenich4bf71552016-09-02 11:20:21 -06003764 // - "in" parameters not marked as "const" can be written to without modifying the calling
3765 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003766 //
3767 // - "const in" parameters can just be the r-value, as no writes need occur.
3768 //
John Kessenich4bf71552016-09-02 11:20:21 -06003769 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3770 // 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 -06003771
3772 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003773 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003774 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3775
John Kessenichfad62972017-07-18 02:35:46 -06003776 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3777 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003778
John Kessenichfad62972017-07-18 02:35:46 -06003779 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003780 for (int p = 0; p < (int)parameters.size(); ++p) {
3781 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3782 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003783 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003784 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003785 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003786 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3787 else
John Kessenich4bf71552016-09-02 11:20:21 -06003788 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003789 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003790 paramTypes.push_back(typeId);
3791 }
3792
3793 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003794 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3795 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003796 glslFunction->getName().c_str(), paramTypes,
3797 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003798 if (implicitThis)
3799 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003800
3801 // Track function to emit/call later
3802 functionMap[glslFunction->getName().c_str()] = function;
3803
3804 // Set the parameter id's
3805 for (int p = 0; p < (int)parameters.size(); ++p) {
3806 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3807 // give a name too
3808 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003809
3810 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3811 if (paramType.containsBasicType(glslang::EbtInt8) ||
3812 paramType.containsBasicType(glslang::EbtUint8))
3813 builder.addCapability(spv::CapabilityInt8);
3814 if (paramType.containsBasicType(glslang::EbtInt16) ||
3815 paramType.containsBasicType(glslang::EbtUint16))
3816 builder.addCapability(spv::CapabilityInt16);
3817 if (paramType.containsBasicType(glslang::EbtFloat16))
3818 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06003819 }
3820 }
3821}
3822
3823// Process all the initializers, while skipping the functions and link objects
3824void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3825{
3826 builder.setBuildPoint(shaderEntry->getLastBlock());
3827 for (int i = 0; i < (int)initializers.size(); ++i) {
3828 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3829 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3830
3831 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003832 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003833 initializer->traverse(this);
3834 }
3835 }
3836}
3837
3838// Process all the functions, while skipping initializers.
3839void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3840{
3841 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3842 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003843 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003844 node->traverse(this);
3845 }
3846}
3847
3848void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3849{
qining25262b32016-05-06 17:25:16 -04003850 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003851 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003852 currentFunction = functionMap[node->getName().c_str()];
3853 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003854 builder.setBuildPoint(functionBlock);
3855}
3856
Rex Xu04db3f52015-09-16 11:44:02 +08003857void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003858{
Rex Xufc618912015-09-09 16:42:49 +08003859 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003860
3861 glslang::TSampler sampler = {};
3862 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003863#ifdef AMD_EXTENSIONS
3864 bool f16ShadowCompare = false;
3865#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003866 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003867 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3868 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003869#ifdef AMD_EXTENSIONS
3870 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3871#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003872 }
3873
John Kessenich140f3df2015-06-26 16:58:36 -06003874 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3875 builder.clearAccessChain();
3876 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003877
3878 // Special case l-value operands
3879 bool lvalue = false;
3880 switch (node.getOp()) {
3881 case glslang::EOpImageAtomicAdd:
3882 case glslang::EOpImageAtomicMin:
3883 case glslang::EOpImageAtomicMax:
3884 case glslang::EOpImageAtomicAnd:
3885 case glslang::EOpImageAtomicOr:
3886 case glslang::EOpImageAtomicXor:
3887 case glslang::EOpImageAtomicExchange:
3888 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003889 case glslang::EOpImageAtomicLoad:
3890 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003891 if (i == 0)
3892 lvalue = true;
3893 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003894 case glslang::EOpSparseImageLoad:
3895 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3896 lvalue = true;
3897 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003898#ifdef AMD_EXTENSIONS
3899 case glslang::EOpSparseTexture:
3900 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3901 lvalue = true;
3902 break;
3903 case glslang::EOpSparseTextureClamp:
3904 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3905 lvalue = true;
3906 break;
3907 case glslang::EOpSparseTextureLod:
3908 case glslang::EOpSparseTextureOffset:
3909 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3910 lvalue = true;
3911 break;
3912#else
Rex Xu48edadf2015-12-31 16:11:41 +08003913 case glslang::EOpSparseTexture:
3914 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3915 lvalue = true;
3916 break;
3917 case glslang::EOpSparseTextureClamp:
3918 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3919 lvalue = true;
3920 break;
3921 case glslang::EOpSparseTextureLod:
3922 case glslang::EOpSparseTextureOffset:
3923 if (i == 3)
3924 lvalue = true;
3925 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003926#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003927 case glslang::EOpSparseTextureFetch:
3928 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3929 lvalue = true;
3930 break;
3931 case glslang::EOpSparseTextureFetchOffset:
3932 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3933 lvalue = true;
3934 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003935#ifdef AMD_EXTENSIONS
3936 case glslang::EOpSparseTextureLodOffset:
3937 case glslang::EOpSparseTextureGrad:
3938 case glslang::EOpSparseTextureOffsetClamp:
3939 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3940 lvalue = true;
3941 break;
3942 case glslang::EOpSparseTextureGradOffset:
3943 case glslang::EOpSparseTextureGradClamp:
3944 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3945 lvalue = true;
3946 break;
3947 case glslang::EOpSparseTextureGradOffsetClamp:
3948 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3949 lvalue = true;
3950 break;
3951#else
Rex Xu48edadf2015-12-31 16:11:41 +08003952 case glslang::EOpSparseTextureLodOffset:
3953 case glslang::EOpSparseTextureGrad:
3954 case glslang::EOpSparseTextureOffsetClamp:
3955 if (i == 4)
3956 lvalue = true;
3957 break;
3958 case glslang::EOpSparseTextureGradOffset:
3959 case glslang::EOpSparseTextureGradClamp:
3960 if (i == 5)
3961 lvalue = true;
3962 break;
3963 case glslang::EOpSparseTextureGradOffsetClamp:
3964 if (i == 6)
3965 lvalue = true;
3966 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003967#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003968 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003969 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3970 lvalue = true;
3971 break;
3972 case glslang::EOpSparseTextureGatherOffset:
3973 case glslang::EOpSparseTextureGatherOffsets:
3974 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3975 lvalue = true;
3976 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003977#ifdef AMD_EXTENSIONS
3978 case glslang::EOpSparseTextureGatherLod:
3979 if (i == 3)
3980 lvalue = true;
3981 break;
3982 case glslang::EOpSparseTextureGatherLodOffset:
3983 case glslang::EOpSparseTextureGatherLodOffsets:
3984 if (i == 4)
3985 lvalue = true;
3986 break;
Rex Xu129799a2017-07-05 17:23:28 +08003987 case glslang::EOpSparseImageLoadLod:
3988 if (i == 3)
3989 lvalue = true;
3990 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003991#endif
Chao Chen3a137962018-09-19 11:41:27 -07003992#ifdef NV_EXTENSIONS
3993 case glslang::EOpImageSampleFootprintNV:
3994 if (i == 4)
3995 lvalue = true;
3996 break;
3997 case glslang::EOpImageSampleFootprintClampNV:
3998 case glslang::EOpImageSampleFootprintLodNV:
3999 if (i == 5)
4000 lvalue = true;
4001 break;
4002 case glslang::EOpImageSampleFootprintGradNV:
4003 if (i == 6)
4004 lvalue = true;
4005 break;
4006 case glslang::EOpImageSampleFootprintGradClampNV:
4007 if (i == 7)
4008 lvalue = true;
4009 break;
4010#endif
Rex Xufc618912015-09-09 16:42:49 +08004011 default:
4012 break;
4013 }
4014
Rex Xu6b86d492015-09-16 17:48:22 +08004015 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004016 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004017 else
John Kessenich32cfd492016-02-02 12:37:46 -07004018 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004019 }
4020}
4021
John Kessenichfc51d282015-08-19 13:34:18 -06004022void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004023{
John Kessenichfc51d282015-08-19 13:34:18 -06004024 builder.clearAccessChain();
4025 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004026 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004027}
John Kessenich140f3df2015-06-26 16:58:36 -06004028
John Kessenichfc51d282015-08-19 13:34:18 -06004029spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4030{
John Kesseniche485c7a2017-05-31 18:50:53 -06004031 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004032 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004033
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004034 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004035
John Kessenichfc51d282015-08-19 13:34:18 -06004036 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004037
4038 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4039 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4040 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004041#ifdef AMD_EXTENSIONS
4042 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4043 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4044 : false;
4045#endif
4046
John Kessenichfc51d282015-08-19 13:34:18 -06004047 std::vector<spv::Id> arguments;
4048 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004049 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004050 else
4051 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004052 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004053
4054 spv::Builder::TextureParameters params = { };
4055 params.sampler = arguments[0];
4056
Rex Xu04db3f52015-09-16 11:44:02 +08004057 glslang::TCrackedTextureOp cracked;
4058 node->crackTexture(sampler, cracked);
4059
amhagan05506bb2017-06-13 16:53:02 -04004060 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004061
John Kessenichfc51d282015-08-19 13:34:18 -06004062 // Check for queries
4063 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004064 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4065 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004066 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004067
John Kessenichfc51d282015-08-19 13:34:18 -06004068 switch (node->getOp()) {
4069 case glslang::EOpImageQuerySize:
4070 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004071 if (arguments.size() > 1) {
4072 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004073 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004074 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004075 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004076 case glslang::EOpImageQuerySamples:
4077 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004078 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004079 case glslang::EOpTextureQueryLod:
4080 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004081 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004082 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004083 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004084 case glslang::EOpSparseTexelsResident:
4085 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004086 default:
4087 assert(0);
4088 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004089 }
John Kessenich140f3df2015-06-26 16:58:36 -06004090 }
4091
LoopDawg4425f242018-02-18 11:40:01 -07004092 int components = node->getType().getVectorSize();
4093
4094 if (node->getOp() == glslang::EOpTextureFetch) {
4095 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4096 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4097 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4098 // here around e.g. which ones return scalars or other types.
4099 components = 4;
4100 }
4101
4102 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4103
4104 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4105
Rex Xufc618912015-09-09 16:42:49 +08004106 // Check for image functions other than queries
4107 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004108 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004109 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004110 spv::IdImmediate image = { true, *(opIt++) };
4111 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004112
4113 // Handle subpass operations
4114 // TODO: GLSL should change to have the "MS" only on the type rather than the
4115 // built-in function.
4116 if (cracked.subpass) {
4117 // add on the (0,0) coordinate
4118 spv::Id zero = builder.makeIntConstant(0);
4119 std::vector<spv::Id> comps;
4120 comps.push_back(zero);
4121 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004122 spv::IdImmediate coord = { true,
4123 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4124 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004125 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004126 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4127 operands.push_back(imageOperands);
4128 spv::IdImmediate imageOperand = { true, *(opIt++) };
4129 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004130 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004131 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4132 builder.setPrecision(result, precision);
4133 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004134 }
4135
John Kessenich149afc32018-08-14 13:31:43 -06004136 spv::IdImmediate coord = { true, *(opIt++) };
4137 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004138#ifdef AMD_EXTENSIONS
4139 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4140#else
John Kessenich56bab042015-09-16 10:54:31 -06004141 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004142#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004143 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004144 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004145 mask = mask | spv::ImageOperandsSampleMask;
4146 }
Rex Xu129799a2017-07-05 17:23:28 +08004147#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004148 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004149 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4150 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004151 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004152 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004153#endif
4154 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4155 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4156 if (mask) {
4157 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4158 operands.push_back(imageOperands);
4159 }
4160 if (mask & spv::ImageOperandsSampleMask) {
4161 spv::IdImmediate imageOperand = { true, *opIt++ };
4162 operands.push_back(imageOperand);
4163 }
4164#ifdef AMD_EXTENSIONS
4165 if (mask & spv::ImageOperandsLodMask) {
4166 spv::IdImmediate imageOperand = { true, *opIt++ };
4167 operands.push_back(imageOperand);
4168 }
4169#endif
4170 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4171 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4172 operands.push_back(imageOperand);
4173 }
4174
John Kessenich149afc32018-08-14 13:31:43 -06004175 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004176 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004177
John Kessenich149afc32018-08-14 13:31:43 -06004178 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004179 builder.setPrecision(result[0], precision);
4180
4181 // If needed, add a conversion constructor to the proper size.
4182 if (components != node->getType().getVectorSize())
4183 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4184
4185 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004186#ifdef AMD_EXTENSIONS
4187 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4188#else
John Kessenich56bab042015-09-16 10:54:31 -06004189 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004190#endif
Rex Xu129799a2017-07-05 17:23:28 +08004191
Jeff Bolz36831c92018-09-05 10:11:41 -05004192 // Push the texel value before the operands
4193#ifdef AMD_EXTENSIONS
4194 if (sampler.ms || cracked.lod) {
4195#else
4196 if (sampler.ms) {
4197#endif
John Kessenich149afc32018-08-14 13:31:43 -06004198 spv::IdImmediate texel = { true, *(opIt + 1) };
4199 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004200 } else {
4201 spv::IdImmediate texel = { true, *opIt };
4202 operands.push_back(texel);
4203 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004204
4205 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4206 if (sampler.ms) {
4207 mask = mask | spv::ImageOperandsSampleMask;
4208 }
4209#ifdef AMD_EXTENSIONS
4210 if (cracked.lod) {
4211 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4212 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4213 mask = mask | spv::ImageOperandsLodMask;
4214 }
4215#endif
4216 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4217 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4218 if (mask) {
4219 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4220 operands.push_back(imageOperands);
4221 }
4222 if (mask & spv::ImageOperandsSampleMask) {
4223 spv::IdImmediate imageOperand = { true, *opIt++ };
4224 operands.push_back(imageOperand);
4225 }
4226#ifdef AMD_EXTENSIONS
4227 if (mask & spv::ImageOperandsLodMask) {
4228 spv::IdImmediate imageOperand = { true, *opIt++ };
4229 operands.push_back(imageOperand);
4230 }
4231#endif
4232 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4233 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4234 operands.push_back(imageOperand);
4235 }
4236
John Kessenich56bab042015-09-16 10:54:31 -06004237 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004238 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004239 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004240 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004241#ifdef AMD_EXTENSIONS
4242 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4243#else
Rex Xu5eafa472016-02-19 22:24:03 +08004244 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004245#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004246 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004247 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004248 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4249
Jeff Bolz36831c92018-09-05 10:11:41 -05004250 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004251 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004252 mask = mask | spv::ImageOperandsSampleMask;
4253 }
Rex Xu129799a2017-07-05 17:23:28 +08004254#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004255 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004256 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4257 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4258
Jeff Bolz36831c92018-09-05 10:11:41 -05004259 mask = mask | spv::ImageOperandsLodMask;
4260 }
4261#endif
4262 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4263 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4264 if (mask) {
4265 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004266 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004267 }
4268 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004269 spv::IdImmediate imageOperand = { true, *opIt++ };
4270 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004271 }
4272#ifdef AMD_EXTENSIONS
4273 if (mask & spv::ImageOperandsLodMask) {
4274 spv::IdImmediate imageOperand = { true, *opIt++ };
4275 operands.push_back(imageOperand);
4276 }
Rex Xu129799a2017-07-05 17:23:28 +08004277#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004278 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4279 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4280 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004281 }
4282
4283 // Create the return type that was a special structure
4284 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004285 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004286 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4287 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4288
4289 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4290
4291 // Decode the return type
4292 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4293 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004294 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004295 // Process image atomic operations
4296
4297 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4298 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004299 // For non-MS, the sample value should be 0
4300 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4301 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004302
Jeff Bolz36831c92018-09-05 10:11:41 -05004303 spv::Id resultTypeId;
4304 // imageAtomicStore has a void return type so base the pointer type on
4305 // the type of the value operand.
4306 if (node->getOp() == glslang::EOpImageAtomicStore) {
4307 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4308 } else {
4309 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4310 }
John Kessenich56bab042015-09-16 10:54:31 -06004311 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004312
4313 std::vector<spv::Id> operands;
4314 operands.push_back(pointer);
4315 for (; opIt != arguments.end(); ++opIt)
4316 operands.push_back(*opIt);
4317
John Kessenich8c8505c2016-07-26 12:50:38 -06004318 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004319 }
4320 }
4321
amhagan05506bb2017-06-13 16:53:02 -04004322#ifdef AMD_EXTENSIONS
4323 // Check for fragment mask functions other than queries
4324 if (cracked.fragMask) {
4325 assert(sampler.ms);
4326
4327 auto opIt = arguments.begin();
4328 std::vector<spv::Id> operands;
4329
4330 // Extract the image if necessary
4331 if (builder.isSampledImage(params.sampler))
4332 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4333
4334 operands.push_back(params.sampler);
4335 ++opIt;
4336
4337 if (sampler.isSubpass()) {
4338 // add on the (0,0) coordinate
4339 spv::Id zero = builder.makeIntConstant(0);
4340 std::vector<spv::Id> comps;
4341 comps.push_back(zero);
4342 comps.push_back(zero);
4343 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4344 }
4345
4346 for (; opIt != arguments.end(); ++opIt)
4347 operands.push_back(*opIt);
4348
4349 spv::Op fragMaskOp = spv::OpNop;
4350 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4351 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4352 else if (node->getOp() == glslang::EOpFragmentFetch)
4353 fragMaskOp = spv::OpFragmentFetchAMD;
4354
4355 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4356 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4357 return builder.createOp(fragMaskOp, resultType(), operands);
4358 }
4359#endif
4360
Rex Xufc618912015-09-09 16:42:49 +08004361 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004362 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004363#ifdef NV_EXTENSIONS
4364 bool imageFootprint = node->isImageFootprint();
4365#endif
4366
Rex Xu71519fe2015-11-11 15:35:47 +08004367 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4368
John Kessenichfc51d282015-08-19 13:34:18 -06004369 // check for bias argument
4370 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004371#ifdef AMD_EXTENSIONS
4372 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4373#else
Rex Xu71519fe2015-11-11 15:35:47 +08004374 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004375#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004376 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004377#ifdef AMD_EXTENSIONS
4378 if (cracked.gather)
4379 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004380
4381 if (f16ShadowCompare)
4382 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004383#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004384 if (cracked.offset)
4385 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004386#ifdef AMD_EXTENSIONS
4387 else if (cracked.offsets)
4388 ++nonBiasArgCount;
4389#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004390 if (cracked.grad)
4391 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004392 if (cracked.lodClamp)
4393 ++nonBiasArgCount;
4394 if (sparse)
4395 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004396#ifdef NV_EXTENSIONS
4397 if (imageFootprint)
4398 //Following three extra arguments
4399 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4400 nonBiasArgCount += 3;
4401#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004402 if ((int)arguments.size() > nonBiasArgCount)
4403 bias = true;
4404 }
4405
John Kessenicha5c33d62016-06-02 23:45:21 -06004406 // See if the sampler param should really be just the SPV image part
4407 if (cracked.fetch) {
4408 // a fetch needs to have the image extracted first
4409 if (builder.isSampledImage(params.sampler))
4410 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4411 }
4412
Rex Xu225e0fc2016-11-17 17:47:59 +08004413#ifdef AMD_EXTENSIONS
4414 if (cracked.gather) {
4415 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4416 if (bias || cracked.lod ||
4417 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4418 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004419 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004420 }
4421 }
4422#endif
4423
John Kessenichfc51d282015-08-19 13:34:18 -06004424 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004425
John Kessenichfc51d282015-08-19 13:34:18 -06004426 params.coords = arguments[1];
4427 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004428 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004429
4430 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004431#ifdef AMD_EXTENSIONS
4432 if (cubeCompare || f16ShadowCompare) {
4433#else
Rex Xu48edadf2015-12-31 16:11:41 +08004434 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004435#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004436 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004437 ++extraArgs;
4438 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004439 params.Dref = arguments[2];
4440 ++extraArgs;
4441 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004442 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004443 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004444 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004445 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004446 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004447 dRefComp = builder.getNumComponents(params.coords) - 1;
4448 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004449 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4450 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004451
4452 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004453 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004454 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004455 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004456 } else if (glslangIntermediate->getStage() != EShLangFragment
4457#ifdef NV_EXTENSIONS
4458 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4459 && !(glslangIntermediate->getStage() == EShLangCompute &&
4460 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4461#endif
4462 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004463 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4464 noImplicitLod = true;
4465 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004466
4467 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004468 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004469 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004470 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004471 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004472
4473 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004474 if (cracked.grad) {
4475 params.gradX = arguments[2 + extraArgs];
4476 params.gradY = arguments[3 + extraArgs];
4477 extraArgs += 2;
4478 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004479
4480 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004481 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004482 params.offset = arguments[2 + extraArgs];
4483 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004484 } else if (cracked.offsets) {
4485 params.offsets = arguments[2 + extraArgs];
4486 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004487 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004488
4489 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004490 if (cracked.lodClamp) {
4491 params.lodClamp = arguments[2 + extraArgs];
4492 ++extraArgs;
4493 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004494 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004495 if (sparse) {
4496 params.texelOut = arguments[2 + extraArgs];
4497 ++extraArgs;
4498 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004499
John Kessenich76d4dfc2016-06-16 12:43:23 -06004500 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004501 if (cracked.gather && ! sampler.shadow) {
4502 // default component is 0, if missing, otherwise an argument
4503 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004504 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004505 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004506 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004507 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004508 }
Chao Chen3a137962018-09-19 11:41:27 -07004509#ifdef NV_EXTENSIONS
4510 spv::Id resultStruct = spv::NoResult;
4511 if (imageFootprint) {
4512 //Following three extra arguments
4513 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4514 params.granularity = arguments[2 + extraArgs];
4515 params.coarse = arguments[3 + extraArgs];
4516 resultStruct = arguments[4 + extraArgs];
4517 extraArgs += 3;
4518 }
4519#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004520 // bias
4521 if (bias) {
4522 params.bias = arguments[2 + extraArgs];
4523 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004524 }
John Kessenichfc51d282015-08-19 13:34:18 -06004525
Chao Chen3a137962018-09-19 11:41:27 -07004526#ifdef NV_EXTENSIONS
4527 if (imageFootprint) {
4528 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4529 builder.addCapability(spv::CapabilityImageFootprintNV);
4530
4531
4532 //resultStructType(OpenGL type) contains 5 elements:
4533 //struct gl_TextureFootprint2DNV {
4534 // uvec2 anchor;
4535 // uvec2 offset;
4536 // uvec2 mask;
4537 // uint lod;
4538 // uint granularity;
4539 //};
4540 //or
4541 //struct gl_TextureFootprint3DNV {
4542 // uvec3 anchor;
4543 // uvec3 offset;
4544 // uvec2 mask;
4545 // uint lod;
4546 // uint granularity;
4547 //};
4548 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4549 assert(builder.isStructType(resultStructType));
4550
4551 //resType (SPIR-V type) contains 6 elements:
4552 //Member 0 must be a Boolean type scalar(LOD),
4553 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4554 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4555 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4556 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4557 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4558 std::vector<spv::Id> members;
4559 members.push_back(resultType());
4560 for (int i = 0; i < 5; i++) {
4561 members.push_back(builder.getContainedTypeId(resultStructType, i));
4562 }
4563 spv::Id resType = builder.makeStructType(members, "ResType");
4564
4565 //call ImageFootprintNV
4566 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4567
4568 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4569 for (int i = 0; i < 5; i++) {
4570 builder.clearAccessChain();
4571 builder.setAccessChainLValue(resultStruct);
4572
4573 //Accessing to a struct we created, no coherent flag is set
4574 spv::Builder::AccessChain::CoherentFlags flags;
4575 flags.clear();
4576
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004577 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004578 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4579 }
4580 return builder.createCompositeExtract(res, resultType(), 0);
4581 }
4582#endif
4583
John Kessenich65336482016-06-16 14:06:26 -06004584 // projective component (might not to move)
4585 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4586 // are divided by the last component of P."
4587 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4588 // unused components will appear after all used components."
4589 if (cracked.proj) {
4590 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4591 int projTargetComp;
4592 switch (sampler.dim) {
4593 case glslang::Esd1D: projTargetComp = 1; break;
4594 case glslang::Esd2D: projTargetComp = 2; break;
4595 case glslang::EsdRect: projTargetComp = 2; break;
4596 default: projTargetComp = projSourceComp; break;
4597 }
4598 // copy the projective coordinate if we have to
4599 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004600 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004601 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4602 projSourceComp);
4603 params.coords = builder.createCompositeInsert(projComp, params.coords,
4604 builder.getTypeId(params.coords), projTargetComp);
4605 }
4606 }
4607
Jeff Bolz36831c92018-09-05 10:11:41 -05004608 // nonprivate
4609 if (imageType.getQualifier().nonprivate) {
4610 params.nonprivate = true;
4611 }
4612
4613 // volatile
4614 if (imageType.getQualifier().volatil) {
4615 params.volatil = true;
4616 }
4617
St0fFa1184dd2018-04-09 21:08:14 +02004618 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004619 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004620 );
LoopDawg4425f242018-02-18 11:40:01 -07004621
4622 if (components != node->getType().getVectorSize())
4623 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4624
4625 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004626}
4627
4628spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4629{
4630 // Grab the function's pointer from the previously created function
4631 spv::Function* function = functionMap[node->getName().c_str()];
4632 if (! function)
4633 return 0;
4634
4635 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4636 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4637
4638 // See comments in makeFunctions() for details about the semantics for parameter passing.
4639 //
4640 // These imply we need a four step process:
4641 // 1. Evaluate the arguments
4642 // 2. Allocate and make copies of in, out, and inout arguments
4643 // 3. Make the call
4644 // 4. Copy back the results
4645
John Kessenichd3ed90b2018-05-04 11:43:03 -06004646 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004647 std::vector<spv::Builder::AccessChain> lValues;
4648 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004649 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004650 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004651 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004652 // build l-value
4653 builder.clearAccessChain();
4654 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004655 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004656 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004657 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004658 // save l-value
4659 lValues.push_back(builder.getAccessChain());
4660 } else {
4661 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004662 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004663 }
4664 }
4665
4666 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4667 // copy the original into that space.
4668 //
4669 // Also, build up the list of actual arguments to pass in for the call
4670 int lValueCount = 0;
4671 int rValueCount = 0;
4672 std::vector<spv::Id> spvArgs;
4673 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4674 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004675 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004676 builder.setAccessChain(lValues[lValueCount]);
4677 arg = builder.accessChainGetLValue();
4678 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004679 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004680 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004681 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004682 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4683 // need to copy the input into output space
4684 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004685 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004686 builder.clearAccessChain();
4687 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004688 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004689 }
4690 ++lValueCount;
4691 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004692 // process r-value, which involves a copy for a type mismatch
4693 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4694 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4695 builder.clearAccessChain();
4696 builder.setAccessChainLValue(argCopy);
4697 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4698 arg = builder.createLoad(argCopy);
4699 } else
4700 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004701 ++rValueCount;
4702 }
4703 spvArgs.push_back(arg);
4704 }
4705
4706 // 3. Make the call.
4707 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004708 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004709
4710 // 4. Copy back out an "out" arguments.
4711 lValueCount = 0;
4712 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004713 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004714 ++lValueCount;
4715 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004716 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4717 spv::Id copy = builder.createLoad(spvArgs[a]);
4718 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004719 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004720 }
4721 ++lValueCount;
4722 }
4723 }
4724
4725 return result;
4726}
4727
4728// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004729spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004730 spv::Id typeId, spv::Id left, spv::Id right,
4731 glslang::TBasicType typeProxy, bool reduceComparison)
4732{
John Kessenich66011cb2018-03-06 16:12:04 -07004733 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4734 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004735 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004736
4737 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004738 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004739 bool comparison = false;
4740
4741 switch (op) {
4742 case glslang::EOpAdd:
4743 case glslang::EOpAddAssign:
4744 if (isFloat)
4745 binOp = spv::OpFAdd;
4746 else
4747 binOp = spv::OpIAdd;
4748 break;
4749 case glslang::EOpSub:
4750 case glslang::EOpSubAssign:
4751 if (isFloat)
4752 binOp = spv::OpFSub;
4753 else
4754 binOp = spv::OpISub;
4755 break;
4756 case glslang::EOpMul:
4757 case glslang::EOpMulAssign:
4758 if (isFloat)
4759 binOp = spv::OpFMul;
4760 else
4761 binOp = spv::OpIMul;
4762 break;
4763 case glslang::EOpVectorTimesScalar:
4764 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004765 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004766 if (builder.isVector(right))
4767 std::swap(left, right);
4768 assert(builder.isScalar(right));
4769 needMatchingVectors = false;
4770 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004771 } else if (isFloat)
4772 binOp = spv::OpFMul;
4773 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004774 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004775 break;
4776 case glslang::EOpVectorTimesMatrix:
4777 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004778 binOp = spv::OpVectorTimesMatrix;
4779 break;
4780 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004781 binOp = spv::OpMatrixTimesVector;
4782 break;
4783 case glslang::EOpMatrixTimesScalar:
4784 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004785 binOp = spv::OpMatrixTimesScalar;
4786 break;
4787 case glslang::EOpMatrixTimesMatrix:
4788 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004789 binOp = spv::OpMatrixTimesMatrix;
4790 break;
4791 case glslang::EOpOuterProduct:
4792 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004793 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004794 break;
4795
4796 case glslang::EOpDiv:
4797 case glslang::EOpDivAssign:
4798 if (isFloat)
4799 binOp = spv::OpFDiv;
4800 else if (isUnsigned)
4801 binOp = spv::OpUDiv;
4802 else
4803 binOp = spv::OpSDiv;
4804 break;
4805 case glslang::EOpMod:
4806 case glslang::EOpModAssign:
4807 if (isFloat)
4808 binOp = spv::OpFMod;
4809 else if (isUnsigned)
4810 binOp = spv::OpUMod;
4811 else
4812 binOp = spv::OpSMod;
4813 break;
4814 case glslang::EOpRightShift:
4815 case glslang::EOpRightShiftAssign:
4816 if (isUnsigned)
4817 binOp = spv::OpShiftRightLogical;
4818 else
4819 binOp = spv::OpShiftRightArithmetic;
4820 break;
4821 case glslang::EOpLeftShift:
4822 case glslang::EOpLeftShiftAssign:
4823 binOp = spv::OpShiftLeftLogical;
4824 break;
4825 case glslang::EOpAnd:
4826 case glslang::EOpAndAssign:
4827 binOp = spv::OpBitwiseAnd;
4828 break;
4829 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004830 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004831 binOp = spv::OpLogicalAnd;
4832 break;
4833 case glslang::EOpInclusiveOr:
4834 case glslang::EOpInclusiveOrAssign:
4835 binOp = spv::OpBitwiseOr;
4836 break;
4837 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004838 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004839 binOp = spv::OpLogicalOr;
4840 break;
4841 case glslang::EOpExclusiveOr:
4842 case glslang::EOpExclusiveOrAssign:
4843 binOp = spv::OpBitwiseXor;
4844 break;
4845 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004846 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004847 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004848 break;
4849
4850 case glslang::EOpLessThan:
4851 case glslang::EOpGreaterThan:
4852 case glslang::EOpLessThanEqual:
4853 case glslang::EOpGreaterThanEqual:
4854 case glslang::EOpEqual:
4855 case glslang::EOpNotEqual:
4856 case glslang::EOpVectorEqual:
4857 case glslang::EOpVectorNotEqual:
4858 comparison = true;
4859 break;
4860 default:
4861 break;
4862 }
4863
John Kessenich7c1aa102015-10-15 13:29:11 -06004864 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004865 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004866 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004867 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004868 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004869
4870 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004871 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004872 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004873
qining25262b32016-05-06 17:25:16 -04004874 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004875 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004876 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004877 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004878 }
4879
4880 if (! comparison)
4881 return 0;
4882
John Kessenich7c1aa102015-10-15 13:29:11 -06004883 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004884
John Kessenich4583b612016-08-07 19:14:22 -06004885 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004886 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4887 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004888 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004889 return result;
4890 }
John Kessenich140f3df2015-06-26 16:58:36 -06004891
4892 switch (op) {
4893 case glslang::EOpLessThan:
4894 if (isFloat)
4895 binOp = spv::OpFOrdLessThan;
4896 else if (isUnsigned)
4897 binOp = spv::OpULessThan;
4898 else
4899 binOp = spv::OpSLessThan;
4900 break;
4901 case glslang::EOpGreaterThan:
4902 if (isFloat)
4903 binOp = spv::OpFOrdGreaterThan;
4904 else if (isUnsigned)
4905 binOp = spv::OpUGreaterThan;
4906 else
4907 binOp = spv::OpSGreaterThan;
4908 break;
4909 case glslang::EOpLessThanEqual:
4910 if (isFloat)
4911 binOp = spv::OpFOrdLessThanEqual;
4912 else if (isUnsigned)
4913 binOp = spv::OpULessThanEqual;
4914 else
4915 binOp = spv::OpSLessThanEqual;
4916 break;
4917 case glslang::EOpGreaterThanEqual:
4918 if (isFloat)
4919 binOp = spv::OpFOrdGreaterThanEqual;
4920 else if (isUnsigned)
4921 binOp = spv::OpUGreaterThanEqual;
4922 else
4923 binOp = spv::OpSGreaterThanEqual;
4924 break;
4925 case glslang::EOpEqual:
4926 case glslang::EOpVectorEqual:
4927 if (isFloat)
4928 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004929 else if (isBool)
4930 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004931 else
4932 binOp = spv::OpIEqual;
4933 break;
4934 case glslang::EOpNotEqual:
4935 case glslang::EOpVectorNotEqual:
4936 if (isFloat)
4937 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004938 else if (isBool)
4939 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004940 else
4941 binOp = spv::OpINotEqual;
4942 break;
4943 default:
4944 break;
4945 }
4946
qining25262b32016-05-06 17:25:16 -04004947 if (binOp != spv::OpNop) {
4948 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004949 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004950 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004951 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004952 }
John Kessenich140f3df2015-06-26 16:58:36 -06004953
4954 return 0;
4955}
4956
John Kessenich04bb8a02015-12-12 12:28:14 -07004957//
4958// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4959// These can be any of:
4960//
4961// matrix * scalar
4962// scalar * matrix
4963// matrix * matrix linear algebraic
4964// matrix * vector
4965// vector * matrix
4966// matrix * matrix componentwise
4967// matrix op matrix op in {+, -, /}
4968// matrix op scalar op in {+, -, /}
4969// scalar op matrix op in {+, -, /}
4970//
John Kessenichead86222018-03-28 18:01:20 -06004971spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4972 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004973{
4974 bool firstClass = true;
4975
4976 // First, handle first-class matrix operations (* and matrix/scalar)
4977 switch (op) {
4978 case spv::OpFDiv:
4979 if (builder.isMatrix(left) && builder.isScalar(right)) {
4980 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004981 spv::Id resultType = builder.getTypeId(right);
4982 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004983 op = spv::OpMatrixTimesScalar;
4984 } else
4985 firstClass = false;
4986 break;
4987 case spv::OpMatrixTimesScalar:
4988 if (builder.isMatrix(right))
4989 std::swap(left, right);
4990 assert(builder.isScalar(right));
4991 break;
4992 case spv::OpVectorTimesMatrix:
4993 assert(builder.isVector(left));
4994 assert(builder.isMatrix(right));
4995 break;
4996 case spv::OpMatrixTimesVector:
4997 assert(builder.isMatrix(left));
4998 assert(builder.isVector(right));
4999 break;
5000 case spv::OpMatrixTimesMatrix:
5001 assert(builder.isMatrix(left));
5002 assert(builder.isMatrix(right));
5003 break;
5004 default:
5005 firstClass = false;
5006 break;
5007 }
5008
qining25262b32016-05-06 17:25:16 -04005009 if (firstClass) {
5010 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005011 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005012 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005013 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005014 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005015
LoopDawg592860c2016-06-09 08:57:35 -06005016 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005017 // The result type of all of them is the same type as the (a) matrix operand.
5018 // The algorithm is to:
5019 // - break the matrix(es) into vectors
5020 // - smear any scalar to a vector
5021 // - do vector operations
5022 // - make a matrix out the vector results
5023 switch (op) {
5024 case spv::OpFAdd:
5025 case spv::OpFSub:
5026 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005027 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005028 case spv::OpFMul:
5029 {
5030 // one time set up...
5031 bool leftMat = builder.isMatrix(left);
5032 bool rightMat = builder.isMatrix(right);
5033 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5034 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5035 spv::Id scalarType = builder.getScalarTypeId(typeId);
5036 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5037 std::vector<spv::Id> results;
5038 spv::Id smearVec = spv::NoResult;
5039 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005040 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005041 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005042 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005043
5044 // do each vector op
5045 for (unsigned int c = 0; c < numCols; ++c) {
5046 std::vector<unsigned int> indexes;
5047 indexes.push_back(c);
5048 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5049 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005050 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005051 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005052 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005053 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005054 }
5055
5056 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005057 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005058 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005059 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005060 }
5061 default:
5062 assert(0);
5063 return spv::NoResult;
5064 }
5065}
5066
John Kessenichead86222018-03-28 18:01:20 -06005067spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5068 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005069{
5070 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005071 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005072 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005073 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5074 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005075
5076 switch (op) {
5077 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005078 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005079 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005080 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005081 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005082 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005083 unaryOp = spv::OpSNegate;
5084 break;
5085
5086 case glslang::EOpLogicalNot:
5087 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005088 unaryOp = spv::OpLogicalNot;
5089 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005090 case glslang::EOpBitwiseNot:
5091 unaryOp = spv::OpNot;
5092 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005093
John Kessenich140f3df2015-06-26 16:58:36 -06005094 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005095 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005096 break;
5097 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005098 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005099 break;
5100 case glslang::EOpTranspose:
5101 unaryOp = spv::OpTranspose;
5102 break;
5103
5104 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005105 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005106 break;
5107 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005108 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005109 break;
5110 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005111 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005112 break;
5113 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005114 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005115 break;
5116 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005117 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005118 break;
5119 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005120 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005121 break;
5122 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005123 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005124 break;
5125 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005126 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005127 break;
5128
5129 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005130 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005131 break;
5132 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005133 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005134 break;
5135 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005136 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005137 break;
5138 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005139 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005140 break;
5141 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005142 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005143 break;
5144 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005145 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005146 break;
5147
5148 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005149 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005150 break;
5151 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005152 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005153 break;
5154
5155 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005156 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005157 break;
5158 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005159 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005160 break;
5161 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005162 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005163 break;
5164 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005165 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005166 break;
5167 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005168 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005169 break;
5170 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005171 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005172 break;
5173
5174 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005175 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005176 break;
5177 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005178 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005179 break;
5180 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005181 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005182 break;
5183 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005184 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005185 break;
5186 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005187 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005188 break;
5189 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005190 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005191 break;
5192
5193 case glslang::EOpIsNan:
5194 unaryOp = spv::OpIsNan;
5195 break;
5196 case glslang::EOpIsInf:
5197 unaryOp = spv::OpIsInf;
5198 break;
LoopDawg592860c2016-06-09 08:57:35 -06005199 case glslang::EOpIsFinite:
5200 unaryOp = spv::OpIsFinite;
5201 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005202
Rex Xucbc426e2015-12-15 16:03:10 +08005203 case glslang::EOpFloatBitsToInt:
5204 case glslang::EOpFloatBitsToUint:
5205 case glslang::EOpIntBitsToFloat:
5206 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005207 case glslang::EOpDoubleBitsToInt64:
5208 case glslang::EOpDoubleBitsToUint64:
5209 case glslang::EOpInt64BitsToDouble:
5210 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005211 case glslang::EOpFloat16BitsToInt16:
5212 case glslang::EOpFloat16BitsToUint16:
5213 case glslang::EOpInt16BitsToFloat16:
5214 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005215 unaryOp = spv::OpBitcast;
5216 break;
5217
John Kessenich140f3df2015-06-26 16:58:36 -06005218 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005219 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005220 break;
5221 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005222 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005223 break;
5224 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005225 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005226 break;
5227 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005228 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005229 break;
5230 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005235 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005236 case glslang::EOpPackSnorm4x8:
5237 libCall = spv::GLSLstd450PackSnorm4x8;
5238 break;
5239 case glslang::EOpUnpackSnorm4x8:
5240 libCall = spv::GLSLstd450UnpackSnorm4x8;
5241 break;
5242 case glslang::EOpPackUnorm4x8:
5243 libCall = spv::GLSLstd450PackUnorm4x8;
5244 break;
5245 case glslang::EOpUnpackUnorm4x8:
5246 libCall = spv::GLSLstd450UnpackUnorm4x8;
5247 break;
5248 case glslang::EOpPackDouble2x32:
5249 libCall = spv::GLSLstd450PackDouble2x32;
5250 break;
5251 case glslang::EOpUnpackDouble2x32:
5252 libCall = spv::GLSLstd450UnpackDouble2x32;
5253 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005254
Rex Xu8ff43de2016-04-22 16:51:45 +08005255 case glslang::EOpPackInt2x32:
5256 case glslang::EOpUnpackInt2x32:
5257 case glslang::EOpPackUint2x32:
5258 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005259 case glslang::EOpPack16:
5260 case glslang::EOpPack32:
5261 case glslang::EOpPack64:
5262 case glslang::EOpUnpack32:
5263 case glslang::EOpUnpack16:
5264 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005265 case glslang::EOpPackInt2x16:
5266 case glslang::EOpUnpackInt2x16:
5267 case glslang::EOpPackUint2x16:
5268 case glslang::EOpUnpackUint2x16:
5269 case glslang::EOpPackInt4x16:
5270 case glslang::EOpUnpackInt4x16:
5271 case glslang::EOpPackUint4x16:
5272 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005273 case glslang::EOpPackFloat2x16:
5274 case glslang::EOpUnpackFloat2x16:
5275 unaryOp = spv::OpBitcast;
5276 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005277
John Kessenich140f3df2015-06-26 16:58:36 -06005278 case glslang::EOpDPdx:
5279 unaryOp = spv::OpDPdx;
5280 break;
5281 case glslang::EOpDPdy:
5282 unaryOp = spv::OpDPdy;
5283 break;
5284 case glslang::EOpFwidth:
5285 unaryOp = spv::OpFwidth;
5286 break;
5287 case glslang::EOpDPdxFine:
5288 unaryOp = spv::OpDPdxFine;
5289 break;
5290 case glslang::EOpDPdyFine:
5291 unaryOp = spv::OpDPdyFine;
5292 break;
5293 case glslang::EOpFwidthFine:
5294 unaryOp = spv::OpFwidthFine;
5295 break;
5296 case glslang::EOpDPdxCoarse:
5297 unaryOp = spv::OpDPdxCoarse;
5298 break;
5299 case glslang::EOpDPdyCoarse:
5300 unaryOp = spv::OpDPdyCoarse;
5301 break;
5302 case glslang::EOpFwidthCoarse:
5303 unaryOp = spv::OpFwidthCoarse;
5304 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005305 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005306#ifdef AMD_EXTENSIONS
5307 if (typeProxy == glslang::EbtFloat16)
5308 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5309#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005310 libCall = spv::GLSLstd450InterpolateAtCentroid;
5311 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005312 case glslang::EOpAny:
5313 unaryOp = spv::OpAny;
5314 break;
5315 case glslang::EOpAll:
5316 unaryOp = spv::OpAll;
5317 break;
5318
5319 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005320 if (isFloat)
5321 libCall = spv::GLSLstd450FAbs;
5322 else
5323 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005324 break;
5325 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005326 if (isFloat)
5327 libCall = spv::GLSLstd450FSign;
5328 else
5329 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
5331
John Kessenichfc51d282015-08-19 13:34:18 -06005332 case glslang::EOpAtomicCounterIncrement:
5333 case glslang::EOpAtomicCounterDecrement:
5334 case glslang::EOpAtomicCounter:
5335 {
5336 // Handle all of the atomics in one place, in createAtomicOperation()
5337 std::vector<spv::Id> operands;
5338 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005339 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005340 }
5341
John Kessenichfc51d282015-08-19 13:34:18 -06005342 case glslang::EOpBitFieldReverse:
5343 unaryOp = spv::OpBitReverse;
5344 break;
5345 case glslang::EOpBitCount:
5346 unaryOp = spv::OpBitCount;
5347 break;
5348 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005349 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005350 break;
5351 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005352 if (isUnsigned)
5353 libCall = spv::GLSLstd450FindUMsb;
5354 else
5355 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005356 break;
5357
Rex Xu574ab042016-04-14 16:53:07 +08005358 case glslang::EOpBallot:
5359 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005360 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005361 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005362 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005363#ifdef AMD_EXTENSIONS
5364 case glslang::EOpMinInvocations:
5365 case glslang::EOpMaxInvocations:
5366 case glslang::EOpAddInvocations:
5367 case glslang::EOpMinInvocationsNonUniform:
5368 case glslang::EOpMaxInvocationsNonUniform:
5369 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005370 case glslang::EOpMinInvocationsInclusiveScan:
5371 case glslang::EOpMaxInvocationsInclusiveScan:
5372 case glslang::EOpAddInvocationsInclusiveScan:
5373 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5374 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5375 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5376 case glslang::EOpMinInvocationsExclusiveScan:
5377 case glslang::EOpMaxInvocationsExclusiveScan:
5378 case glslang::EOpAddInvocationsExclusiveScan:
5379 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5380 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5381 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005382#endif
Rex Xu51596642016-09-21 18:56:12 +08005383 {
5384 std::vector<spv::Id> operands;
5385 operands.push_back(operand);
5386 return createInvocationsOperation(op, typeId, operands, typeProxy);
5387 }
John Kessenich66011cb2018-03-06 16:12:04 -07005388 case glslang::EOpSubgroupAll:
5389 case glslang::EOpSubgroupAny:
5390 case glslang::EOpSubgroupAllEqual:
5391 case glslang::EOpSubgroupBroadcastFirst:
5392 case glslang::EOpSubgroupBallot:
5393 case glslang::EOpSubgroupInverseBallot:
5394 case glslang::EOpSubgroupBallotBitCount:
5395 case glslang::EOpSubgroupBallotInclusiveBitCount:
5396 case glslang::EOpSubgroupBallotExclusiveBitCount:
5397 case glslang::EOpSubgroupBallotFindLSB:
5398 case glslang::EOpSubgroupBallotFindMSB:
5399 case glslang::EOpSubgroupAdd:
5400 case glslang::EOpSubgroupMul:
5401 case glslang::EOpSubgroupMin:
5402 case glslang::EOpSubgroupMax:
5403 case glslang::EOpSubgroupAnd:
5404 case glslang::EOpSubgroupOr:
5405 case glslang::EOpSubgroupXor:
5406 case glslang::EOpSubgroupInclusiveAdd:
5407 case glslang::EOpSubgroupInclusiveMul:
5408 case glslang::EOpSubgroupInclusiveMin:
5409 case glslang::EOpSubgroupInclusiveMax:
5410 case glslang::EOpSubgroupInclusiveAnd:
5411 case glslang::EOpSubgroupInclusiveOr:
5412 case glslang::EOpSubgroupInclusiveXor:
5413 case glslang::EOpSubgroupExclusiveAdd:
5414 case glslang::EOpSubgroupExclusiveMul:
5415 case glslang::EOpSubgroupExclusiveMin:
5416 case glslang::EOpSubgroupExclusiveMax:
5417 case glslang::EOpSubgroupExclusiveAnd:
5418 case glslang::EOpSubgroupExclusiveOr:
5419 case glslang::EOpSubgroupExclusiveXor:
5420 case glslang::EOpSubgroupQuadSwapHorizontal:
5421 case glslang::EOpSubgroupQuadSwapVertical:
5422 case glslang::EOpSubgroupQuadSwapDiagonal: {
5423 std::vector<spv::Id> operands;
5424 operands.push_back(operand);
5425 return createSubgroupOperation(op, typeId, operands, typeProxy);
5426 }
Rex Xu9d93a232016-05-05 12:30:44 +08005427#ifdef AMD_EXTENSIONS
5428 case glslang::EOpMbcnt:
5429 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5430 libCall = spv::MbcntAMD;
5431 break;
5432
5433 case glslang::EOpCubeFaceIndex:
5434 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5435 libCall = spv::CubeFaceIndexAMD;
5436 break;
5437
5438 case glslang::EOpCubeFaceCoord:
5439 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5440 libCall = spv::CubeFaceCoordAMD;
5441 break;
5442#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005443#ifdef NV_EXTENSIONS
5444 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005445 unaryOp = spv::OpGroupNonUniformPartitionNV;
5446 break;
5447#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005448 case glslang::EOpConstructReference:
5449 unaryOp = spv::OpBitcast;
5450 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005451 default:
5452 return 0;
5453 }
5454
5455 spv::Id id;
5456 if (libCall >= 0) {
5457 std::vector<spv::Id> args;
5458 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005459 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005460 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005461 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005462 }
John Kessenich140f3df2015-06-26 16:58:36 -06005463
John Kessenichead86222018-03-28 18:01:20 -06005464 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005465 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005466 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005467}
5468
John Kessenich7a53f762016-01-20 11:19:27 -07005469// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005470spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5471 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005472{
5473 // Handle unary operations vector by vector.
5474 // The result type is the same type as the original type.
5475 // The algorithm is to:
5476 // - break the matrix into vectors
5477 // - apply the operation to each vector
5478 // - make a matrix out the vector results
5479
5480 // get the types sorted out
5481 int numCols = builder.getNumColumns(operand);
5482 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005483 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5484 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005485 std::vector<spv::Id> results;
5486
5487 // do each vector op
5488 for (int c = 0; c < numCols; ++c) {
5489 std::vector<unsigned int> indexes;
5490 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005491 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5492 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005493 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005494 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005495 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005496 }
5497
5498 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005499 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005500 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005501 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005502}
5503
John Kessenichad7645f2018-06-04 19:11:25 -06005504// For converting integers where both the bitwidth and the signedness could
5505// change, but only do the width change here. The caller is still responsible
5506// for the signedness conversion.
5507spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005508{
John Kessenichad7645f2018-06-04 19:11:25 -06005509 // Get the result type width, based on the type to convert to.
5510 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005511 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005512 case glslang::EOpConvInt16ToUint8:
5513 case glslang::EOpConvIntToUint8:
5514 case glslang::EOpConvInt64ToUint8:
5515 case glslang::EOpConvUint16ToInt8:
5516 case glslang::EOpConvUintToInt8:
5517 case glslang::EOpConvUint64ToInt8:
5518 width = 8;
5519 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005520 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005521 case glslang::EOpConvIntToUint16:
5522 case glslang::EOpConvInt64ToUint16:
5523 case glslang::EOpConvUint8ToInt16:
5524 case glslang::EOpConvUintToInt16:
5525 case glslang::EOpConvUint64ToInt16:
5526 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005527 break;
5528 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005529 case glslang::EOpConvInt16ToUint:
5530 case glslang::EOpConvInt64ToUint:
5531 case glslang::EOpConvUint8ToInt:
5532 case glslang::EOpConvUint16ToInt:
5533 case glslang::EOpConvUint64ToInt:
5534 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005535 break;
5536 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005537 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005538 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005539 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005540 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005541 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005542 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005543 break;
5544
5545 default:
5546 assert(false && "Default missing");
5547 break;
5548 }
5549
John Kessenichad7645f2018-06-04 19:11:25 -06005550 // Get the conversion operation and result type,
5551 // based on the target width, but the source type.
5552 spv::Id type = spv::NoType;
5553 spv::Op convOp = spv::OpNop;
5554 switch(op) {
5555 case glslang::EOpConvInt8ToUint16:
5556 case glslang::EOpConvInt8ToUint:
5557 case glslang::EOpConvInt8ToUint64:
5558 case glslang::EOpConvInt16ToUint8:
5559 case glslang::EOpConvInt16ToUint:
5560 case glslang::EOpConvInt16ToUint64:
5561 case glslang::EOpConvIntToUint8:
5562 case glslang::EOpConvIntToUint16:
5563 case glslang::EOpConvIntToUint64:
5564 case glslang::EOpConvInt64ToUint8:
5565 case glslang::EOpConvInt64ToUint16:
5566 case glslang::EOpConvInt64ToUint:
5567 convOp = spv::OpSConvert;
5568 type = builder.makeIntType(width);
5569 break;
5570 default:
5571 convOp = spv::OpUConvert;
5572 type = builder.makeUintType(width);
5573 break;
5574 }
5575
John Kessenich66011cb2018-03-06 16:12:04 -07005576 if (vectorSize > 0)
5577 type = builder.makeVectorType(type, vectorSize);
5578
John Kessenichad7645f2018-06-04 19:11:25 -06005579 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005580}
5581
John Kessenichead86222018-03-28 18:01:20 -06005582spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5583 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005584{
5585 spv::Op convOp = spv::OpNop;
5586 spv::Id zero = 0;
5587 spv::Id one = 0;
5588
5589 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5590
5591 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005592 case glslang::EOpConvInt8ToBool:
5593 case glslang::EOpConvUint8ToBool:
5594 zero = builder.makeUint8Constant(0);
5595 zero = makeSmearedConstant(zero, vectorSize);
5596 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005597 case glslang::EOpConvInt16ToBool:
5598 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005599 zero = builder.makeUint16Constant(0);
5600 zero = makeSmearedConstant(zero, vectorSize);
5601 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5602 case glslang::EOpConvIntToBool:
5603 case glslang::EOpConvUintToBool:
5604 zero = builder.makeUintConstant(0);
5605 zero = makeSmearedConstant(zero, vectorSize);
5606 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5607 case glslang::EOpConvInt64ToBool:
5608 case glslang::EOpConvUint64ToBool:
5609 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005610 zero = makeSmearedConstant(zero, vectorSize);
5611 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5612
5613 case glslang::EOpConvFloatToBool:
5614 zero = builder.makeFloatConstant(0.0F);
5615 zero = makeSmearedConstant(zero, vectorSize);
5616 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5617
5618 case glslang::EOpConvDoubleToBool:
5619 zero = builder.makeDoubleConstant(0.0);
5620 zero = makeSmearedConstant(zero, vectorSize);
5621 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5622
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005623 case glslang::EOpConvFloat16ToBool:
5624 zero = builder.makeFloat16Constant(0.0F);
5625 zero = makeSmearedConstant(zero, vectorSize);
5626 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005627
John Kessenich140f3df2015-06-26 16:58:36 -06005628 case glslang::EOpConvBoolToFloat:
5629 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005630 zero = builder.makeFloatConstant(0.0F);
5631 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005632 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005633
John Kessenich140f3df2015-06-26 16:58:36 -06005634 case glslang::EOpConvBoolToDouble:
5635 convOp = spv::OpSelect;
5636 zero = builder.makeDoubleConstant(0.0);
5637 one = builder.makeDoubleConstant(1.0);
5638 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005639
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005640 case glslang::EOpConvBoolToFloat16:
5641 convOp = spv::OpSelect;
5642 zero = builder.makeFloat16Constant(0.0F);
5643 one = builder.makeFloat16Constant(1.0F);
5644 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005645
5646 case glslang::EOpConvBoolToInt8:
5647 zero = builder.makeInt8Constant(0);
5648 one = builder.makeInt8Constant(1);
5649 convOp = spv::OpSelect;
5650 break;
5651
5652 case glslang::EOpConvBoolToUint8:
5653 zero = builder.makeUint8Constant(0);
5654 one = builder.makeUint8Constant(1);
5655 convOp = spv::OpSelect;
5656 break;
5657
5658 case glslang::EOpConvBoolToInt16:
5659 zero = builder.makeInt16Constant(0);
5660 one = builder.makeInt16Constant(1);
5661 convOp = spv::OpSelect;
5662 break;
5663
5664 case glslang::EOpConvBoolToUint16:
5665 zero = builder.makeUint16Constant(0);
5666 one = builder.makeUint16Constant(1);
5667 convOp = spv::OpSelect;
5668 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005669
John Kessenich140f3df2015-06-26 16:58:36 -06005670 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005671 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005672 if (op == glslang::EOpConvBoolToInt64)
5673 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005674 else
5675 zero = builder.makeIntConstant(0);
5676
5677 if (op == glslang::EOpConvBoolToInt64)
5678 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005679 else
5680 one = builder.makeIntConstant(1);
5681
John Kessenich140f3df2015-06-26 16:58:36 -06005682 convOp = spv::OpSelect;
5683 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005684
John Kessenich140f3df2015-06-26 16:58:36 -06005685 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005686 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005687 if (op == glslang::EOpConvBoolToUint64)
5688 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005689 else
5690 zero = builder.makeUintConstant(0);
5691
5692 if (op == glslang::EOpConvBoolToUint64)
5693 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005694 else
5695 one = builder.makeUintConstant(1);
5696
John Kessenich140f3df2015-06-26 16:58:36 -06005697 convOp = spv::OpSelect;
5698 break;
5699
John Kessenich66011cb2018-03-06 16:12:04 -07005700 case glslang::EOpConvInt8ToFloat16:
5701 case glslang::EOpConvInt8ToFloat:
5702 case glslang::EOpConvInt8ToDouble:
5703 case glslang::EOpConvInt16ToFloat16:
5704 case glslang::EOpConvInt16ToFloat:
5705 case glslang::EOpConvInt16ToDouble:
5706 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005707 case glslang::EOpConvIntToFloat:
5708 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005709 case glslang::EOpConvInt64ToFloat:
5710 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005711 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005712 convOp = spv::OpConvertSToF;
5713 break;
5714
John Kessenich66011cb2018-03-06 16:12:04 -07005715 case glslang::EOpConvUint8ToFloat16:
5716 case glslang::EOpConvUint8ToFloat:
5717 case glslang::EOpConvUint8ToDouble:
5718 case glslang::EOpConvUint16ToFloat16:
5719 case glslang::EOpConvUint16ToFloat:
5720 case glslang::EOpConvUint16ToDouble:
5721 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005722 case glslang::EOpConvUintToFloat:
5723 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005724 case glslang::EOpConvUint64ToFloat:
5725 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005726 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005727 convOp = spv::OpConvertUToF;
5728 break;
5729
5730 case glslang::EOpConvDoubleToFloat:
5731 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005732 case glslang::EOpConvDoubleToFloat16:
5733 case glslang::EOpConvFloat16ToDouble:
5734 case glslang::EOpConvFloatToFloat16:
5735 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005736 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005737 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005738 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005739 break;
5740
John Kessenich66011cb2018-03-06 16:12:04 -07005741 case glslang::EOpConvFloat16ToInt8:
5742 case glslang::EOpConvFloatToInt8:
5743 case glslang::EOpConvDoubleToInt8:
5744 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005745 case glslang::EOpConvFloatToInt16:
5746 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005747 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005748 case glslang::EOpConvFloatToInt:
5749 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005750 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005751 case glslang::EOpConvFloatToInt64:
5752 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005753 convOp = spv::OpConvertFToS;
5754 break;
5755
John Kessenich66011cb2018-03-06 16:12:04 -07005756 case glslang::EOpConvUint8ToInt8:
5757 case glslang::EOpConvInt8ToUint8:
5758 case glslang::EOpConvUint16ToInt16:
5759 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005760 case glslang::EOpConvUintToInt:
5761 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005762 case glslang::EOpConvUint64ToInt64:
5763 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005764 if (builder.isInSpecConstCodeGenMode()) {
5765 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005766 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5767 zero = builder.makeUint8Constant(0);
5768 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005769 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005770 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5771 zero = builder.makeUint64Constant(0);
5772 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005773 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005774 }
qining189b2032016-04-12 23:16:20 -04005775 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005776 // Use OpIAdd, instead of OpBitcast to do the conversion when
5777 // generating for OpSpecConstantOp instruction.
5778 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5779 }
5780 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005781 convOp = spv::OpBitcast;
5782 break;
5783
John Kessenich66011cb2018-03-06 16:12:04 -07005784 case glslang::EOpConvFloat16ToUint8:
5785 case glslang::EOpConvFloatToUint8:
5786 case glslang::EOpConvDoubleToUint8:
5787 case glslang::EOpConvFloat16ToUint16:
5788 case glslang::EOpConvFloatToUint16:
5789 case glslang::EOpConvDoubleToUint16:
5790 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005791 case glslang::EOpConvFloatToUint:
5792 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005793 case glslang::EOpConvFloatToUint64:
5794 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005795 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005796 convOp = spv::OpConvertFToU;
5797 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005798
John Kessenich66011cb2018-03-06 16:12:04 -07005799 case glslang::EOpConvInt8ToInt16:
5800 case glslang::EOpConvInt8ToInt:
5801 case glslang::EOpConvInt8ToInt64:
5802 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005803 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005804 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005805 case glslang::EOpConvIntToInt8:
5806 case glslang::EOpConvIntToInt16:
5807 case glslang::EOpConvIntToInt64:
5808 case glslang::EOpConvInt64ToInt8:
5809 case glslang::EOpConvInt64ToInt16:
5810 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005811 convOp = spv::OpSConvert;
5812 break;
5813
John Kessenich66011cb2018-03-06 16:12:04 -07005814 case glslang::EOpConvUint8ToUint16:
5815 case glslang::EOpConvUint8ToUint:
5816 case glslang::EOpConvUint8ToUint64:
5817 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005818 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005819 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005820 case glslang::EOpConvUintToUint8:
5821 case glslang::EOpConvUintToUint16:
5822 case glslang::EOpConvUintToUint64:
5823 case glslang::EOpConvUint64ToUint8:
5824 case glslang::EOpConvUint64ToUint16:
5825 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005826 convOp = spv::OpUConvert;
5827 break;
5828
John Kessenich66011cb2018-03-06 16:12:04 -07005829 case glslang::EOpConvInt8ToUint16:
5830 case glslang::EOpConvInt8ToUint:
5831 case glslang::EOpConvInt8ToUint64:
5832 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005833 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005834 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005835 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005836 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005837 case glslang::EOpConvIntToUint64:
5838 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005839 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005840 case glslang::EOpConvInt64ToUint:
5841 case glslang::EOpConvUint8ToInt16:
5842 case glslang::EOpConvUint8ToInt:
5843 case glslang::EOpConvUint8ToInt64:
5844 case glslang::EOpConvUint16ToInt8:
5845 case glslang::EOpConvUint16ToInt:
5846 case glslang::EOpConvUint16ToInt64:
5847 case glslang::EOpConvUintToInt8:
5848 case glslang::EOpConvUintToInt16:
5849 case glslang::EOpConvUintToInt64:
5850 case glslang::EOpConvUint64ToInt8:
5851 case glslang::EOpConvUint64ToInt16:
5852 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005853 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005854 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005855
5856 if (builder.isInSpecConstCodeGenMode()) {
5857 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005858 switch(op) {
5859 case glslang::EOpConvInt16ToUint8:
5860 case glslang::EOpConvIntToUint8:
5861 case glslang::EOpConvInt64ToUint8:
5862 case glslang::EOpConvUint16ToInt8:
5863 case glslang::EOpConvUintToInt8:
5864 case glslang::EOpConvUint64ToInt8:
5865 zero = builder.makeUint8Constant(0);
5866 break;
5867 case glslang::EOpConvInt8ToUint16:
5868 case glslang::EOpConvIntToUint16:
5869 case glslang::EOpConvInt64ToUint16:
5870 case glslang::EOpConvUint8ToInt16:
5871 case glslang::EOpConvUintToInt16:
5872 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005873 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005874 break;
5875 case glslang::EOpConvInt8ToUint:
5876 case glslang::EOpConvInt16ToUint:
5877 case glslang::EOpConvInt64ToUint:
5878 case glslang::EOpConvUint8ToInt:
5879 case glslang::EOpConvUint16ToInt:
5880 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005881 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005882 break;
5883 case glslang::EOpConvInt8ToUint64:
5884 case glslang::EOpConvInt16ToUint64:
5885 case glslang::EOpConvIntToUint64:
5886 case glslang::EOpConvUint8ToInt64:
5887 case glslang::EOpConvUint16ToInt64:
5888 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005889 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005890 break;
5891 default:
5892 assert(false && "Default missing");
5893 break;
5894 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005895 zero = makeSmearedConstant(zero, vectorSize);
5896 // Use OpIAdd, instead of OpBitcast to do the conversion when
5897 // generating for OpSpecConstantOp instruction.
5898 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5899 }
5900 // For normal run-time conversion instruction, use OpBitcast.
5901 convOp = spv::OpBitcast;
5902 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005903 case glslang::EOpConvUint64ToPtr:
5904 convOp = spv::OpConvertUToPtr;
5905 break;
5906 case glslang::EOpConvPtrToUint64:
5907 convOp = spv::OpConvertPtrToU;
5908 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005909 default:
5910 break;
5911 }
5912
5913 spv::Id result = 0;
5914 if (convOp == spv::OpNop)
5915 return result;
5916
5917 if (convOp == spv::OpSelect) {
5918 zero = makeSmearedConstant(zero, vectorSize);
5919 one = makeSmearedConstant(one, vectorSize);
5920 result = builder.createTriOp(convOp, destType, operand, one, zero);
5921 } else
5922 result = builder.createUnaryOp(convOp, destType, operand);
5923
John Kessenichead86222018-03-28 18:01:20 -06005924 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005925 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005926 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005927}
5928
5929spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5930{
5931 if (vectorSize == 0)
5932 return constant;
5933
5934 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5935 std::vector<spv::Id> components;
5936 for (int c = 0; c < vectorSize; ++c)
5937 components.push_back(constant);
5938 return builder.makeCompositeConstant(vectorTypeId, components);
5939}
5940
John Kessenich426394d2015-07-23 10:22:48 -06005941// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005942spv::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 -06005943{
5944 spv::Op opCode = spv::OpNop;
5945
5946 switch (op) {
5947 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005948 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005949 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005950 opCode = spv::OpAtomicIAdd;
5951 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005952 case glslang::EOpAtomicCounterSubtract:
5953 opCode = spv::OpAtomicISub;
5954 break;
John Kessenich426394d2015-07-23 10:22:48 -06005955 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005956 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005957 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005958 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005959 break;
5960 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005961 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005962 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005963 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005964 break;
5965 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005966 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005967 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005968 opCode = spv::OpAtomicAnd;
5969 break;
5970 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005971 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005972 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005973 opCode = spv::OpAtomicOr;
5974 break;
5975 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005976 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005977 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005978 opCode = spv::OpAtomicXor;
5979 break;
5980 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005981 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005982 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005983 opCode = spv::OpAtomicExchange;
5984 break;
5985 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005986 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005987 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005988 opCode = spv::OpAtomicCompareExchange;
5989 break;
5990 case glslang::EOpAtomicCounterIncrement:
5991 opCode = spv::OpAtomicIIncrement;
5992 break;
5993 case glslang::EOpAtomicCounterDecrement:
5994 opCode = spv::OpAtomicIDecrement;
5995 break;
5996 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005997 case glslang::EOpImageAtomicLoad:
5998 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005999 opCode = spv::OpAtomicLoad;
6000 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006001 case glslang::EOpAtomicStore:
6002 case glslang::EOpImageAtomicStore:
6003 opCode = spv::OpAtomicStore;
6004 break;
John Kessenich426394d2015-07-23 10:22:48 -06006005 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006006 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006007 break;
6008 }
6009
Rex Xue8fe8b02017-09-26 15:42:56 +08006010 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6011 builder.addCapability(spv::CapabilityInt64Atomics);
6012
John Kessenich426394d2015-07-23 10:22:48 -06006013 // Sort out the operands
6014 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006015 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006016 // - compare-exchange swaps the value and comparator
6017 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006018 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006019 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6020 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6021 spv::Id scopeId;
6022 if (glslangIntermediate->usingVulkanMemoryModel()) {
6023 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6024 } else {
6025 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6026 }
6027 // semantics default to relaxed
6028 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6029 spv::Id semanticsId2 = semanticsId;
6030
6031 pointerId = operands[0];
6032 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6033 // no additional operands
6034 } else if (opCode == spv::OpAtomicCompareExchange) {
6035 compareId = operands[1];
6036 valueId = operands[2];
6037 if (operands.size() > 3) {
6038 scopeId = operands[3];
6039 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6040 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6041 }
6042 } else if (opCode == spv::OpAtomicLoad) {
6043 if (operands.size() > 1) {
6044 scopeId = operands[1];
6045 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6046 }
6047 } else {
6048 // atomic store or RMW
6049 valueId = operands[1];
6050 if (operands.size() > 2) {
6051 scopeId = operands[2];
6052 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6053 }
Rex Xu04db3f52015-09-16 11:44:02 +08006054 }
John Kessenich426394d2015-07-23 10:22:48 -06006055
Jeff Bolz36831c92018-09-05 10:11:41 -05006056 // Check for capabilities
6057 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6058 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6059 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6060 }
John Kessenich426394d2015-07-23 10:22:48 -06006061
Jeff Bolz36831c92018-09-05 10:11:41 -05006062 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6063 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6064 }
John Kessenich48d6e792017-10-06 21:21:48 -06006065
Jeff Bolz36831c92018-09-05 10:11:41 -05006066 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6067 spvAtomicOperands.push_back(pointerId);
6068 spvAtomicOperands.push_back(scopeId);
6069 spvAtomicOperands.push_back(semanticsId);
6070 if (opCode == spv::OpAtomicCompareExchange) {
6071 spvAtomicOperands.push_back(semanticsId2);
6072 spvAtomicOperands.push_back(valueId);
6073 spvAtomicOperands.push_back(compareId);
6074 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6075 spvAtomicOperands.push_back(valueId);
6076 }
John Kessenich48d6e792017-10-06 21:21:48 -06006077
Jeff Bolz36831c92018-09-05 10:11:41 -05006078 if (opCode == spv::OpAtomicStore) {
6079 builder.createNoResultOp(opCode, spvAtomicOperands);
6080 return 0;
6081 } else {
6082 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6083
6084 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6085 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6086 if (op == glslang::EOpAtomicCounterDecrement)
6087 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6088
6089 return resultId;
6090 }
John Kessenich426394d2015-07-23 10:22:48 -06006091}
6092
John Kessenich91cef522016-05-05 16:45:40 -06006093// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006094spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006095{
Corentin Walleze7061422018-08-08 15:20:15 +02006096#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006097 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6098 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006099#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006100
Rex Xu51596642016-09-21 18:56:12 +08006101 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006102 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006103 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6104
chaocf200da82016-12-20 12:44:35 -08006105 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6106 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006107 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6108 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006109 } else if (op == glslang::EOpAnyInvocation ||
6110 op == glslang::EOpAllInvocations ||
6111 op == glslang::EOpAllInvocationsEqual) {
6112 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6113 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006114 } else {
6115 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006116#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006117 if (op == glslang::EOpMinInvocationsNonUniform ||
6118 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006119 op == glslang::EOpAddInvocationsNonUniform ||
6120 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6121 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6122 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6123 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6124 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6125 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006126 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006127#endif
Rex Xu51596642016-09-21 18:56:12 +08006128
Rex Xu9d93a232016-05-05 12:30:44 +08006129#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006130 switch (op) {
6131 case glslang::EOpMinInvocations:
6132 case glslang::EOpMaxInvocations:
6133 case glslang::EOpAddInvocations:
6134 case glslang::EOpMinInvocationsNonUniform:
6135 case glslang::EOpMaxInvocationsNonUniform:
6136 case glslang::EOpAddInvocationsNonUniform:
6137 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006138 break;
6139 case glslang::EOpMinInvocationsInclusiveScan:
6140 case glslang::EOpMaxInvocationsInclusiveScan:
6141 case glslang::EOpAddInvocationsInclusiveScan:
6142 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6143 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6144 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6145 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006146 break;
6147 case glslang::EOpMinInvocationsExclusiveScan:
6148 case glslang::EOpMaxInvocationsExclusiveScan:
6149 case glslang::EOpAddInvocationsExclusiveScan:
6150 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6151 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6152 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6153 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006154 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006155 default:
6156 break;
Rex Xu430ef402016-10-14 17:22:23 +08006157 }
John Kessenich149afc32018-08-14 13:31:43 -06006158 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6159 spvGroupOperands.push_back(scope);
6160 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006161 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006162 spvGroupOperands.push_back(groupOp);
6163 }
Rex Xu9d93a232016-05-05 12:30:44 +08006164#endif
Rex Xu51596642016-09-21 18:56:12 +08006165 }
6166
John Kessenich149afc32018-08-14 13:31:43 -06006167 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6168 spv::IdImmediate op = { true, *opIt };
6169 spvGroupOperands.push_back(op);
6170 }
John Kessenich91cef522016-05-05 16:45:40 -06006171
6172 switch (op) {
6173 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006174 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006175 break;
John Kessenich91cef522016-05-05 16:45:40 -06006176 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006177 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006178 break;
John Kessenich91cef522016-05-05 16:45:40 -06006179 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006180 opCode = spv::OpSubgroupAllEqualKHR;
6181 break;
Rex Xu51596642016-09-21 18:56:12 +08006182 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006183 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006184 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006185 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006186 break;
6187 case glslang::EOpReadFirstInvocation:
6188 opCode = spv::OpSubgroupFirstInvocationKHR;
6189 break;
6190 case glslang::EOpBallot:
6191 {
6192 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6193 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6194 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6195 //
6196 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6197 //
6198 spv::Id uintType = builder.makeUintType(32);
6199 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6200 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6201
6202 std::vector<spv::Id> components;
6203 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6204 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6205
6206 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6207 return builder.createUnaryOp(spv::OpBitcast, typeId,
6208 builder.createCompositeConstruct(uvec2Type, components));
6209 }
6210
Rex Xu9d93a232016-05-05 12:30:44 +08006211#ifdef AMD_EXTENSIONS
6212 case glslang::EOpMinInvocations:
6213 case glslang::EOpMaxInvocations:
6214 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006215 case glslang::EOpMinInvocationsInclusiveScan:
6216 case glslang::EOpMaxInvocationsInclusiveScan:
6217 case glslang::EOpAddInvocationsInclusiveScan:
6218 case glslang::EOpMinInvocationsExclusiveScan:
6219 case glslang::EOpMaxInvocationsExclusiveScan:
6220 case glslang::EOpAddInvocationsExclusiveScan:
6221 if (op == glslang::EOpMinInvocations ||
6222 op == glslang::EOpMinInvocationsInclusiveScan ||
6223 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006224 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006225 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006226 else {
6227 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006228 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006229 else
Rex Xu51596642016-09-21 18:56:12 +08006230 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006231 }
Rex Xu430ef402016-10-14 17:22:23 +08006232 } else if (op == glslang::EOpMaxInvocations ||
6233 op == glslang::EOpMaxInvocationsInclusiveScan ||
6234 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006235 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006236 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006237 else {
6238 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006239 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006240 else
Rex Xu51596642016-09-21 18:56:12 +08006241 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006242 }
6243 } else {
6244 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006245 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006246 else
Rex Xu51596642016-09-21 18:56:12 +08006247 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006248 }
6249
Rex Xu2bbbe062016-08-23 15:41:05 +08006250 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006251 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006252
6253 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006254 case glslang::EOpMinInvocationsNonUniform:
6255 case glslang::EOpMaxInvocationsNonUniform:
6256 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006257 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6258 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6259 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6260 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6261 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6262 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6263 if (op == glslang::EOpMinInvocationsNonUniform ||
6264 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6265 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006266 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006267 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006268 else {
6269 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006270 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006271 else
Rex Xu51596642016-09-21 18:56:12 +08006272 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006273 }
6274 }
Rex Xu430ef402016-10-14 17:22:23 +08006275 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6276 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6277 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006278 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006279 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006280 else {
6281 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006282 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006283 else
Rex Xu51596642016-09-21 18:56:12 +08006284 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006285 }
6286 }
6287 else {
6288 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006289 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006290 else
Rex Xu51596642016-09-21 18:56:12 +08006291 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006292 }
6293
Rex Xu2bbbe062016-08-23 15:41:05 +08006294 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006295 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006296
6297 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006298#endif
John Kessenich91cef522016-05-05 16:45:40 -06006299 default:
6300 logger->missingFunctionality("invocation operation");
6301 return spv::NoResult;
6302 }
Rex Xu51596642016-09-21 18:56:12 +08006303
6304 assert(opCode != spv::OpNop);
6305 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006306}
6307
Rex Xu2bbbe062016-08-23 15:41:05 +08006308// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006309spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6310 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006311{
Rex Xub7072052016-09-26 15:53:40 +08006312#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006313 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6314 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006315 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006316 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006317 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6318 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6319 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006320#else
6321 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6322 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006323 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6324 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006325#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006326
6327 // Handle group invocation operations scalar by scalar.
6328 // The result type is the same type as the original type.
6329 // The algorithm is to:
6330 // - break the vector into scalars
6331 // - apply the operation to each scalar
6332 // - make a vector out the scalar results
6333
6334 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006335 int numComponents = builder.getNumComponents(operands[0]);
6336 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006337 std::vector<spv::Id> results;
6338
6339 // do each scalar op
6340 for (int comp = 0; comp < numComponents; ++comp) {
6341 std::vector<unsigned int> indexes;
6342 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006343 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6344 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006345 if (op == spv::OpSubgroupReadInvocationKHR) {
6346 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006347 spv::IdImmediate operand = { true, operands[1] };
6348 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006349 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006350 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6351 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006352 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006353 spv::IdImmediate operand = { true, operands[1] };
6354 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006355 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006356 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6357 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006358 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006359 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006360 spvGroupOperands.push_back(scalar);
6361 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006362
Rex Xub7072052016-09-26 15:53:40 +08006363 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006364 }
6365
6366 // put the pieces together
6367 return builder.createCompositeConstruct(typeId, results);
6368}
Rex Xu2bbbe062016-08-23 15:41:05 +08006369
John Kessenich66011cb2018-03-06 16:12:04 -07006370// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006371spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6372 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006373{
6374 // Add the required capabilities.
6375 switch (op) {
6376 case glslang::EOpSubgroupElect:
6377 builder.addCapability(spv::CapabilityGroupNonUniform);
6378 break;
6379 case glslang::EOpSubgroupAll:
6380 case glslang::EOpSubgroupAny:
6381 case glslang::EOpSubgroupAllEqual:
6382 builder.addCapability(spv::CapabilityGroupNonUniform);
6383 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6384 break;
6385 case glslang::EOpSubgroupBroadcast:
6386 case glslang::EOpSubgroupBroadcastFirst:
6387 case glslang::EOpSubgroupBallot:
6388 case glslang::EOpSubgroupInverseBallot:
6389 case glslang::EOpSubgroupBallotBitExtract:
6390 case glslang::EOpSubgroupBallotBitCount:
6391 case glslang::EOpSubgroupBallotInclusiveBitCount:
6392 case glslang::EOpSubgroupBallotExclusiveBitCount:
6393 case glslang::EOpSubgroupBallotFindLSB:
6394 case glslang::EOpSubgroupBallotFindMSB:
6395 builder.addCapability(spv::CapabilityGroupNonUniform);
6396 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6397 break;
6398 case glslang::EOpSubgroupShuffle:
6399 case glslang::EOpSubgroupShuffleXor:
6400 builder.addCapability(spv::CapabilityGroupNonUniform);
6401 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6402 break;
6403 case glslang::EOpSubgroupShuffleUp:
6404 case glslang::EOpSubgroupShuffleDown:
6405 builder.addCapability(spv::CapabilityGroupNonUniform);
6406 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6407 break;
6408 case glslang::EOpSubgroupAdd:
6409 case glslang::EOpSubgroupMul:
6410 case glslang::EOpSubgroupMin:
6411 case glslang::EOpSubgroupMax:
6412 case glslang::EOpSubgroupAnd:
6413 case glslang::EOpSubgroupOr:
6414 case glslang::EOpSubgroupXor:
6415 case glslang::EOpSubgroupInclusiveAdd:
6416 case glslang::EOpSubgroupInclusiveMul:
6417 case glslang::EOpSubgroupInclusiveMin:
6418 case glslang::EOpSubgroupInclusiveMax:
6419 case glslang::EOpSubgroupInclusiveAnd:
6420 case glslang::EOpSubgroupInclusiveOr:
6421 case glslang::EOpSubgroupInclusiveXor:
6422 case glslang::EOpSubgroupExclusiveAdd:
6423 case glslang::EOpSubgroupExclusiveMul:
6424 case glslang::EOpSubgroupExclusiveMin:
6425 case glslang::EOpSubgroupExclusiveMax:
6426 case glslang::EOpSubgroupExclusiveAnd:
6427 case glslang::EOpSubgroupExclusiveOr:
6428 case glslang::EOpSubgroupExclusiveXor:
6429 builder.addCapability(spv::CapabilityGroupNonUniform);
6430 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6431 break;
6432 case glslang::EOpSubgroupClusteredAdd:
6433 case glslang::EOpSubgroupClusteredMul:
6434 case glslang::EOpSubgroupClusteredMin:
6435 case glslang::EOpSubgroupClusteredMax:
6436 case glslang::EOpSubgroupClusteredAnd:
6437 case glslang::EOpSubgroupClusteredOr:
6438 case glslang::EOpSubgroupClusteredXor:
6439 builder.addCapability(spv::CapabilityGroupNonUniform);
6440 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6441 break;
6442 case glslang::EOpSubgroupQuadBroadcast:
6443 case glslang::EOpSubgroupQuadSwapHorizontal:
6444 case glslang::EOpSubgroupQuadSwapVertical:
6445 case glslang::EOpSubgroupQuadSwapDiagonal:
6446 builder.addCapability(spv::CapabilityGroupNonUniform);
6447 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6448 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006449#ifdef NV_EXTENSIONS
6450 case glslang::EOpSubgroupPartitionedAdd:
6451 case glslang::EOpSubgroupPartitionedMul:
6452 case glslang::EOpSubgroupPartitionedMin:
6453 case glslang::EOpSubgroupPartitionedMax:
6454 case glslang::EOpSubgroupPartitionedAnd:
6455 case glslang::EOpSubgroupPartitionedOr:
6456 case glslang::EOpSubgroupPartitionedXor:
6457 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6458 case glslang::EOpSubgroupPartitionedInclusiveMul:
6459 case glslang::EOpSubgroupPartitionedInclusiveMin:
6460 case glslang::EOpSubgroupPartitionedInclusiveMax:
6461 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6462 case glslang::EOpSubgroupPartitionedInclusiveOr:
6463 case glslang::EOpSubgroupPartitionedInclusiveXor:
6464 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6465 case glslang::EOpSubgroupPartitionedExclusiveMul:
6466 case glslang::EOpSubgroupPartitionedExclusiveMin:
6467 case glslang::EOpSubgroupPartitionedExclusiveMax:
6468 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6469 case glslang::EOpSubgroupPartitionedExclusiveOr:
6470 case glslang::EOpSubgroupPartitionedExclusiveXor:
6471 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6472 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6473 break;
6474#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006475 default: assert(0 && "Unhandled subgroup operation!");
6476 }
6477
6478 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6479 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6480 const bool isBool = typeProxy == glslang::EbtBool;
6481
6482 spv::Op opCode = spv::OpNop;
6483
6484 // Figure out which opcode to use.
6485 switch (op) {
6486 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6487 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6488 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6489 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6490 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6491 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6492 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6493 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6494 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6495 case glslang::EOpSubgroupBallotBitCount:
6496 case glslang::EOpSubgroupBallotInclusiveBitCount:
6497 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6498 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6499 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6500 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6501 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6502 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6503 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6504 case glslang::EOpSubgroupAdd:
6505 case glslang::EOpSubgroupInclusiveAdd:
6506 case glslang::EOpSubgroupExclusiveAdd:
6507 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006508#ifdef NV_EXTENSIONS
6509 case glslang::EOpSubgroupPartitionedAdd:
6510 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6511 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6512#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006513 if (isFloat) {
6514 opCode = spv::OpGroupNonUniformFAdd;
6515 } else {
6516 opCode = spv::OpGroupNonUniformIAdd;
6517 }
6518 break;
6519 case glslang::EOpSubgroupMul:
6520 case glslang::EOpSubgroupInclusiveMul:
6521 case glslang::EOpSubgroupExclusiveMul:
6522 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006523#ifdef NV_EXTENSIONS
6524 case glslang::EOpSubgroupPartitionedMul:
6525 case glslang::EOpSubgroupPartitionedInclusiveMul:
6526 case glslang::EOpSubgroupPartitionedExclusiveMul:
6527#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006528 if (isFloat) {
6529 opCode = spv::OpGroupNonUniformFMul;
6530 } else {
6531 opCode = spv::OpGroupNonUniformIMul;
6532 }
6533 break;
6534 case glslang::EOpSubgroupMin:
6535 case glslang::EOpSubgroupInclusiveMin:
6536 case glslang::EOpSubgroupExclusiveMin:
6537 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006538#ifdef NV_EXTENSIONS
6539 case glslang::EOpSubgroupPartitionedMin:
6540 case glslang::EOpSubgroupPartitionedInclusiveMin:
6541 case glslang::EOpSubgroupPartitionedExclusiveMin:
6542#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006543 if (isFloat) {
6544 opCode = spv::OpGroupNonUniformFMin;
6545 } else if (isUnsigned) {
6546 opCode = spv::OpGroupNonUniformUMin;
6547 } else {
6548 opCode = spv::OpGroupNonUniformSMin;
6549 }
6550 break;
6551 case glslang::EOpSubgroupMax:
6552 case glslang::EOpSubgroupInclusiveMax:
6553 case glslang::EOpSubgroupExclusiveMax:
6554 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006555#ifdef NV_EXTENSIONS
6556 case glslang::EOpSubgroupPartitionedMax:
6557 case glslang::EOpSubgroupPartitionedInclusiveMax:
6558 case glslang::EOpSubgroupPartitionedExclusiveMax:
6559#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006560 if (isFloat) {
6561 opCode = spv::OpGroupNonUniformFMax;
6562 } else if (isUnsigned) {
6563 opCode = spv::OpGroupNonUniformUMax;
6564 } else {
6565 opCode = spv::OpGroupNonUniformSMax;
6566 }
6567 break;
6568 case glslang::EOpSubgroupAnd:
6569 case glslang::EOpSubgroupInclusiveAnd:
6570 case glslang::EOpSubgroupExclusiveAnd:
6571 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006572#ifdef NV_EXTENSIONS
6573 case glslang::EOpSubgroupPartitionedAnd:
6574 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6575 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6576#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006577 if (isBool) {
6578 opCode = spv::OpGroupNonUniformLogicalAnd;
6579 } else {
6580 opCode = spv::OpGroupNonUniformBitwiseAnd;
6581 }
6582 break;
6583 case glslang::EOpSubgroupOr:
6584 case glslang::EOpSubgroupInclusiveOr:
6585 case glslang::EOpSubgroupExclusiveOr:
6586 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006587#ifdef NV_EXTENSIONS
6588 case glslang::EOpSubgroupPartitionedOr:
6589 case glslang::EOpSubgroupPartitionedInclusiveOr:
6590 case glslang::EOpSubgroupPartitionedExclusiveOr:
6591#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006592 if (isBool) {
6593 opCode = spv::OpGroupNonUniformLogicalOr;
6594 } else {
6595 opCode = spv::OpGroupNonUniformBitwiseOr;
6596 }
6597 break;
6598 case glslang::EOpSubgroupXor:
6599 case glslang::EOpSubgroupInclusiveXor:
6600 case glslang::EOpSubgroupExclusiveXor:
6601 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006602#ifdef NV_EXTENSIONS
6603 case glslang::EOpSubgroupPartitionedXor:
6604 case glslang::EOpSubgroupPartitionedInclusiveXor:
6605 case glslang::EOpSubgroupPartitionedExclusiveXor:
6606#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006607 if (isBool) {
6608 opCode = spv::OpGroupNonUniformLogicalXor;
6609 } else {
6610 opCode = spv::OpGroupNonUniformBitwiseXor;
6611 }
6612 break;
6613 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6614 case glslang::EOpSubgroupQuadSwapHorizontal:
6615 case glslang::EOpSubgroupQuadSwapVertical:
6616 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6617 default: assert(0 && "Unhandled subgroup operation!");
6618 }
6619
John Kessenich149afc32018-08-14 13:31:43 -06006620 // get the right Group Operation
6621 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006622 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006623 default:
6624 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006625 case glslang::EOpSubgroupBallotBitCount:
6626 case glslang::EOpSubgroupAdd:
6627 case glslang::EOpSubgroupMul:
6628 case glslang::EOpSubgroupMin:
6629 case glslang::EOpSubgroupMax:
6630 case glslang::EOpSubgroupAnd:
6631 case glslang::EOpSubgroupOr:
6632 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006633 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006634 break;
6635 case glslang::EOpSubgroupBallotInclusiveBitCount:
6636 case glslang::EOpSubgroupInclusiveAdd:
6637 case glslang::EOpSubgroupInclusiveMul:
6638 case glslang::EOpSubgroupInclusiveMin:
6639 case glslang::EOpSubgroupInclusiveMax:
6640 case glslang::EOpSubgroupInclusiveAnd:
6641 case glslang::EOpSubgroupInclusiveOr:
6642 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006643 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006644 break;
6645 case glslang::EOpSubgroupBallotExclusiveBitCount:
6646 case glslang::EOpSubgroupExclusiveAdd:
6647 case glslang::EOpSubgroupExclusiveMul:
6648 case glslang::EOpSubgroupExclusiveMin:
6649 case glslang::EOpSubgroupExclusiveMax:
6650 case glslang::EOpSubgroupExclusiveAnd:
6651 case glslang::EOpSubgroupExclusiveOr:
6652 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006653 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006654 break;
6655 case glslang::EOpSubgroupClusteredAdd:
6656 case glslang::EOpSubgroupClusteredMul:
6657 case glslang::EOpSubgroupClusteredMin:
6658 case glslang::EOpSubgroupClusteredMax:
6659 case glslang::EOpSubgroupClusteredAnd:
6660 case glslang::EOpSubgroupClusteredOr:
6661 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006662 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006663 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006664#ifdef NV_EXTENSIONS
6665 case glslang::EOpSubgroupPartitionedAdd:
6666 case glslang::EOpSubgroupPartitionedMul:
6667 case glslang::EOpSubgroupPartitionedMin:
6668 case glslang::EOpSubgroupPartitionedMax:
6669 case glslang::EOpSubgroupPartitionedAnd:
6670 case glslang::EOpSubgroupPartitionedOr:
6671 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006672 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006673 break;
6674 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6675 case glslang::EOpSubgroupPartitionedInclusiveMul:
6676 case glslang::EOpSubgroupPartitionedInclusiveMin:
6677 case glslang::EOpSubgroupPartitionedInclusiveMax:
6678 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6679 case glslang::EOpSubgroupPartitionedInclusiveOr:
6680 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006681 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006682 break;
6683 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6684 case glslang::EOpSubgroupPartitionedExclusiveMul:
6685 case glslang::EOpSubgroupPartitionedExclusiveMin:
6686 case glslang::EOpSubgroupPartitionedExclusiveMax:
6687 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6688 case glslang::EOpSubgroupPartitionedExclusiveOr:
6689 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006690 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006691 break;
6692#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006693 }
6694
John Kessenich149afc32018-08-14 13:31:43 -06006695 // build the instruction
6696 std::vector<spv::IdImmediate> spvGroupOperands;
6697
6698 // Every operation begins with the Execution Scope operand.
6699 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6700 spvGroupOperands.push_back(executionScope);
6701
6702 // Next, for all operations that use a Group Operation, push that as an operand.
6703 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006704 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006705 spvGroupOperands.push_back(groupOperand);
6706 }
6707
John Kessenich66011cb2018-03-06 16:12:04 -07006708 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006709 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6710 spv::IdImmediate operand = { true, *opIt };
6711 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006712 }
6713
6714 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006715 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006716 switch (op) {
6717 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006718 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6719 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6720 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6721 }
6722 if (directionId != spv::NoResult) {
6723 spv::IdImmediate direction = { true, directionId };
6724 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006725 }
6726
6727 return builder.createOp(opCode, typeId, spvGroupOperands);
6728}
6729
John Kessenich5e4b1242015-08-06 22:53:06 -06006730spv::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 -06006731{
John Kessenich66011cb2018-03-06 16:12:04 -07006732 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6733 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006734
John Kessenich140f3df2015-06-26 16:58:36 -06006735 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006736 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006737 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006738 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006739 spv::Id typeId0 = 0;
6740 if (consumedOperands > 0)
6741 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006742 spv::Id typeId1 = 0;
6743 if (consumedOperands > 1)
6744 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006745 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006746
6747 switch (op) {
6748 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006749 if (isFloat)
6750 libCall = spv::GLSLstd450FMin;
6751 else if (isUnsigned)
6752 libCall = spv::GLSLstd450UMin;
6753 else
6754 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006755 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006756 break;
6757 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006758 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006759 break;
6760 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006761 if (isFloat)
6762 libCall = spv::GLSLstd450FMax;
6763 else if (isUnsigned)
6764 libCall = spv::GLSLstd450UMax;
6765 else
6766 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006767 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006768 break;
6769 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006770 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006771 break;
6772 case glslang::EOpDot:
6773 opCode = spv::OpDot;
6774 break;
6775 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006776 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006777 break;
6778
6779 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006780 if (isFloat)
6781 libCall = spv::GLSLstd450FClamp;
6782 else if (isUnsigned)
6783 libCall = spv::GLSLstd450UClamp;
6784 else
6785 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006786 builder.promoteScalar(precision, operands.front(), operands[1]);
6787 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006788 break;
6789 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006790 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6791 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006792 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006793 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006794 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006795 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006796 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006797 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006798 break;
6799 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006800 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006801 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006802 break;
6803 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006804 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006805 builder.promoteScalar(precision, operands[0], operands[2]);
6806 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006807 break;
6808
6809 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006810 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006811 break;
6812 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006813 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006814 break;
6815 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006816 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006817 break;
6818 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006819 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006820 break;
6821 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006822 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006823 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006824 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006825#ifdef AMD_EXTENSIONS
6826 if (typeProxy == glslang::EbtFloat16)
6827 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6828#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006829 libCall = spv::GLSLstd450InterpolateAtSample;
6830 break;
6831 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006832#ifdef AMD_EXTENSIONS
6833 if (typeProxy == glslang::EbtFloat16)
6834 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6835#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006836 libCall = spv::GLSLstd450InterpolateAtOffset;
6837 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006838 case glslang::EOpAddCarry:
6839 opCode = spv::OpIAddCarry;
6840 typeId = builder.makeStructResultType(typeId0, typeId0);
6841 consumedOperands = 2;
6842 break;
6843 case glslang::EOpSubBorrow:
6844 opCode = spv::OpISubBorrow;
6845 typeId = builder.makeStructResultType(typeId0, typeId0);
6846 consumedOperands = 2;
6847 break;
6848 case glslang::EOpUMulExtended:
6849 opCode = spv::OpUMulExtended;
6850 typeId = builder.makeStructResultType(typeId0, typeId0);
6851 consumedOperands = 2;
6852 break;
6853 case glslang::EOpIMulExtended:
6854 opCode = spv::OpSMulExtended;
6855 typeId = builder.makeStructResultType(typeId0, typeId0);
6856 consumedOperands = 2;
6857 break;
6858 case glslang::EOpBitfieldExtract:
6859 if (isUnsigned)
6860 opCode = spv::OpBitFieldUExtract;
6861 else
6862 opCode = spv::OpBitFieldSExtract;
6863 break;
6864 case glslang::EOpBitfieldInsert:
6865 opCode = spv::OpBitFieldInsert;
6866 break;
6867
6868 case glslang::EOpFma:
6869 libCall = spv::GLSLstd450Fma;
6870 break;
6871 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006872 {
6873 libCall = spv::GLSLstd450FrexpStruct;
6874 assert(builder.isPointerType(typeId1));
6875 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006876 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006877#ifdef AMD_EXTENSIONS
6878 if (width == 16)
6879 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6880 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6881#endif
Rex Xu470026f2017-03-29 17:12:40 +08006882 if (builder.getNumComponents(operands[0]) == 1)
6883 frexpIntType = builder.makeIntegerType(width, true);
6884 else
6885 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6886 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6887 consumedOperands = 1;
6888 }
John Kessenich55e7d112015-11-15 21:33:39 -07006889 break;
6890 case glslang::EOpLdexp:
6891 libCall = spv::GLSLstd450Ldexp;
6892 break;
6893
Rex Xu574ab042016-04-14 16:53:07 +08006894 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006895 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006896
John Kessenich66011cb2018-03-06 16:12:04 -07006897 case glslang::EOpSubgroupBroadcast:
6898 case glslang::EOpSubgroupBallotBitExtract:
6899 case glslang::EOpSubgroupShuffle:
6900 case glslang::EOpSubgroupShuffleXor:
6901 case glslang::EOpSubgroupShuffleUp:
6902 case glslang::EOpSubgroupShuffleDown:
6903 case glslang::EOpSubgroupClusteredAdd:
6904 case glslang::EOpSubgroupClusteredMul:
6905 case glslang::EOpSubgroupClusteredMin:
6906 case glslang::EOpSubgroupClusteredMax:
6907 case glslang::EOpSubgroupClusteredAnd:
6908 case glslang::EOpSubgroupClusteredOr:
6909 case glslang::EOpSubgroupClusteredXor:
6910 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006911#ifdef NV_EXTENSIONS
6912 case glslang::EOpSubgroupPartitionedAdd:
6913 case glslang::EOpSubgroupPartitionedMul:
6914 case glslang::EOpSubgroupPartitionedMin:
6915 case glslang::EOpSubgroupPartitionedMax:
6916 case glslang::EOpSubgroupPartitionedAnd:
6917 case glslang::EOpSubgroupPartitionedOr:
6918 case glslang::EOpSubgroupPartitionedXor:
6919 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6920 case glslang::EOpSubgroupPartitionedInclusiveMul:
6921 case glslang::EOpSubgroupPartitionedInclusiveMin:
6922 case glslang::EOpSubgroupPartitionedInclusiveMax:
6923 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6924 case glslang::EOpSubgroupPartitionedInclusiveOr:
6925 case glslang::EOpSubgroupPartitionedInclusiveXor:
6926 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6927 case glslang::EOpSubgroupPartitionedExclusiveMul:
6928 case glslang::EOpSubgroupPartitionedExclusiveMin:
6929 case glslang::EOpSubgroupPartitionedExclusiveMax:
6930 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6931 case glslang::EOpSubgroupPartitionedExclusiveOr:
6932 case glslang::EOpSubgroupPartitionedExclusiveXor:
6933#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006934 return createSubgroupOperation(op, typeId, operands, typeProxy);
6935
Rex Xu9d93a232016-05-05 12:30:44 +08006936#ifdef AMD_EXTENSIONS
6937 case glslang::EOpSwizzleInvocations:
6938 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6939 libCall = spv::SwizzleInvocationsAMD;
6940 break;
6941 case glslang::EOpSwizzleInvocationsMasked:
6942 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6943 libCall = spv::SwizzleInvocationsMaskedAMD;
6944 break;
6945 case glslang::EOpWriteInvocation:
6946 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6947 libCall = spv::WriteInvocationAMD;
6948 break;
6949
6950 case glslang::EOpMin3:
6951 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6952 if (isFloat)
6953 libCall = spv::FMin3AMD;
6954 else {
6955 if (isUnsigned)
6956 libCall = spv::UMin3AMD;
6957 else
6958 libCall = spv::SMin3AMD;
6959 }
6960 break;
6961 case glslang::EOpMax3:
6962 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6963 if (isFloat)
6964 libCall = spv::FMax3AMD;
6965 else {
6966 if (isUnsigned)
6967 libCall = spv::UMax3AMD;
6968 else
6969 libCall = spv::SMax3AMD;
6970 }
6971 break;
6972 case glslang::EOpMid3:
6973 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6974 if (isFloat)
6975 libCall = spv::FMid3AMD;
6976 else {
6977 if (isUnsigned)
6978 libCall = spv::UMid3AMD;
6979 else
6980 libCall = spv::SMid3AMD;
6981 }
6982 break;
6983
6984 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006985 if (typeProxy == glslang::EbtFloat16)
6986 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006987 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6988 libCall = spv::InterpolateAtVertexAMD;
6989 break;
6990#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006991 case glslang::EOpBarrier:
6992 {
6993 // This is for the extended controlBarrier function, with four operands.
6994 // The unextended barrier() goes through createNoArgOperation.
6995 assert(operands.size() == 4);
6996 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6997 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6998 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6999 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7000 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7001 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7002 }
7003 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7004 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7005 }
7006 return 0;
7007 }
7008 break;
7009 case glslang::EOpMemoryBarrier:
7010 {
7011 // This is for the extended memoryBarrier function, with three operands.
7012 // The unextended memoryBarrier() goes through createNoArgOperation.
7013 assert(operands.size() == 3);
7014 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7015 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7016 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7017 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7018 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7019 }
7020 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7021 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7022 }
7023 return 0;
7024 }
7025 break;
Chao Chen3c366992018-09-19 11:41:59 -07007026
7027#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007028 case glslang::EOpReportIntersectionNV:
7029 {
7030 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007031 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007032 }
7033 break;
7034 case glslang::EOpTraceNV:
7035 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007036 builder.createNoResultOp(spv::OpTraceNV, operands);
7037 return 0;
7038 }
7039 break;
7040 case glslang::EOpExecuteCallableNV:
7041 {
7042 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007043 return 0;
7044 }
7045 break;
Chao Chen3c366992018-09-19 11:41:59 -07007046 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7047 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7048 return 0;
7049#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007050 default:
7051 return 0;
7052 }
7053
7054 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007055 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007056 // Use an extended instruction from the standard library.
7057 // Construct the call arguments, without modifying the original operands vector.
7058 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7059 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007060 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007061 } else if (opCode == spv::OpDot && !isFloat) {
7062 // int dot(int, int)
7063 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7064 const int componentCount = builder.getNumComponents(operands[0]);
7065 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7066 builder.setPrecision(mulOp, precision);
7067 id = builder.createCompositeExtract(mulOp, typeId, 0);
7068 for (int i = 1; i < componentCount; ++i) {
7069 builder.setPrecision(id, precision);
7070 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7071 }
John Kessenich2359bd02015-12-06 19:29:11 -07007072 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007073 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007074 case 0:
7075 // should all be handled by visitAggregate and createNoArgOperation
7076 assert(0);
7077 return 0;
7078 case 1:
7079 // should all be handled by createUnaryOperation
7080 assert(0);
7081 return 0;
7082 case 2:
7083 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7084 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007085 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007086 // anything 3 or over doesn't have l-value operands, so all should be consumed
7087 assert(consumedOperands == operands.size());
7088 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007089 break;
7090 }
7091 }
7092
John Kessenich55e7d112015-11-15 21:33:39 -07007093 // Decode the return types that were structures
7094 switch (op) {
7095 case glslang::EOpAddCarry:
7096 case glslang::EOpSubBorrow:
7097 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7098 id = builder.createCompositeExtract(id, typeId0, 0);
7099 break;
7100 case glslang::EOpUMulExtended:
7101 case glslang::EOpIMulExtended:
7102 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7103 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7104 break;
7105 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007106 {
7107 assert(operands.size() == 2);
7108 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7109 // "exp" is floating-point type (from HLSL intrinsic)
7110 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7111 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7112 builder.createStore(member1, operands[1]);
7113 } else
7114 // "exp" is integer type (from GLSL built-in function)
7115 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7116 id = builder.createCompositeExtract(id, typeId0, 0);
7117 }
John Kessenich55e7d112015-11-15 21:33:39 -07007118 break;
7119 default:
7120 break;
7121 }
7122
John Kessenich32cfd492016-02-02 12:37:46 -07007123 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007124}
7125
Rex Xu9d93a232016-05-05 12:30:44 +08007126// Intrinsics with no arguments (or no return value, and no precision).
7127spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007128{
Jeff Bolz36831c92018-09-05 10:11:41 -05007129 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7130 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007131
7132 switch (op) {
7133 case glslang::EOpEmitVertex:
7134 builder.createNoResultOp(spv::OpEmitVertex);
7135 return 0;
7136 case glslang::EOpEndPrimitive:
7137 builder.createNoResultOp(spv::OpEndPrimitive);
7138 return 0;
7139 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007140 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007141 if (glslangIntermediate->usingVulkanMemoryModel()) {
7142 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7143 spv::MemorySemanticsOutputMemoryKHRMask |
7144 spv::MemorySemanticsAcquireReleaseMask);
7145 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7146 } else {
7147 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7148 }
John Kessenich82979362017-12-11 04:02:24 -07007149 } else {
7150 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7151 spv::MemorySemanticsWorkgroupMemoryMask |
7152 spv::MemorySemanticsAcquireReleaseMask);
7153 }
John Kessenich140f3df2015-06-26 16:58:36 -06007154 return 0;
7155 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007156 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7157 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007158 return 0;
7159 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007160 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7161 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007162 return 0;
7163 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007164 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7165 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007166 return 0;
7167 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007168 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7169 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007170 return 0;
7171 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007172 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7173 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007174 return 0;
7175 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007176 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7177 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007178 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007179 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007180 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007181 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007182 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007183 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007184 case glslang::EOpDeviceMemoryBarrier:
7185 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7186 spv::MemorySemanticsImageMemoryMask |
7187 spv::MemorySemanticsAcquireReleaseMask);
7188 return 0;
7189 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7190 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7191 spv::MemorySemanticsImageMemoryMask |
7192 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007193 return 0;
7194 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007195 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7196 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007197 return 0;
7198 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007199 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7200 spv::MemorySemanticsWorkgroupMemoryMask |
7201 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007202 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007203 case glslang::EOpSubgroupBarrier:
7204 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7205 spv::MemorySemanticsAcquireReleaseMask);
7206 return spv::NoResult;
7207 case glslang::EOpSubgroupMemoryBarrier:
7208 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7209 spv::MemorySemanticsAcquireReleaseMask);
7210 return spv::NoResult;
7211 case glslang::EOpSubgroupMemoryBarrierBuffer:
7212 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7213 spv::MemorySemanticsAcquireReleaseMask);
7214 return spv::NoResult;
7215 case glslang::EOpSubgroupMemoryBarrierImage:
7216 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7217 spv::MemorySemanticsAcquireReleaseMask);
7218 return spv::NoResult;
7219 case glslang::EOpSubgroupMemoryBarrierShared:
7220 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7221 spv::MemorySemanticsAcquireReleaseMask);
7222 return spv::NoResult;
7223 case glslang::EOpSubgroupElect: {
7224 std::vector<spv::Id> operands;
7225 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7226 }
Rex Xu9d93a232016-05-05 12:30:44 +08007227#ifdef AMD_EXTENSIONS
7228 case glslang::EOpTime:
7229 {
7230 std::vector<spv::Id> args; // Dummy arguments
7231 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7232 return builder.setPrecision(id, precision);
7233 }
7234#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007235#ifdef NV_EXTENSIONS
7236 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007237 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007238 return 0;
7239 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007240 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007241 return 0;
7242#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007243 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007244 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007245 return 0;
7246 }
7247}
7248
7249spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7250{
John Kessenich2f273362015-07-18 22:34:27 -06007251 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007252 spv::Id id;
7253 if (symbolValues.end() != iter) {
7254 id = iter->second;
7255 return id;
7256 }
7257
7258 // it was not found, create it
7259 id = createSpvVariable(symbol);
7260 symbolValues[symbol->getId()] = id;
7261
Rex Xuc884b4a2016-06-29 15:03:44 +08007262 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007263 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7264 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7265 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007266#ifdef NV_EXTENSIONS
7267 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7268#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007269 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007270 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007271 if (symbol->getQualifier().hasIndex())
7272 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7273 if (symbol->getQualifier().hasComponent())
7274 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007275 // atomic counters use this:
7276 if (symbol->getQualifier().hasOffset())
7277 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007278 }
7279
scygan2c864272016-05-18 18:09:17 +02007280 if (symbol->getQualifier().hasLocation())
7281 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007282 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007283 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007284 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007285 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007286 }
John Kessenich140f3df2015-06-26 16:58:36 -06007287 if (symbol->getQualifier().hasSet())
7288 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007289 else if (IsDescriptorResource(symbol->getType())) {
7290 // default to 0
7291 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7292 }
John Kessenich140f3df2015-06-26 16:58:36 -06007293 if (symbol->getQualifier().hasBinding())
7294 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007295 else if (IsDescriptorResource(symbol->getType())) {
7296 // default to 0
7297 builder.addDecoration(id, spv::DecorationBinding, 0);
7298 }
John Kessenich6c292d32016-02-15 20:58:50 -07007299 if (symbol->getQualifier().hasAttachment())
7300 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007301 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007302 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007303 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007304 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007305 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7306 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7307 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7308 }
7309 if (symbol->getQualifier().hasXfbOffset())
7310 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007311 }
7312
Rex Xu1da878f2016-02-21 20:59:01 +08007313 if (symbol->getType().isImage()) {
7314 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007315 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007316 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007317 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007318 }
7319
John Kessenich140f3df2015-06-26 16:58:36 -06007320 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007321 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007322 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007323 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007324
John Kessenich5611c6d2018-04-05 11:25:02 -06007325 // nonuniform
7326 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7327
John Kessenichecba76f2017-01-06 00:34:48 -07007328#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007329 if (builtIn == spv::BuiltInSampleMask) {
7330 spv::Decoration decoration;
7331 // GL_NV_sample_mask_override_coverage extension
7332 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007333 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007334 else
7335 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007336 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007337 if (decoration != spv::DecorationMax) {
7338 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7339 }
7340 }
chaoc771d89f2017-01-13 01:10:53 -08007341 else if (builtIn == spv::BuiltInLayer) {
7342 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007343 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007344 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007345 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7346 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7347 }
John Kessenichb41bff62017-08-11 13:07:17 -06007348 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007349 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7350 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007351 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7352 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7353 }
7354 }
7355
chaoc6e5acae2016-12-20 13:28:52 -08007356 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007357 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007358 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007359 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7360 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007361 if (symbol->getQualifier().pervertexNV) {
7362 builder.addDecoration(id, spv::DecorationPerVertexNV);
7363 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7364 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7365 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007366#endif
7367
John Kessenich5d610ee2018-03-07 18:05:55 -07007368 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7369 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7370 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7371 symbol->getType().getQualifier().semanticName);
7372 }
7373
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007374 if (symbol->getBasicType() == glslang::EbtReference) {
7375 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7376 }
7377
John Kessenich140f3df2015-06-26 16:58:36 -06007378 return id;
7379}
7380
Chao Chen3c366992018-09-19 11:41:59 -07007381#ifdef NV_EXTENSIONS
7382// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7383void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7384{
7385 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007386 if (qualifier.perPrimitiveNV) {
7387 // Need to add capability/extension for fragment shader.
7388 // Mesh shader already adds this by default.
7389 if (glslangIntermediate->getStage() == EShLangFragment) {
7390 builder.addCapability(spv::CapabilityMeshShadingNV);
7391 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7392 }
Chao Chen3c366992018-09-19 11:41:59 -07007393 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007394 }
Chao Chen3c366992018-09-19 11:41:59 -07007395 if (qualifier.perViewNV)
7396 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7397 if (qualifier.perTaskNV)
7398 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7399 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007400 if (qualifier.perPrimitiveNV) {
7401 // Need to add capability/extension for fragment shader.
7402 // Mesh shader already adds this by default.
7403 if (glslangIntermediate->getStage() == EShLangFragment) {
7404 builder.addCapability(spv::CapabilityMeshShadingNV);
7405 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7406 }
Chao Chen3c366992018-09-19 11:41:59 -07007407 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007408 }
Chao Chen3c366992018-09-19 11:41:59 -07007409 if (qualifier.perViewNV)
7410 builder.addDecoration(id, spv::DecorationPerViewNV);
7411 if (qualifier.perTaskNV)
7412 builder.addDecoration(id, spv::DecorationPerTaskNV);
7413 }
7414}
7415#endif
7416
John Kessenich55e7d112015-11-15 21:33:39 -07007417// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007418// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007419//
7420// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7421//
7422// Recursively walk the nodes. The nodes form a tree whose leaves are
7423// regular constants, which themselves are trees that createSpvConstant()
7424// recursively walks. So, this function walks the "top" of the tree:
7425// - emit specialization constant-building instructions for specConstant
7426// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007427spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007428{
John Kessenich7cc0e282016-03-20 00:46:02 -06007429 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007430
qining4f4bb812016-04-03 23:55:17 -04007431 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007432 if (! node.getQualifier().specConstant) {
7433 // hand off to the non-spec-constant path
7434 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7435 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007436 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007437 nextConst, false);
7438 }
7439
7440 // We now know we have a specialization constant to build
7441
John Kessenichd94c0032016-05-30 19:29:40 -06007442 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007443 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7444 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7445 std::vector<spv::Id> dimConstId;
7446 for (int dim = 0; dim < 3; ++dim) {
7447 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7448 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007449 if (specConst) {
7450 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7451 glslangIntermediate->getLocalSizeSpecId(dim));
7452 }
qining4f4bb812016-04-03 23:55:17 -04007453 }
7454 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7455 }
7456
7457 // An AST node labelled as specialization constant should be a symbol node.
7458 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7459 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007460 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007461 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007462 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7463 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7464 // will set the builder into spec constant op instruction generating mode.
7465 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007466 result = accessChainLoad(sub_tree->getType());
7467 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007468 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007469 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007470 } else {
7471 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007472 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007473 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007474 builder.addName(result, sn->getName().c_str());
7475 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007476 }
qining4f4bb812016-04-03 23:55:17 -04007477
7478 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7479 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007480 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007481 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007482}
7483
John Kessenich140f3df2015-06-26 16:58:36 -06007484// Use 'consts' as the flattened glslang source of scalar constants to recursively
7485// build the aggregate SPIR-V constant.
7486//
7487// If there are not enough elements present in 'consts', 0 will be substituted;
7488// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7489//
qining08408382016-03-21 09:51:37 -04007490spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007491{
7492 // vector of constants for SPIR-V
7493 std::vector<spv::Id> spvConsts;
7494
7495 // Type is used for struct and array constants
7496 spv::Id typeId = convertGlslangToSpvType(glslangType);
7497
7498 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007499 glslang::TType elementType(glslangType, 0);
7500 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007501 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007502 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007503 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007504 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007505 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007506 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007507 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7508 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007509 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007510 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007511 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7512 bool zero = nextConst >= consts.size();
7513 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007514 case glslang::EbtInt8:
7515 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7516 break;
7517 case glslang::EbtUint8:
7518 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7519 break;
7520 case glslang::EbtInt16:
7521 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7522 break;
7523 case glslang::EbtUint16:
7524 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7525 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007526 case glslang::EbtInt:
7527 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7528 break;
7529 case glslang::EbtUint:
7530 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7531 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007532 case glslang::EbtInt64:
7533 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7534 break;
7535 case glslang::EbtUint64:
7536 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7537 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007538 case glslang::EbtFloat:
7539 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7540 break;
7541 case glslang::EbtDouble:
7542 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7543 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007544 case glslang::EbtFloat16:
7545 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7546 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007547 case glslang::EbtBool:
7548 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7549 break;
7550 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007551 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007552 break;
7553 }
7554 ++nextConst;
7555 }
7556 } else {
7557 // we have a non-aggregate (scalar) constant
7558 bool zero = nextConst >= consts.size();
7559 spv::Id scalar = 0;
7560 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007561 case glslang::EbtInt8:
7562 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7563 break;
7564 case glslang::EbtUint8:
7565 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7566 break;
7567 case glslang::EbtInt16:
7568 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7569 break;
7570 case glslang::EbtUint16:
7571 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7572 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007573 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007574 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007575 break;
7576 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007577 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007578 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007579 case glslang::EbtInt64:
7580 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7581 break;
7582 case glslang::EbtUint64:
7583 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7584 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007585 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007586 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007587 break;
7588 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007589 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007590 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007591 case glslang::EbtFloat16:
7592 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7593 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007594 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007595 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007596 break;
7597 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007598 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007599 break;
7600 }
7601 ++nextConst;
7602 return scalar;
7603 }
7604
7605 return builder.makeCompositeConstant(typeId, spvConsts);
7606}
7607
John Kessenich7c1aa102015-10-15 13:29:11 -06007608// Return true if the node is a constant or symbol whose reading has no
7609// non-trivial observable cost or effect.
7610bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7611{
7612 // don't know what this is
7613 if (node == nullptr)
7614 return false;
7615
7616 // a constant is safe
7617 if (node->getAsConstantUnion() != nullptr)
7618 return true;
7619
7620 // not a symbol means non-trivial
7621 if (node->getAsSymbolNode() == nullptr)
7622 return false;
7623
7624 // a symbol, depends on what's being read
7625 switch (node->getType().getQualifier().storage) {
7626 case glslang::EvqTemporary:
7627 case glslang::EvqGlobal:
7628 case glslang::EvqIn:
7629 case glslang::EvqInOut:
7630 case glslang::EvqConst:
7631 case glslang::EvqConstReadOnly:
7632 case glslang::EvqUniform:
7633 return true;
7634 default:
7635 return false;
7636 }
qining25262b32016-05-06 17:25:16 -04007637}
John Kessenich7c1aa102015-10-15 13:29:11 -06007638
7639// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007640// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007641// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007642// Return true if trivial.
7643bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7644{
7645 if (node == nullptr)
7646 return false;
7647
John Kessenich84cc15f2017-05-24 16:44:47 -06007648 // count non scalars as trivial, as well as anything coming from HLSL
7649 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007650 return true;
7651
John Kessenich7c1aa102015-10-15 13:29:11 -06007652 // symbols and constants are trivial
7653 if (isTrivialLeaf(node))
7654 return true;
7655
7656 // otherwise, it needs to be a simple operation or one or two leaf nodes
7657
7658 // not a simple operation
7659 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7660 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7661 if (binaryNode == nullptr && unaryNode == nullptr)
7662 return false;
7663
7664 // not on leaf nodes
7665 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7666 return false;
7667
7668 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7669 return false;
7670 }
7671
7672 switch (node->getAsOperator()->getOp()) {
7673 case glslang::EOpLogicalNot:
7674 case glslang::EOpConvIntToBool:
7675 case glslang::EOpConvUintToBool:
7676 case glslang::EOpConvFloatToBool:
7677 case glslang::EOpConvDoubleToBool:
7678 case glslang::EOpEqual:
7679 case glslang::EOpNotEqual:
7680 case glslang::EOpLessThan:
7681 case glslang::EOpGreaterThan:
7682 case glslang::EOpLessThanEqual:
7683 case glslang::EOpGreaterThanEqual:
7684 case glslang::EOpIndexDirect:
7685 case glslang::EOpIndexDirectStruct:
7686 case glslang::EOpLogicalXor:
7687 case glslang::EOpAny:
7688 case glslang::EOpAll:
7689 return true;
7690 default:
7691 return false;
7692 }
7693}
7694
7695// Emit short-circuiting code, where 'right' is never evaluated unless
7696// the left side is true (for &&) or false (for ||).
7697spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7698{
7699 spv::Id boolTypeId = builder.makeBoolType();
7700
7701 // emit left operand
7702 builder.clearAccessChain();
7703 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007704 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007705
7706 // Operands to accumulate OpPhi operands
7707 std::vector<spv::Id> phiOperands;
7708 // accumulate left operand's phi information
7709 phiOperands.push_back(leftId);
7710 phiOperands.push_back(builder.getBuildPoint()->getId());
7711
7712 // Make the two kinds of operation symmetric with a "!"
7713 // || => emit "if (! left) result = right"
7714 // && => emit "if ( left) result = right"
7715 //
7716 // TODO: this runtime "not" for || could be avoided by adding functionality
7717 // to 'builder' to have an "else" without an "then"
7718 if (op == glslang::EOpLogicalOr)
7719 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7720
7721 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007722 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007723
7724 // emit right operand as the "then" part of the "if"
7725 builder.clearAccessChain();
7726 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007727 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007728
7729 // accumulate left operand's phi information
7730 phiOperands.push_back(rightId);
7731 phiOperands.push_back(builder.getBuildPoint()->getId());
7732
7733 // finish the "if"
7734 ifBuilder.makeEndIf();
7735
7736 // phi together the two results
7737 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7738}
7739
Frank Henigman541f7bb2018-01-16 00:18:26 -05007740#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007741// Return type Id of the imported set of extended instructions corresponds to the name.
7742// Import this set if it has not been imported yet.
7743spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7744{
7745 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7746 return extBuiltinMap[name];
7747 else {
Rex Xu51596642016-09-21 18:56:12 +08007748 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007749 spv::Id extBuiltins = builder.import(name);
7750 extBuiltinMap[name] = extBuiltins;
7751 return extBuiltins;
7752 }
7753}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007754#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007755
John Kessenich140f3df2015-06-26 16:58:36 -06007756}; // end anonymous namespace
7757
7758namespace glslang {
7759
John Kessenich68d78fd2015-07-12 19:28:10 -06007760void GetSpirvVersion(std::string& version)
7761{
John Kessenich9e55f632015-07-15 10:03:39 -06007762 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007763 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007764 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007765 version = buf;
7766}
7767
John Kessenicha372a3e2017-11-02 22:32:14 -06007768// For low-order part of the generator's magic number. Bump up
7769// when there is a change in the style (e.g., if SSA form changes,
7770// or a different instruction sequence to do something gets used).
7771int GetSpirvGeneratorVersion()
7772{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007773 // return 1; // start
7774 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007775 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007776 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007777 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007778 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7779 // versions 4 and 6 each generate OpArrayLength as it has long been done
7780 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007781}
7782
John Kessenich140f3df2015-06-26 16:58:36 -06007783// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007784void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007785{
7786 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007787 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007788 if (out.fail())
7789 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007790 for (int i = 0; i < (int)spirv.size(); ++i) {
7791 unsigned int word = spirv[i];
7792 out.write((const char*)&word, 4);
7793 }
7794 out.close();
7795}
7796
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007797// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007798void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007799{
7800 std::ofstream out;
7801 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007802 if (out.fail())
7803 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007804 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007805 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007806 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007807 if (varName != nullptr) {
7808 out << "\t #pragma once" << std::endl;
7809 out << "const uint32_t " << varName << "[] = {" << std::endl;
7810 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007811 const int WORDS_PER_LINE = 8;
7812 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7813 out << "\t";
7814 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7815 const unsigned int word = spirv[i + j];
7816 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7817 if (i + j + 1 < (int)spirv.size()) {
7818 out << ",";
7819 }
7820 }
7821 out << std::endl;
7822 }
Flavio15017db2017-02-15 14:29:33 -08007823 if (varName != nullptr) {
7824 out << "};";
7825 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007826 out.close();
7827}
7828
John Kessenich140f3df2015-06-26 16:58:36 -06007829//
7830// Set up the glslang traversal
7831//
John Kessenich4e11b612018-08-30 16:56:59 -06007832void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007833{
Lei Zhang17535f72016-05-04 15:55:59 -04007834 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007835 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007836}
7837
John Kessenich4e11b612018-08-30 16:56:59 -06007838void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007839 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007840{
John Kessenich140f3df2015-06-26 16:58:36 -06007841 TIntermNode* root = intermediate.getTreeRoot();
7842
7843 if (root == 0)
7844 return;
7845
John Kessenich4e11b612018-08-30 16:56:59 -06007846 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007847 if (options == nullptr)
7848 options = &defaultOptions;
7849
John Kessenich4e11b612018-08-30 16:56:59 -06007850 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007851
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007852 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007853 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007854 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007855 it.dumpSpv(spirv);
7856
GregFfb03a552018-03-29 11:49:14 -06007857#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007858 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7859 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007860 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007861 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007862
John Kessenich4e11b612018-08-30 16:56:59 -06007863 if (options->validate)
7864 SpirvToolsValidate(intermediate, spirv, logger);
7865
John Kessenich717c80a2018-08-23 15:17:10 -06007866 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007867 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007868
GregFcd1f1692017-09-21 18:40:22 -06007869#endif
7870
John Kessenich4e11b612018-08-30 16:56:59 -06007871 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007872}
7873
7874}; // end namespace glslang