blob: e41bb5de6eb687b177da6c212c9c19cbe8fda1d5 [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 Kessenich56364b62020-03-01 04:51:40 -07003// Copyright (C) 2015-2020 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
Torosdagli06c2eee2020-03-19 11:09:57 -04005// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06008//
John Kessenich927608b2017-01-06 12:34:14 -07009// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions
11// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060012//
13// Redistributions of source code must retain the above copyright
14// notice, this list of conditions and the following disclaimer.
15//
16// Redistributions in binary form must reproduce the above
17// copyright notice, this list of conditions and the following
18// disclaimer in the documentation and/or other materials provided
19// with the distribution.
20//
21// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22// contributors may be used to endorse or promote products derived
23// from this software without specific prior written permission.
24//
John Kessenich927608b2017-01-06 12:34:14 -070025// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060037
38//
John Kessenich140f3df2015-06-26 16:58:36 -060039// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080047 #include "GLSL.std.450.h"
48 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070049 #include "GLSL.ext.EXT.h"
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
chaoc0ad6a4e2016-12-19 16:29:34 -080051 #include "GLSL.ext.NV.h"
Jeff Bolz04d73732019-05-31 13:06:01 -050052 #include "NonSemanticDebugPrintf.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
John Kessenichb9197c82019-08-11 07:41:45 -060092 public:
93 OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
94 precision(precision)
95#ifndef GLSLANG_WEB
96 ,
97 noContraction(noContraction),
98 nonUniform(nonUniform)
99#endif
100 { }
101
John Kessenichead86222018-03-28 18:01:20 -0600102 spv::Decoration precision;
John Kessenichb9197c82019-08-11 07:41:45 -0600103
104#ifdef GLSLANG_WEB
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400105 void addNoContraction(spv::Builder&, spv::Id) const { }
106 void addNonUniform(spv::Builder&, spv::Id) const { }
John Kessenichb9197c82019-08-11 07:41:45 -0600107#else
Ryan Harrison7c9accb2019-10-11 11:00:57 -0400108 void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
109 void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
John Kessenichb9197c82019-08-11 07:41:45 -0600110 protected:
111 spv::Decoration noContraction;
112 spv::Decoration nonUniform;
113#endif
114
John Kessenichead86222018-03-28 18:01:20 -0600115};
116
117} // namespace
qining4c912612016-04-01 10:35:16 -0400118
John Kessenich140f3df2015-06-26 16:58:36 -0600119//
120// The main holder of information for translating glslang to SPIR-V.
121//
122// Derives from the AST walking base class.
123//
124class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
125public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700126 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
127 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700128 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600129
130 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
131 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
132 void visitConstantUnion(glslang::TIntermConstantUnion*);
133 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
134 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
135 void visitSymbol(glslang::TIntermSymbol* symbol);
136 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
137 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
138 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
139
John Kessenichfca82622016-11-26 13:23:20 -0700140 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700141 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600142
143protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700144 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
145 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
146
Rex Xu17ff3432016-10-14 17:41:45 +0800147 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800148 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600149 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500150 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
151 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
152 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
153 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100154 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700155 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700156 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
157 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700158 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600159 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600160 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich9c14f772019-06-17 08:38:35 -0600161 spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600163 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
164 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
165 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600166 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600167 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600168 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600169 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600170 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
171 glslang::TLayoutPacking, const glslang::TQualifier&);
172 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
173 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700174 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700175 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800176 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600177 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700178 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700179 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
180 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700181 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
182 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100183 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600184
John Kessenich6fccb3c2016-09-19 16:01:41 -0600185 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600186 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600187 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600188 void makeFunctions(const glslang::TIntermSequence&);
189 void makeGlobalInitializers(const glslang::TIntermSequence&);
190 void visitFunctions(const glslang::TIntermSequence&);
191 void handleFunctionEntry(const glslang::TIntermAggregate* node);
John Kessenich8985fc92020-03-03 10:25:07 -0700192 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
193 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -0600194 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
195 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
197
John Kessenichead86222018-03-28 18:01:20 -0600198 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
199 glslang::TBasicType typeProxy, bool reduceComparison = true);
200 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
201 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
John Kessenich8985fc92020-03-03 10:25:07 -0700202 glslang::TBasicType typeProxy,
203 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -0600204 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
205 glslang::TBasicType typeProxy);
206 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
207 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600208 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600209 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich8985fc92020-03-03 10:25:07 -0700210 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
211 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
212 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
213 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
214 glslang::TBasicType typeProxy);
215 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
216 spv::Id typeId, std::vector<spv::Id>& operands);
217 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
218 glslang::TBasicType typeProxy);
219 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
220 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800221 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600222 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700223 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
qining08408382016-03-21 09:51:37 -0400224 spv::Id createSpvConstant(const glslang::TIntermTyped&);
John Kessenich8985fc92020-03-03 10:25:07 -0700225 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
226 int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600227 bool isTrivialLeaf(const glslang::TIntermTyped* node);
228 bool isTrivial(const glslang::TIntermTyped* node);
229 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800230 spv::Id getExtBuiltins(const char* name);
Daniel Kochdb32b242020-03-17 20:42:47 -0400231 std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
John Kessenich9c14f772019-06-17 08:38:35 -0600232 spv::Id translateForcedType(spv::Id object);
Jeff Bolz53134492019-06-25 13:31:10 -0500233 spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
John Kessenich140f3df2015-06-26 16:58:36 -0600234
John Kessenich121853f2017-05-31 17:11:16 -0600235 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600237 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700238 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 int sequenceDepth;
240
Lei Zhang17535f72016-05-04 15:55:59 -0400241 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400242
John Kessenich140f3df2015-06-26 16:58:36 -0600243 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
244 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700245 bool inEntryPoint;
246 bool entryPointTerminated;
John Kessenich8985fc92020-03-03 10:25:07 -0700247 bool linkageOnly; // true when visiting the set of objects in the AST present only for
248 // establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700249 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600250 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600251 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600252 spv::Id stdBuiltins;
Jeff Bolz04d73732019-05-31 13:06:01 -0500253 spv::Id nonSemanticDebugPrintf;
Rex Xu9d93a232016-05-05 12:30:44 +0800254 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600255
John Kessenich2f273362015-07-18 22:34:27 -0600256 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich8985fc92020-03-03 10:25:07 -0700257 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues,
258 // rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600259 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700260 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700261 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
Roy05a5b532020-01-03 16:21:34 +0800262 std::unordered_map<int, std::vector<int>> memberRemapper;
263 // for mapping glslang symbol struct to symbol Id
264 std::unordered_map<const glslang::TTypeList*, int> glslangTypeToIdMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700266 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600267 // Map pointee types for EbtReference to their forward pointers
268 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600269 // Type forcing, for when SPIR-V wants a different type than the AST,
270 // requiring local translation to and from SPIR-V type on every access.
271 // Maps <builtin-variable-id -> AST-required-type-id>
272 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600273};
274
275//
276// Helper functions for translating glslang representations to SPIR-V enumerants.
277//
278
279// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700280spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600281{
John Kessenich155d3512019-08-08 23:29:20 -0600282#ifdef GLSLANG_WEB
283 return spv::SourceLanguageESSL;
284#endif
285
John Kessenich66e2faf2016-03-12 18:34:36 -0700286 switch (source) {
287 case glslang::EShSourceGlsl:
288 switch (profile) {
289 case ENoProfile:
290 case ECoreProfile:
291 case ECompatibilityProfile:
292 return spv::SourceLanguageGLSL;
293 case EEsProfile:
294 return spv::SourceLanguageESSL;
295 default:
296 return spv::SourceLanguageUnknown;
297 }
298 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600299 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600300 default:
301 return spv::SourceLanguageUnknown;
302 }
303}
304
305// Translate glslang language (stage) to SPIR-V execution model.
306spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
307{
308 switch (stage) {
309 case EShLangVertex: return spv::ExecutionModelVertex;
John Kessenicha28f7a72019-08-06 07:00:58 -0600310 case EShLangFragment: return spv::ExecutionModelFragment;
John Kessenicha28f7a72019-08-06 07:00:58 -0600311 case EShLangCompute: return spv::ExecutionModelGLCompute;
John Kessenich51ed01c2019-10-10 11:40:11 -0600312#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -0600313 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
314 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
315 case EShLangGeometry: return spv::ExecutionModelGeometry;
Daniel Kochdb32b242020-03-17 20:42:47 -0400316 case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
317 case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
318 case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
319 case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
320 case EShLangMiss: return spv::ExecutionModelMissKHR;
321 case EShLangCallable: return spv::ExecutionModelCallableKHR;
Chao Chen3c366992018-09-19 11:41:59 -0700322 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
323 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
324#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600325 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700326 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600327 return spv::ExecutionModelFragment;
328 }
329}
330
John Kessenich140f3df2015-06-26 16:58:36 -0600331// Translate glslang sampler type to SPIR-V dimensionality.
332spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
333{
334 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700335 case glslang::Esd1D: return spv::Dim1D;
336 case glslang::Esd2D: return spv::Dim2D;
337 case glslang::Esd3D: return spv::Dim3D;
338 case glslang::EsdCube: return spv::DimCube;
339 case glslang::EsdRect: return spv::DimRect;
340 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700341 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700343 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return spv::Dim2D;
345 }
346}
347
John Kessenichf6640762016-08-01 19:44:00 -0600348// Translate glslang precision to SPIR-V precision decorations.
349spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600350{
John Kessenichf6640762016-08-01 19:44:00 -0600351 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700352 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600353 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 default:
355 return spv::NoPrecision;
356 }
357}
358
John Kessenichf6640762016-08-01 19:44:00 -0600359// Translate glslang type to SPIR-V precision decorations.
360spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
361{
362 return TranslatePrecisionDecoration(type.getQualifier().precision);
363}
364
John Kessenich140f3df2015-06-26 16:58:36 -0600365// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600366spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600367{
368 if (type.getBasicType() == glslang::EbtBlock) {
369 switch (type.getQualifier().storage) {
370 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600371 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 case glslang::EvqVaryingIn: return spv::DecorationBlock;
373 case glslang::EvqVaryingOut: return spv::DecorationBlock;
John Kessenicha28f7a72019-08-06 07:00:58 -0600374#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400375 case glslang::EvqPayload: return spv::DecorationBlock;
376 case glslang::EvqPayloadIn: return spv::DecorationBlock;
377 case glslang::EvqHitAttr: return spv::DecorationBlock;
378 case glslang::EvqCallableData: return spv::DecorationBlock;
379 case glslang::EvqCallableDataIn: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700380#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600381 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700382 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 break;
384 }
385 }
386
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600388}
389
Rex Xu1da878f2016-02-21 20:59:01 +0800390// Translate glslang type to SPIR-V memory decorations.
John Kessenich8985fc92020-03-03 10:25:07 -0700391void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
392 bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800393{
Jeff Bolz36831c92018-09-05 10:11:41 -0500394 if (!useVulkanMemoryModel) {
John Kessenichf8d1d742019-10-21 06:55:11 -0600395 if (qualifier.isCoherent())
Jeff Bolz36831c92018-09-05 10:11:41 -0500396 memory.push_back(spv::DecorationCoherent);
John Kessenichf8d1d742019-10-21 06:55:11 -0600397 if (qualifier.isVolatile()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500398 memory.push_back(spv::DecorationVolatile);
399 memory.push_back(spv::DecorationCoherent);
400 }
John Kessenich14b85d32018-06-04 15:36:03 -0600401 }
John Kessenichf8d1d742019-10-21 06:55:11 -0600402 if (qualifier.isRestrict())
Rex Xu1da878f2016-02-21 20:59:01 +0800403 memory.push_back(spv::DecorationRestrict);
John Kessenichdeec1932019-08-13 08:00:30 -0600404 if (qualifier.isReadOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800405 memory.push_back(spv::DecorationNonWritable);
John Kessenichdeec1932019-08-13 08:00:30 -0600406 if (qualifier.isWriteOnly())
Rex Xu1da878f2016-02-21 20:59:01 +0800407 memory.push_back(spv::DecorationNonReadable);
408}
409
John Kessenich140f3df2015-06-26 16:58:36 -0600410// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700411spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600412{
413 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700414 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600415 case glslang::ElmRowMajor:
416 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700417 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700419 default:
420 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422 }
423 } else {
424 switch (type.getBasicType()) {
425 default:
John Kessenich4016e382016-07-15 11:53:56 -0600426 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600427 break;
428 case glslang::EbtBlock:
429 switch (type.getQualifier().storage) {
430 case glslang::EvqUniform:
431 case glslang::EvqBuffer:
432 switch (type.getQualifier().layoutPacking) {
433 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600434 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
435 default:
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600437 }
438 case glslang::EvqVaryingIn:
439 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700440 if (type.getQualifier().isTaskMemory()) {
441 switch (type.getQualifier().layoutPacking) {
442 case glslang::ElpShared: return spv::DecorationGLSLShared;
443 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
444 default: break;
445 }
446 } else {
447 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
448 }
John Kessenich4016e382016-07-15 11:53:56 -0600449 return spv::DecorationMax;
John Kessenicha28f7a72019-08-06 07:00:58 -0600450#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -0400451 case glslang::EvqPayload:
452 case glslang::EvqPayloadIn:
453 case glslang::EvqHitAttr:
454 case glslang::EvqCallableData:
455 case glslang::EvqCallableDataIn:
Chao Chenb50c02e2018-09-19 11:42:24 -0700456 return spv::DecorationMax;
457#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600458 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700459 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600460 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600461 }
462 }
463 }
464}
465
466// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600467// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700468// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800469spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600470{
Rex Xubbceed72016-05-21 09:40:44 +0800471 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700472 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600473 return spv::DecorationMax;
John Kessenich7015bd62019-08-01 03:28:08 -0600474 else if (qualifier.isNonPerspective())
John Kessenich55e7d112015-11-15 21:33:39 -0700475 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700476 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationFlat;
John Kessenicha28f7a72019-08-06 07:00:58 -0600478 else if (qualifier.isExplicitInterpolation()) {
Rex Xu17ff3432016-10-14 17:41:45 +0800479 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800480 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800481 }
Rex Xubbceed72016-05-21 09:40:44 +0800482 else
John Kessenich4016e382016-07-15 11:53:56 -0600483 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800484}
485
486// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600487// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800488// should be applied.
489spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
490{
John Kessenichb9197c82019-08-11 07:41:45 -0600491 if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600492 return spv::DecorationCentroid;
John Kessenichb9197c82019-08-11 07:41:45 -0600493#ifndef GLSLANG_WEB
494 else if (qualifier.patch)
495 return spv::DecorationPatch;
John Kessenich5e801132016-02-15 11:09:46 -0700496 else if (qualifier.sample) {
497 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600498 return spv::DecorationSample;
John Kessenichb9197c82019-08-11 07:41:45 -0600499 }
500#endif
501
502 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600503}
504
John Kessenich92187592016-02-01 13:45:25 -0700505// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700506spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600507{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700508 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600509 return spv::DecorationInvariant;
510 else
John Kessenich4016e382016-07-15 11:53:56 -0600511 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600512}
513
qining9220dbb2016-05-04 17:34:38 -0400514// If glslang type is noContraction, return SPIR-V NoContraction decoration.
515spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
516{
John Kessenichb9197c82019-08-11 07:41:45 -0600517#ifndef GLSLANG_WEB
John Kessenicha28f7a72019-08-06 07:00:58 -0600518 if (qualifier.isNoContraction())
qining9220dbb2016-05-04 17:34:38 -0400519 return spv::DecorationNoContraction;
520 else
John Kessenichb9197c82019-08-11 07:41:45 -0600521#endif
John Kessenich4016e382016-07-15 11:53:56 -0600522 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400523}
524
John Kessenich5611c6d2018-04-05 11:25:02 -0600525// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
526spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
527{
John Kessenichb9197c82019-08-11 07:41:45 -0600528#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -0600529 if (qualifier.isNonUniform()) {
John Kessenich8317e6c2019-08-18 23:58:08 -0600530 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -0600531 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
532 return spv::DecorationNonUniformEXT;
533 } else
John Kessenichb9197c82019-08-11 07:41:45 -0600534#endif
John Kessenich5611c6d2018-04-05 11:25:02 -0600535 return spv::DecorationMax;
536}
537
John Kessenichb9197c82019-08-11 07:41:45 -0600538spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
539 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500540{
Jeff Bolz36831c92018-09-05 10:11:41 -0500541 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600542
543#ifndef GLSLANG_WEB
544 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
545 return mask;
546
Daniel Kochdb32b242020-03-17 20:42:47 -0400547 if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500548 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
549 spv::MemoryAccessMakePointerVisibleKHRMask;
550 }
Daniel Kochdb32b242020-03-17 20:42:47 -0400551
Jeff Bolz36831c92018-09-05 10:11:41 -0500552 if (coherentFlags.nonprivate) {
553 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
554 }
555 if (coherentFlags.volatil) {
556 mask = mask | spv::MemoryAccessVolatileMask;
557 }
558 if (mask != spv::MemoryAccessMaskNone) {
559 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
560 }
John Kessenichb9197c82019-08-11 07:41:45 -0600561#endif
562
Jeff Bolz36831c92018-09-05 10:11:41 -0500563 return mask;
564}
565
John Kessenichb9197c82019-08-11 07:41:45 -0600566spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
567 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500568{
Jeff Bolz36831c92018-09-05 10:11:41 -0500569 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenichb9197c82019-08-11 07:41:45 -0600570
571#ifndef GLSLANG_WEB
572 if (!glslangIntermediate->usingVulkanMemoryModel())
573 return mask;
574
Jeff Bolz36831c92018-09-05 10:11:41 -0500575 if (coherentFlags.volatil ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400576 coherentFlags.anyCoherent()) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
578 spv::ImageOperandsMakeTexelVisibleKHRMask;
579 }
580 if (coherentFlags.nonprivate) {
581 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
582 }
583 if (coherentFlags.volatil) {
584 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
585 }
586 if (mask != spv::ImageOperandsMaskNone) {
587 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
588 }
John Kessenichb9197c82019-08-11 07:41:45 -0600589#endif
590
Jeff Bolz36831c92018-09-05 10:11:41 -0500591 return mask;
592}
593
594spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
595{
John Kessenichb9197c82019-08-11 07:41:45 -0600596 spv::Builder::AccessChain::CoherentFlags flags = {};
597#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -0500598 flags.coherent = type.getQualifier().coherent;
599 flags.devicecoherent = type.getQualifier().devicecoherent;
600 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
601 // shared variables are implicitly workgroupcoherent in GLSL.
602 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
603 type.getQualifier().storage == glslang::EvqShared;
604 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Daniel Kochdb32b242020-03-17 20:42:47 -0400605 flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600606 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500607 // *coherent variables are implicitly nonprivate in GLSL
608 flags.nonprivate = type.getQualifier().nonprivate ||
Daniel Kochdb32b242020-03-17 20:42:47 -0400609 flags.anyCoherent() ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600610 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500611 flags.isImage = type.getBasicType() == glslang::EbtSampler;
John Kessenichb9197c82019-08-11 07:41:45 -0600612#endif
Jeff Bolz36831c92018-09-05 10:11:41 -0500613 return flags;
614}
615
John Kessenichb9197c82019-08-11 07:41:45 -0600616spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
617 const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
Jeff Bolz36831c92018-09-05 10:11:41 -0500618{
John Kessenichb9197c82019-08-11 07:41:45 -0600619 spv::Scope scope = spv::ScopeMax;
620
621#ifndef GLSLANG_WEB
Jeff Bolz38cbad12019-03-05 14:40:07 -0600622 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500623 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
624 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
625 } else if (coherentFlags.devicecoherent) {
626 scope = spv::ScopeDevice;
627 } else if (coherentFlags.queuefamilycoherent) {
628 scope = spv::ScopeQueueFamilyKHR;
629 } else if (coherentFlags.workgroupcoherent) {
630 scope = spv::ScopeWorkgroup;
631 } else if (coherentFlags.subgroupcoherent) {
632 scope = spv::ScopeSubgroup;
Daniel Kochdb32b242020-03-17 20:42:47 -0400633 } else if (coherentFlags.shadercallcoherent) {
634 scope = spv::ScopeShaderCallKHR;
Jeff Bolz36831c92018-09-05 10:11:41 -0500635 }
636 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
637 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
638 }
John Kessenichb9197c82019-08-11 07:41:45 -0600639#endif
640
Jeff Bolz36831c92018-09-05 10:11:41 -0500641 return scope;
642}
643
David Netoa901ffe2016-06-08 14:11:40 +0100644// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
645// associated capabilities when required. For some built-in variables, a capability
646// is generated only when using the variable in an executable instruction, but not when
647// just declaring a struct member variable with it. This is true for PointSize,
648// ClipDistance, and CullDistance.
John Kessenich8985fc92020-03-03 10:25:07 -0700649spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
650 bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600651{
652 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700653 case glslang::EbvPointSize:
John Kessenich155d3512019-08-08 23:29:20 -0600654#ifndef GLSLANG_WEB
John Kessenich78a45572016-07-08 14:05:15 -0600655 // Defer adding the capability until the built-in is actually used.
656 if (! memberDeclaration) {
657 switch (glslangIntermediate->getStage()) {
658 case EShLangGeometry:
659 builder.addCapability(spv::CapabilityGeometryPointSize);
660 break;
661 case EShLangTessControl:
662 case EShLangTessEvaluation:
663 builder.addCapability(spv::CapabilityTessellationPointSize);
664 break;
665 default:
666 break;
667 }
John Kessenich92187592016-02-01 13:45:25 -0700668 }
John Kessenich155d3512019-08-08 23:29:20 -0600669#endif
John Kessenich92187592016-02-01 13:45:25 -0700670 return spv::BuiltInPointSize;
671
John Kessenicha28f7a72019-08-06 07:00:58 -0600672 case glslang::EbvPosition: return spv::BuiltInPosition;
673 case glslang::EbvVertexId: return spv::BuiltInVertexId;
674 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
675 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
676 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
677
678 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
679 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
680 case glslang::EbvFace: return spv::BuiltInFrontFacing;
681 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
682
John Kessenich3dd1ce52019-10-17 07:08:40 -0600683 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
684 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
685 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
686 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
687 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
688 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
689
John Kessenicha28f7a72019-08-06 07:00:58 -0600690#ifndef GLSLANG_WEB
John Kessenichebb50532016-05-16 19:22:05 -0600691 // These *Distance capabilities logically belong here, but if the member is declared and
692 // then never used, consumers of SPIR-V prefer the capability not be declared.
693 // They are now generated when used, rather than here when declared.
694 // Potentially, the specification should be more clear what the minimum
695 // use needed is to trigger the capability.
696 //
John Kessenich92187592016-02-01 13:45:25 -0700697 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100698 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800699 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700700 return spv::BuiltInClipDistance;
701
702 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100703 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800704 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700705 return spv::BuiltInCullDistance;
706
707 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600708 builder.addCapability(spv::CapabilityMultiViewport);
709 if (glslangIntermediate->getStage() == EShLangVertex ||
710 glslangIntermediate->getStage() == EShLangTessControl ||
711 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800712
John Kessenich8317e6c2019-08-18 23:58:08 -0600713 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600714 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800715 }
John Kessenich92187592016-02-01 13:45:25 -0700716 return spv::BuiltInViewportIndex;
717
John Kessenich5e801132016-02-15 11:09:46 -0700718 case glslang::EbvSampleId:
719 builder.addCapability(spv::CapabilitySampleRateShading);
720 return spv::BuiltInSampleId;
721
722 case glslang::EbvSamplePosition:
723 builder.addCapability(spv::CapabilitySampleRateShading);
724 return spv::BuiltInSamplePosition;
725
726 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700727 return spv::BuiltInSampleMask;
728
John Kessenich78a45572016-07-08 14:05:15 -0600729 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700730 if (glslangIntermediate->getStage() == EShLangMeshNV) {
731 return spv::BuiltInLayer;
732 }
John Kessenichba6a3c22017-09-13 13:22:50 -0600733 builder.addCapability(spv::CapabilityGeometry);
734 if (glslangIntermediate->getStage() == EShLangVertex ||
735 glslangIntermediate->getStage() == EShLangTessControl ||
736 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800737
John Kessenich8317e6c2019-08-18 23:58:08 -0600738 builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
John Kessenichba6a3c22017-09-13 13:22:50 -0600739 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800740 }
John Kessenich78a45572016-07-08 14:05:15 -0600741 return spv::BuiltInLayer;
742
John Kessenichda581a22015-10-14 14:10:30 -0600743 case glslang::EbvBaseVertex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600744 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800745 builder.addCapability(spv::CapabilityDrawParameters);
746 return spv::BuiltInBaseVertex;
747
John Kessenichda581a22015-10-14 14:10:30 -0600748 case glslang::EbvBaseInstance:
John Kessenich8317e6c2019-08-18 23:58:08 -0600749 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800750 builder.addCapability(spv::CapabilityDrawParameters);
751 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200752
John Kessenichda581a22015-10-14 14:10:30 -0600753 case glslang::EbvDrawId:
John Kessenich8317e6c2019-08-18 23:58:08 -0600754 builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
Rex Xuf3b27472016-07-22 18:15:31 +0800755 builder.addCapability(spv::CapabilityDrawParameters);
756 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200757
758 case glslang::EbvPrimitiveId:
759 if (glslangIntermediate->getStage() == EShLangFragment)
760 builder.addCapability(spv::CapabilityGeometry);
761 return spv::BuiltInPrimitiveId;
762
Rex Xu37cdcee2017-06-29 17:46:34 +0800763 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800764 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
765 builder.addCapability(spv::CapabilityStencilExportEXT);
766 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800767
John Kessenich140f3df2015-06-26 16:58:36 -0600768 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600769 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
770 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
771 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
772 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
John Kessenich140f3df2015-06-26 16:58:36 -0600773 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
Rex Xu51596642016-09-21 18:56:12 +0800774
Rex Xu574ab042016-04-14 16:53:07 +0800775 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800776 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800777 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
778 return spv::BuiltInSubgroupSize;
779
Rex Xu574ab042016-04-14 16:53:07 +0800780 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800781 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800782 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
783 return spv::BuiltInSubgroupLocalInvocationId;
784
Rex Xu574ab042016-04-14 16:53:07 +0800785 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800786 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
787 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600788 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800789
Rex Xu574ab042016-04-14 16:53:07 +0800790 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800791 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
792 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600793 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800794
Rex Xu574ab042016-04-14 16:53:07 +0800795 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800796 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
797 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600798 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800799
Rex Xu574ab042016-04-14 16:53:07 +0800800 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800801 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
802 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600803 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800804
Rex Xu574ab042016-04-14 16:53:07 +0800805 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800806 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
807 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600808 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800809
John Kessenich66011cb2018-03-06 16:12:04 -0700810 case glslang::EbvNumSubgroups:
811 builder.addCapability(spv::CapabilityGroupNonUniform);
812 return spv::BuiltInNumSubgroups;
813
814 case glslang::EbvSubgroupID:
815 builder.addCapability(spv::CapabilityGroupNonUniform);
816 return spv::BuiltInSubgroupId;
817
818 case glslang::EbvSubgroupSize2:
819 builder.addCapability(spv::CapabilityGroupNonUniform);
820 return spv::BuiltInSubgroupSize;
821
822 case glslang::EbvSubgroupInvocation2:
823 builder.addCapability(spv::CapabilityGroupNonUniform);
824 return spv::BuiltInSubgroupLocalInvocationId;
825
826 case glslang::EbvSubgroupEqMask2:
827 builder.addCapability(spv::CapabilityGroupNonUniform);
828 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
829 return spv::BuiltInSubgroupEqMask;
830
831 case glslang::EbvSubgroupGeMask2:
832 builder.addCapability(spv::CapabilityGroupNonUniform);
833 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
834 return spv::BuiltInSubgroupGeMask;
835
836 case glslang::EbvSubgroupGtMask2:
837 builder.addCapability(spv::CapabilityGroupNonUniform);
838 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
839 return spv::BuiltInSubgroupGtMask;
840
841 case glslang::EbvSubgroupLeMask2:
842 builder.addCapability(spv::CapabilityGroupNonUniform);
843 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
844 return spv::BuiltInSubgroupLeMask;
845
846 case glslang::EbvSubgroupLtMask2:
847 builder.addCapability(spv::CapabilityGroupNonUniform);
848 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
849 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600850
Rex Xu17ff3432016-10-14 17:41:45 +0800851 case glslang::EbvBaryCoordNoPersp:
852 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
853 return spv::BuiltInBaryCoordNoPerspAMD;
854
855 case glslang::EbvBaryCoordNoPerspCentroid:
856 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
857 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
858
859 case glslang::EbvBaryCoordNoPerspSample:
860 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
861 return spv::BuiltInBaryCoordNoPerspSampleAMD;
862
863 case glslang::EbvBaryCoordSmooth:
864 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
865 return spv::BuiltInBaryCoordSmoothAMD;
866
867 case glslang::EbvBaryCoordSmoothCentroid:
868 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
869 return spv::BuiltInBaryCoordSmoothCentroidAMD;
870
871 case glslang::EbvBaryCoordSmoothSample:
872 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
873 return spv::BuiltInBaryCoordSmoothSampleAMD;
874
875 case glslang::EbvBaryCoordPullModel:
876 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
877 return spv::BuiltInBaryCoordPullModelAMD;
chaoc771d89f2017-01-13 01:10:53 -0800878
John Kessenich6c8aaac2017-02-27 01:20:51 -0700879 case glslang::EbvDeviceIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600880 builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700881 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700882 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700883
884 case glslang::EbvViewIndex:
John Kessenich8317e6c2019-08-18 23:58:08 -0600885 builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700886 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700887 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700888
Daniel Koch5154db52018-11-26 10:01:58 -0500889 case glslang::EbvFragSizeEXT:
890 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
891 builder.addCapability(spv::CapabilityFragmentDensityEXT);
892 return spv::BuiltInFragSizeEXT;
893
894 case glslang::EbvFragInvocationCountEXT:
895 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
896 builder.addCapability(spv::CapabilityFragmentDensityEXT);
897 return spv::BuiltInFragInvocationCountEXT;
898
chaoc771d89f2017-01-13 01:10:53 -0800899 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800900 if (!memberDeclaration) {
901 builder.addExtension(spv::E_SPV_NV_viewport_array2);
902 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
903 }
chaoc771d89f2017-01-13 01:10:53 -0800904 return spv::BuiltInViewportMaskNV;
905 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800906 if (!memberDeclaration) {
907 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
908 builder.addCapability(spv::CapabilityShaderStereoViewNV);
909 }
chaoc771d89f2017-01-13 01:10:53 -0800910 return spv::BuiltInSecondaryPositionNV;
911 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800912 if (!memberDeclaration) {
913 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
914 builder.addCapability(spv::CapabilityShaderStereoViewNV);
915 }
chaoc771d89f2017-01-13 01:10:53 -0800916 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800917 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800918 if (!memberDeclaration) {
919 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
920 builder.addCapability(spv::CapabilityPerViewAttributesNV);
921 }
chaocdf3956c2017-02-14 14:52:34 -0800922 return spv::BuiltInPositionPerViewNV;
923 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800924 if (!memberDeclaration) {
925 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
926 builder.addCapability(spv::CapabilityPerViewAttributesNV);
927 }
chaocdf3956c2017-02-14 14:52:34 -0800928 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700929 case glslang::EbvFragFullyCoveredNV:
930 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
931 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
932 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700933 case glslang::EbvFragmentSizeNV:
934 builder.addExtension(spv::E_SPV_NV_shading_rate);
935 builder.addCapability(spv::CapabilityShadingRateNV);
936 return spv::BuiltInFragmentSizeNV;
937 case glslang::EbvInvocationsPerPixelNV:
938 builder.addExtension(spv::E_SPV_NV_shading_rate);
939 builder.addCapability(spv::CapabilityShadingRateNV);
940 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700941
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 // ray tracing
Daniel Kochdb32b242020-03-17 20:42:47 -0400943 case glslang::EbvLaunchId:
944 return spv::BuiltInLaunchIdKHR;
945 case glslang::EbvLaunchSize:
946 return spv::BuiltInLaunchSizeKHR;
947 case glslang::EbvWorldRayOrigin:
948 return spv::BuiltInWorldRayOriginKHR;
949 case glslang::EbvWorldRayDirection:
950 return spv::BuiltInWorldRayDirectionKHR;
951 case glslang::EbvObjectRayOrigin:
952 return spv::BuiltInObjectRayOriginKHR;
953 case glslang::EbvObjectRayDirection:
954 return spv::BuiltInObjectRayDirectionKHR;
955 case glslang::EbvRayTmin:
956 return spv::BuiltInRayTminKHR;
957 case glslang::EbvRayTmax:
958 return spv::BuiltInRayTmaxKHR;
959 case glslang::EbvInstanceCustomIndex:
960 return spv::BuiltInInstanceCustomIndexKHR;
961 case glslang::EbvHitT:
962 return spv::BuiltInHitTKHR;
963 case glslang::EbvHitKind:
964 return spv::BuiltInHitKindKHR;
965 case glslang::EbvObjectToWorld:
966 case glslang::EbvObjectToWorld3x4:
967 return spv::BuiltInObjectToWorldKHR;
968 case glslang::EbvWorldToObject:
969 case glslang::EbvWorldToObject3x4:
970 return spv::BuiltInWorldToObjectKHR;
971 case glslang::EbvIncomingRayFlags:
972 return spv::BuiltInIncomingRayFlagsKHR;
973 case glslang::EbvGeometryIndex:
974 return spv::BuiltInRayGeometryIndexKHR;
Daniel Koch593a4e02019-05-27 16:46:31 -0400975
976 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700977 case glslang::EbvBaryCoordNV:
978 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
979 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
980 return spv::BuiltInBaryCoordNV;
981 case glslang::EbvBaryCoordNoPerspNV:
982 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
983 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
984 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400985
986 // mesh shaders
987 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700988 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400989 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700990 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400991 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700992 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400993 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700994 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400995 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700996 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400997 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700998 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400999 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -07001000 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -04001001 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -07001002 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch2cb2f192019-06-04 08:43:32 -04001003
1004 // sm builtins
1005 case glslang::EbvWarpsPerSM:
1006 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1007 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1008 return spv::BuiltInWarpsPerSMNV;
1009 case glslang::EbvSMCount:
1010 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1011 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1012 return spv::BuiltInSMCountNV;
1013 case glslang::EbvWarpID:
1014 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1015 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1016 return spv::BuiltInWarpIDNV;
1017 case glslang::EbvSMID:
1018 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
1019 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
1020 return spv::BuiltInSMIDNV;
John Kessenicha28f7a72019-08-06 07:00:58 -06001021#endif
1022
Rex Xu3e783f92017-02-22 16:44:48 +08001023 default:
1024 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -06001025 }
1026}
1027
Rex Xufc618912015-09-09 16:42:49 +08001028// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -07001029spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +08001030{
1031 assert(type.getBasicType() == glslang::EbtSampler);
1032
John Kessenichb9197c82019-08-11 07:41:45 -06001033#ifdef GLSLANG_WEB
1034 return spv::ImageFormatUnknown;
1035#endif
1036
John Kessenich5d0fa972016-02-15 11:57:00 -07001037 // Check for capabilities
John Kessenich7015bd62019-08-01 03:28:08 -06001038 switch (type.getQualifier().getFormat()) {
John Kessenich5d0fa972016-02-15 11:57:00 -07001039 case glslang::ElfRg32f:
1040 case glslang::ElfRg16f:
1041 case glslang::ElfR11fG11fB10f:
1042 case glslang::ElfR16f:
1043 case glslang::ElfRgba16:
1044 case glslang::ElfRgb10A2:
1045 case glslang::ElfRg16:
1046 case glslang::ElfRg8:
1047 case glslang::ElfR16:
1048 case glslang::ElfR8:
1049 case glslang::ElfRgba16Snorm:
1050 case glslang::ElfRg16Snorm:
1051 case glslang::ElfRg8Snorm:
1052 case glslang::ElfR16Snorm:
1053 case glslang::ElfR8Snorm:
1054
1055 case glslang::ElfRg32i:
1056 case glslang::ElfRg16i:
1057 case glslang::ElfRg8i:
1058 case glslang::ElfR16i:
1059 case glslang::ElfR8i:
1060
1061 case glslang::ElfRgb10a2ui:
1062 case glslang::ElfRg32ui:
1063 case glslang::ElfRg16ui:
1064 case glslang::ElfRg8ui:
1065 case glslang::ElfR16ui:
1066 case glslang::ElfR8ui:
1067 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1068 break;
1069
1070 default:
1071 break;
1072 }
1073
1074 // do the translation
John Kessenich7015bd62019-08-01 03:28:08 -06001075 switch (type.getQualifier().getFormat()) {
Rex Xufc618912015-09-09 16:42:49 +08001076 case glslang::ElfNone: return spv::ImageFormatUnknown;
1077 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1078 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1079 case glslang::ElfR32f: return spv::ImageFormatR32f;
1080 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1081 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1082 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1083 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1084 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1085 case glslang::ElfR16f: return spv::ImageFormatR16f;
1086 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1087 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1088 case glslang::ElfRg16: return spv::ImageFormatRg16;
1089 case glslang::ElfRg8: return spv::ImageFormatRg8;
1090 case glslang::ElfR16: return spv::ImageFormatR16;
1091 case glslang::ElfR8: return spv::ImageFormatR8;
1092 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1093 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1094 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1095 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1096 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1097 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1098 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1099 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1100 case glslang::ElfR32i: return spv::ImageFormatR32i;
1101 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1102 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1103 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1104 case glslang::ElfR16i: return spv::ImageFormatR16i;
1105 case glslang::ElfR8i: return spv::ImageFormatR8i;
1106 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1107 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1108 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1109 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1110 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1111 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1112 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1113 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1114 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1115 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001116 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001117 }
1118}
1119
John Kessenich8985fc92020-03-03 10:25:07 -07001120spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
1121 const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001122{
John Kesseniche18fd202018-01-30 11:01:39 -07001123 if (selectionNode.getFlatten())
1124 return spv::SelectionControlFlattenMask;
1125 if (selectionNode.getDontFlatten())
1126 return spv::SelectionControlDontFlattenMask;
1127 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001128}
1129
John Kessenich8985fc92020-03-03 10:25:07 -07001130spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
1131 const
steve-lunargf1709e72017-05-02 20:14:50 -06001132{
John Kesseniche18fd202018-01-30 11:01:39 -07001133 if (switchNode.getFlatten())
1134 return spv::SelectionControlFlattenMask;
1135 if (switchNode.getDontFlatten())
1136 return spv::SelectionControlDontFlattenMask;
1137 return spv::SelectionControlMaskNone;
1138}
1139
John Kessenicha2858d92018-01-31 08:11:18 -07001140// return a non-0 dependency if the dependency argument must be set
1141spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001142 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001143{
1144 spv::LoopControlMask control = spv::LoopControlMaskNone;
1145
1146 if (loopNode.getDontUnroll())
1147 control = control | spv::LoopControlDontUnrollMask;
1148 if (loopNode.getUnroll())
1149 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001150 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001151 control = control | spv::LoopControlDependencyInfiniteMask;
1152 else if (loopNode.getLoopDependency() > 0) {
1153 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001154 operands.push_back((unsigned int)loopNode.getLoopDependency());
1155 }
1156 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1157 if (loopNode.getMinIterations() > 0) {
1158 control = control | spv::LoopControlMinIterationsMask;
1159 operands.push_back(loopNode.getMinIterations());
1160 }
1161 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1162 control = control | spv::LoopControlMaxIterationsMask;
1163 operands.push_back(loopNode.getMaxIterations());
1164 }
1165 if (loopNode.getIterationMultiple() > 1) {
1166 control = control | spv::LoopControlIterationMultipleMask;
1167 operands.push_back(loopNode.getIterationMultiple());
1168 }
1169 if (loopNode.getPeelCount() > 0) {
1170 control = control | spv::LoopControlPeelCountMask;
1171 operands.push_back(loopNode.getPeelCount());
1172 }
1173 if (loopNode.getPartialCount() > 0) {
1174 control = control | spv::LoopControlPartialCountMask;
1175 operands.push_back(loopNode.getPartialCount());
1176 }
John Kessenicha2858d92018-01-31 08:11:18 -07001177 }
John Kesseniche18fd202018-01-30 11:01:39 -07001178
1179 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001180}
1181
John Kessenicha5c5fb62017-05-05 05:09:58 -06001182// Translate glslang type to SPIR-V storage class.
1183spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1184{
Torosdagli06c2eee2020-03-19 11:09:57 -04001185 if (type.getBasicType() == glslang::EbtRayQuery)
Neslisah Torosdagli054b5e32020-03-26 12:24:31 -04001186 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001187 if (type.getQualifier().isPipeInput())
1188 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001189 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001190 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001191
1192 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
John Kessenicha28f7a72019-08-06 07:00:58 -06001193 type.getQualifier().storage == glslang::EvqUniform) {
John Kessenichdeec1932019-08-13 08:00:30 -06001194 if (type.isAtomic())
John Kessenichbed4e4f2017-09-08 02:38:07 -06001195 return spv::StorageClassAtomicCounter;
1196 if (type.containsOpaque())
1197 return spv::StorageClassUniformConstant;
1198 }
1199
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001200 if (type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001201 type.getQualifier().isShaderRecord()) {
1202 return spv::StorageClassShaderRecordBufferKHR;
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001203 }
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001204
John Kessenichbed4e4f2017-09-08 02:38:07 -06001205 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001206 builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001207 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001208 }
1209
1210 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich7015bd62019-08-01 03:28:08 -06001211 if (type.getQualifier().isPushConstant())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001212 return spv::StorageClassPushConstant;
1213 if (type.getBasicType() == glslang::EbtBlock)
1214 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001215 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001216 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001217
1218 switch (type.getQualifier().storage) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001219 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1220 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1221 case glslang::EvqTemporary: return spv::StorageClassFunction;
John Kessenichdeec1932019-08-13 08:00:30 -06001222 case glslang::EvqShared: return spv::StorageClassWorkgroup;
John Kessenich3dd1ce52019-10-17 07:08:40 -06001223#ifndef GLSLANG_WEB
Daniel Kochdb32b242020-03-17 20:42:47 -04001224 case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
1225 case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
1226 case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
1227 case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
1228 case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
Chao Chenb50c02e2018-09-19 11:42:24 -07001229#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001230 default:
1231 assert(0);
1232 break;
1233 }
1234
1235 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001236}
1237
John Kessenich5611c6d2018-04-05 11:25:02 -06001238// Add capabilities pertaining to how an array is indexed.
1239void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1240 const glslang::TType& indexType)
1241{
John Kessenichb9197c82019-08-11 07:41:45 -06001242#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06001243 if (indexType.getQualifier().isNonUniform()) {
1244 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001245 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001246 if (baseType.getBasicType() == glslang::EbtSampler) {
1247 if (baseType.getQualifier().hasAttachment())
1248 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001249 else if (baseType.isImage() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001250 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001251 else if (baseType.isTexture() && baseType.getSampler().isBuffer())
John Kessenich5611c6d2018-04-05 11:25:02 -06001252 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1253 else if (baseType.isImage())
1254 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1255 else if (baseType.isTexture())
1256 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1257 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1258 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1259 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1260 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1261 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1262 }
1263 } else {
1264 // assume a dynamically uniform index
1265 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001266 if (baseType.getQualifier().hasAttachment()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001267 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001268 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001269 } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001270 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001271 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06001272 } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
John Kessenich8317e6c2019-08-18 23:58:08 -06001273 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06001274 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001275 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001276 }
1277 }
John Kessenichb9197c82019-08-11 07:41:45 -06001278#endif
John Kessenich5611c6d2018-04-05 11:25:02 -06001279}
1280
qining25262b32016-05-06 17:25:16 -04001281// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001282// descriptor set.
1283bool IsDescriptorResource(const glslang::TType& type)
1284{
John Kessenichf7497e22016-03-08 21:36:22 -07001285 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001286 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001287 return type.getQualifier().isUniformOrBuffer() &&
Daniel Kochdb32b242020-03-17 20:42:47 -04001288 ! type.getQualifier().isShaderRecord() &&
John Kessenich7015bd62019-08-01 03:28:08 -06001289 ! type.getQualifier().isPushConstant();
John Kessenich6c292d32016-02-15 20:58:50 -07001290
1291 // non block...
1292 // basically samplerXXX/subpass/sampler/texture are all included
1293 // if they are the global-scope-class, not the function parameter
1294 // (or local, if they ever exist) class.
1295 if (type.getBasicType() == glslang::EbtSampler)
1296 return type.getQualifier().isUniformOrBuffer();
1297
1298 // None of the above.
1299 return false;
1300}
1301
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1303{
1304 if (child.layoutMatrix == glslang::ElmNone)
1305 child.layoutMatrix = parent.layoutMatrix;
1306
1307 if (parent.invariant)
1308 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001309 if (parent.flat)
1310 child.flat = true;
1311 if (parent.centroid)
1312 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001313#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001314 if (parent.nopersp)
1315 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001316 if (parent.explicitInterp)
1317 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001318 if (parent.perPrimitiveNV)
1319 child.perPrimitiveNV = true;
1320 if (parent.perViewNV)
1321 child.perViewNV = true;
1322 if (parent.perTaskNV)
1323 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001324 if (parent.patch)
1325 child.patch = true;
1326 if (parent.sample)
1327 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001328 if (parent.coherent)
1329 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001330 if (parent.devicecoherent)
1331 child.devicecoherent = true;
1332 if (parent.queuefamilycoherent)
1333 child.queuefamilycoherent = true;
1334 if (parent.workgroupcoherent)
1335 child.workgroupcoherent = true;
1336 if (parent.subgroupcoherent)
1337 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001338 if (parent.shadercallcoherent)
1339 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001340 if (parent.nonprivate)
1341 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001342 if (parent.volatil)
1343 child.volatil = true;
1344 if (parent.restrict)
1345 child.restrict = true;
1346 if (parent.readonly)
1347 child.readonly = true;
1348 if (parent.writeonly)
1349 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001350#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001351}
1352
John Kessenichf2b7f332016-09-01 17:05:23 -06001353bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001354{
John Kessenich7b9fa252016-01-21 18:56:57 -07001355 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001356 // - struct members might inherit from a struct declaration
1357 // (note that non-block structs don't explicitly inherit,
1358 // only implicitly, meaning no decoration involved)
1359 // - affect decorations on the struct members
1360 // (note smooth does not, and expecting something like volatile
1361 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001362 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001363 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001364}
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366//
1367// Implement the TGlslangToSpvTraverser class.
1368//
1369
John Kessenich8985fc92020-03-03 10:25:07 -07001370TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1371 const glslang::TIntermediate* glslangIntermediate,
1372 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1373 TIntermTraverser(true, false, true),
1374 options(options),
1375 shaderEntry(nullptr), currentFunction(nullptr),
1376 sequenceDepth(0), logger(buildLogger),
1377 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1378 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1379 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001380 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1381 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001382{
1383 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1384
1385 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001386 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1387 glslangIntermediate->getVersion());
1388
John Kessenich121853f2017-05-31 17:11:16 -06001389 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001390 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001391 builder.setSourceFile(glslangIntermediate->getSourceFile());
1392
1393 // Set the source shader's text. If for SPV version 1.0, include
1394 // a preamble in comments stating the OpModuleProcessed instructions.
1395 // Otherwise, emit those as actual instructions.
1396 std::string text;
1397 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1398 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001399 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001400 text.append("// OpModuleProcessed ");
1401 text.append(processes[p]);
1402 text.append("\n");
1403 } else
1404 builder.addModuleProcessed(processes[p]);
1405 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001406 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001407 text.append("#line 1\n");
1408 text.append(glslangIntermediate->getSourceText());
1409 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001410 // Pass name and text for all included files
1411 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1412 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1413 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001414 }
John Kessenich140f3df2015-06-26 16:58:36 -06001415 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001416
1417 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1418 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1419
1420 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1421 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001422 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001423 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001424 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001425 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001426 memoryModel = spv::MemoryModelVulkanKHR;
1427 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001428 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001429 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001430 builder.setMemoryModel(addressingModel, memoryModel);
1431
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001432 if (glslangIntermediate->usingVariablePointers()) {
1433 builder.addCapability(spv::CapabilityVariablePointers);
1434 }
1435
John Kessenicheee9d532016-09-19 18:09:30 -06001436 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1437 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001438
1439 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001440 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1441 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
Pankaj Mistry2a8ead22020-04-26 17:52:31 -07001442 builder.addSourceExtension(it->first.c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001443
1444 // Add the top-level modes for this shader.
1445
John Kessenich92187592016-02-01 13:45:25 -07001446 if (glslangIntermediate->getXfbMode()) {
1447 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450
alelenv59216d52020-05-21 04:38:41 -07001451 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001452 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1453 }
1454
John Kessenich140f3df2015-06-26 16:58:36 -06001455 unsigned int mode;
1456 switch (glslangIntermediate->getStage()) {
1457 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001458 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001459 break;
1460
John Kessenicha28f7a72019-08-06 07:00:58 -06001461 case EShLangFragment:
1462 builder.addCapability(spv::CapabilityShader);
1463 if (glslangIntermediate->getPixelCenterInteger())
1464 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1465
1466 if (glslangIntermediate->getOriginUpperLeft())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1468 else
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1470
1471 if (glslangIntermediate->getEarlyFragmentTests())
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1473
1474 if (glslangIntermediate->getPostDepthCoverage()) {
1475 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1476 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1477 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1478 }
1479
John Kessenichb9197c82019-08-11 07:41:45 -06001480 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1481 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1482
1483#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001484
John Kessenicha28f7a72019-08-06 07:00:58 -06001485 switch(glslangIntermediate->getDepth()) {
1486 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1487 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1488 default: mode = spv::ExecutionModeMax; break;
1489 }
1490 if (mode != spv::ExecutionModeMax)
1491 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001492 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001493 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1494 break;
1495 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1496 break;
1497 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1498 break;
1499 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1500 break;
1501 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1502 break;
1503 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1504 break;
1505 default: mode = spv::ExecutionModeMax;
1506 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001507 }
1508 if (mode != spv::ExecutionModeMax) {
1509 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1510 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1511 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1512 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1513 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1514 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1515 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1516 } else {
1517 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1518 }
1519 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1520 }
John Kessenichb9197c82019-08-11 07:41:45 -06001521#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001522 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001523
John Kessenicha28f7a72019-08-06 07:00:58 -06001524 case EShLangCompute:
1525 builder.addCapability(spv::CapabilityShader);
1526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1527 glslangIntermediate->getLocalSize(1),
1528 glslangIntermediate->getLocalSize(2));
1529 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1530 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1531 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1532 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1533 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1534 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1535 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1536 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1537 }
1538 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001539#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001540 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001541 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001542 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001543
steve-lunarge7412492017-03-23 11:56:07 -06001544 glslang::TLayoutGeometry primitive;
1545
1546 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001547 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1548 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001549 primitive = glslangIntermediate->getOutputPrimitive();
1550 } else {
1551 primitive = glslangIntermediate->getInputPrimitive();
1552 }
1553
1554 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001555 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1556 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1557 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001558 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001559 }
John Kessenich4016e382016-07-15 11:53:56 -06001560 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001561 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1562
John Kesseniche6903322015-10-13 16:29:02 -06001563 switch (glslangIntermediate->getVertexSpacing()) {
1564 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1565 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1566 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001567 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001568 }
John Kessenich4016e382016-07-15 11:53:56 -06001569 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001570 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1571
1572 switch (glslangIntermediate->getVertexOrder()) {
1573 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1574 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001575 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001576 }
John Kessenich4016e382016-07-15 11:53:56 -06001577 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001578 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1579
1580 if (glslangIntermediate->getPointMode())
1581 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001582 break;
1583
1584 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001585 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001586 switch (glslangIntermediate->getInputPrimitive()) {
1587 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1588 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1589 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001590 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001591 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001592 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001593 }
John Kessenich4016e382016-07-15 11:53:56 -06001594 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001595 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001596
John Kessenich140f3df2015-06-26 16:58:36 -06001597 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1598
1599 switch (glslangIntermediate->getOutputPrimitive()) {
1600 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1601 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1602 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001603 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001604 }
John Kessenich4016e382016-07-15 11:53:56 -06001605 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001606 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1607 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1608 break;
1609
Daniel Kochdb32b242020-03-17 20:42:47 -04001610 case EShLangRayGen:
1611 case EShLangIntersect:
1612 case EShLangAnyHit:
1613 case EShLangClosestHit:
1614 case EShLangMiss:
1615 case EShLangCallable:
1616 {
1617 auto& extensions = glslangIntermediate->getRequestedExtensions();
1618 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1619 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1620 builder.addExtension("SPV_KHR_ray_tracing");
1621 }
1622 else {
1623 builder.addCapability(spv::CapabilityRayTracingNV);
1624 builder.addExtension("SPV_NV_ray_tracing");
1625 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001626 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001627 }
Chao Chen3c366992018-09-19 11:41:59 -07001628 case EShLangTaskNV:
1629 case EShLangMeshNV:
1630 builder.addCapability(spv::CapabilityMeshShadingNV);
1631 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1632 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1633 glslangIntermediate->getLocalSize(1),
1634 glslangIntermediate->getLocalSize(2));
1635 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001636 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1637 glslangIntermediate->getVertices());
1638 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1639 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001640
1641 switch (glslangIntermediate->getOutputPrimitive()) {
1642 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1643 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1644 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1645 default: mode = spv::ExecutionModeMax; break;
1646 }
1647 if (mode != spv::ExecutionModeMax)
1648 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1649 }
1650 break;
1651#endif
1652
John Kessenich140f3df2015-06-26 16:58:36 -06001653 default:
1654 break;
1655 }
John Kessenich140f3df2015-06-26 16:58:36 -06001656}
1657
John Kessenichfca82622016-11-26 13:23:20 -07001658// Finish creating SPV, after the traversal is complete.
1659void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001660{
John Kessenichf04c51b2018-08-03 15:56:12 -06001661 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001662 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001663 builder.setBuildPoint(shaderEntry->getLastBlock());
1664 builder.leaveFunction();
1665 }
1666
John Kessenich7ba63412015-12-20 17:37:07 -07001667 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001668 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1669 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001670
David Neto8c3d5b42019-10-21 14:50:31 -04001671 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001672 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001673 // Note: WebGPU code generation must have the opportunity to aggressively
1674 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001675 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001676}
1677
John Kessenichfca82622016-11-26 13:23:20 -07001678// Write the SPV into 'out'.
1679void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001680{
John Kessenichfca82622016-11-26 13:23:20 -07001681 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001682}
1683
1684//
1685// Implement the traversal functions.
1686//
1687// Return true from interior nodes to have the external traversal
1688// continue on to children. Return false if children were
1689// already processed.
1690//
1691
1692//
qining25262b32016-05-06 17:25:16 -04001693// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001694// - uniform/input reads
1695// - output writes
1696// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1697// - something simple that degenerates into the last bullet
1698//
1699void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1700{
qining75d1d802016-04-06 14:42:01 -04001701 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001702 if (symbol->getType().isStruct())
1703 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1704
qining75d1d802016-04-06 14:42:01 -04001705 if (symbol->getType().getQualifier().isSpecConstant())
1706 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1707
John Kessenich140f3df2015-06-26 16:58:36 -06001708 // getSymbolId() will set up all the IO decorations on the first call.
1709 // Formal function parameters were mapped during makeFunctions().
1710 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001711
John Kessenich7ba63412015-12-20 17:37:07 -07001712 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001713 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001714 // Consider adding to the OpEntryPoint interface list.
1715 // Only looking at structures if they have at least one member.
1716 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1717 spv::StorageClass sc = builder.getStorageClass(id);
1718 // Before SPIR-V 1.4, we only want to include Input and Output.
1719 // Starting with SPIR-V 1.4, we want all globals.
1720 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1721 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001722 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001723 }
John Kessenich5f77d862017-09-19 11:09:59 -06001724 }
John Kessenich9c14f772019-06-17 08:38:35 -06001725
Daniel Kochdb32b242020-03-17 20:42:47 -04001726 // If the SPIR-V type is required to be different than the AST type
1727 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001728 // translate now from the SPIR-V type to the AST type, for the consuming
1729 // operation.
1730 // Note this turns it from an l-value to an r-value.
1731 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1732 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1733 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001734 }
1735
1736 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001737 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001738 // Prepare to generate code for the access
1739
1740 // L-value chains will be computed left to right. We're on the symbol now,
1741 // which is the left-most part of the access chain, so now is "clear" time,
1742 // followed by setting the base.
1743 builder.clearAccessChain();
1744
1745 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001746 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001747 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001748 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001749 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001750 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001751 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001752 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001753 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1754 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001755 builder.setAccessChainRValue(id);
1756 else
1757 builder.setAccessChainLValue(id);
1758 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001759
John Kessenichb9197c82019-08-11 07:41:45 -06001760#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001761 // Process linkage-only nodes for any special additional interface work.
1762 if (linkageOnly) {
1763 if (glslangIntermediate->getHlslFunctionality1()) {
1764 // Map implicit counter buffers to their originating buffers, which should have been
1765 // seen by now, given earlier pruning of unused counters, and preservation of order
1766 // of declaration.
1767 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1768 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1769 // Save possible originating buffers for counter buffers, keyed by
1770 // making the potential counter-buffer name.
1771 std::string keyName = symbol->getName().c_str();
1772 keyName = glslangIntermediate->addCounterBufferName(keyName);
1773 counterOriginator[keyName] = symbol;
1774 } else {
1775 // Handle a counter buffer, by finding the saved originating buffer.
1776 std::string keyName = symbol->getName().c_str();
1777 auto it = counterOriginator.find(keyName);
1778 if (it != counterOriginator.end()) {
1779 id = getSymbolId(it->second);
1780 if (id != spv::NoResult) {
1781 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001782 if (counterId != spv::NoResult) {
1783 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001784 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001785 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001786 }
1787 }
1788 }
1789 }
1790 }
1791 }
John Kessenich155d3512019-08-08 23:29:20 -06001792#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001793}
1794
1795bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1796{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001797 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001798 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1799 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1800 }
1801 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1802 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1803 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001804
qining40887662016-04-03 22:20:42 -04001805 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1806 if (node->getType().getQualifier().isSpecConstant())
1807 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1808
John Kessenich140f3df2015-06-26 16:58:36 -06001809 // First, handle special cases
1810 switch (node->getOp()) {
1811 case glslang::EOpAssign:
1812 case glslang::EOpAddAssign:
1813 case glslang::EOpSubAssign:
1814 case glslang::EOpMulAssign:
1815 case glslang::EOpVectorTimesMatrixAssign:
1816 case glslang::EOpVectorTimesScalarAssign:
1817 case glslang::EOpMatrixTimesScalarAssign:
1818 case glslang::EOpMatrixTimesMatrixAssign:
1819 case glslang::EOpDivAssign:
1820 case glslang::EOpModAssign:
1821 case glslang::EOpAndAssign:
1822 case glslang::EOpInclusiveOrAssign:
1823 case glslang::EOpExclusiveOrAssign:
1824 case glslang::EOpLeftShiftAssign:
1825 case glslang::EOpRightShiftAssign:
1826 // A bin-op assign "a += b" means the same thing as "a = a + b"
1827 // where a is evaluated before b. For a simple assignment, GLSL
1828 // says to evaluate the left before the right. So, always, left
1829 // node then right node.
1830 {
1831 // get the left l-value, save it away
1832 builder.clearAccessChain();
1833 node->getLeft()->traverse(this);
1834 spv::Builder::AccessChain lValue = builder.getAccessChain();
1835
1836 // evaluate the right
1837 builder.clearAccessChain();
1838 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001839 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001840
1841 if (node->getOp() != glslang::EOpAssign) {
1842 // the left is also an r-value
1843 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001844 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001845
1846 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001847 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001848 TranslateNoContractionDecoration(node->getType().getQualifier()),
1849 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001850 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001851 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1852 node->getType().getBasicType());
1853
1854 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001855 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001856 }
1857
1858 // store the result
1859 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001860 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001861
1862 // assignments are expressions having an rValue after they are evaluated...
1863 builder.clearAccessChain();
1864 builder.setAccessChainRValue(rValue);
1865 }
1866 return false;
1867 case glslang::EOpIndexDirect:
1868 case glslang::EOpIndexDirectStruct:
1869 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001870 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001871 // Get the left part of the access chain.
1872 node->getLeft()->traverse(this);
1873
1874 // Add the next element in the chain
1875
David Netoa901ffe2016-06-08 14:11:40 +01001876 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001877 if (! node->getLeft()->getType().isArray() &&
1878 node->getLeft()->getType().isVector() &&
1879 node->getOp() == glslang::EOpIndexDirect) {
1880 // This is essentially a hard-coded vector swizzle of size 1,
1881 // so short circuit the access-chain stuff with a swizzle.
1882 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001883 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001884 int dummySize;
1885 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1886 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001887 glslangIntermediate->getBaseAlignmentScalar(
1888 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001889 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001890
1891 // Load through a block reference is performed with a dot operator that
1892 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1893 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001894 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001895 !node->getLeft()->getType().isArray() &&
1896 node->getOp() == glslang::EOpIndexDirectStruct)
1897 {
1898 spv::Id left = accessChainLoad(node->getLeft()->getType());
1899 builder.clearAccessChain();
1900 builder.setAccessChainLValue(left);
1901 }
1902
David Netoa901ffe2016-06-08 14:11:40 +01001903 int spvIndex = glslangIndex;
1904 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1905 node->getOp() == glslang::EOpIndexDirectStruct)
1906 {
1907 // This may be, e.g., an anonymous block-member selection, which generally need
1908 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001909 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1910 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1911 std::vector<int>& remapper = memberRemapper[glslangId];
1912 assert(remapper.size() > 0);
1913 spvIndex = remapper[glslangIndex];
1914 }
David Netoa901ffe2016-06-08 14:11:40 +01001915 }
John Kessenichebb50532016-05-16 19:22:05 -06001916
David Netoa901ffe2016-06-08 14:11:40 +01001917 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001918 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1919 TranslateCoherent(node->getLeft()->getType()),
1920 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001921
1922 // Add capabilities here for accessing PointSize and clip/cull distance.
1923 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001924 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001925 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001926 }
1927 }
1928 return false;
1929 case glslang::EOpIndexIndirect:
1930 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001931 // Array, matrix, or vector indirection with variable index.
1932 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001933 // matrices are arrays of vectors, so will also work for a matrix.
1934 // Will use the access chain's 'component' for variable index into a vector.
1935
1936 // This adapter is building access chains left to right.
1937 // Set up the access chain to the left.
1938 node->getLeft()->traverse(this);
1939
1940 // save it so that computing the right side doesn't trash it
1941 spv::Builder::AccessChain partial = builder.getAccessChain();
1942
1943 // compute the next index in the chain
1944 builder.clearAccessChain();
1945 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001946 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001947
John Kessenich5611c6d2018-04-05 11:25:02 -06001948 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1949
John Kessenich140f3df2015-06-26 16:58:36 -06001950 // restore the saved access chain
1951 builder.setAccessChain(partial);
1952
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001953 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1954 int dummySize;
1955 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1956 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001957 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1958 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001959 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001960 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1961 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001962 }
1963 return false;
1964 case glslang::EOpVectorSwizzle:
1965 {
1966 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001967 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001968 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001969 int dummySize;
1970 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1971 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001972 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1973 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001974 }
1975 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001976 case glslang::EOpMatrixSwizzle:
1977 logger->missingFunctionality("matrix swizzle");
1978 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001979 case glslang::EOpLogicalOr:
1980 case glslang::EOpLogicalAnd:
1981 {
1982
1983 // These may require short circuiting, but can sometimes be done as straight
1984 // binary operations. The right operand must be short circuited if it has
1985 // side effects, and should probably be if it is complex.
1986 if (isTrivial(node->getRight()->getAsTyped()))
1987 break; // handle below as a normal binary operation
1988 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001989 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1990 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001991 builder.clearAccessChain();
1992 builder.setAccessChainRValue(result);
1993 }
1994 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001995 default:
1996 break;
1997 }
1998
1999 // Assume generic binary op...
2000
John Kessenich32cfd492016-02-02 12:37:46 -07002001 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002002 builder.clearAccessChain();
2003 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002004 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002005
John Kessenich32cfd492016-02-02 12:37:46 -07002006 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002007 builder.clearAccessChain();
2008 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002009 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002010
John Kessenich32cfd492016-02-02 12:37:46 -07002011 // get result
John Kessenichead86222018-03-28 18:01:20 -06002012 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002013 TranslateNoContractionDecoration(node->getType().getQualifier()),
2014 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002015 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002016 convertGlslangToSpvType(node->getType()), left, right,
2017 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002018
John Kessenich50e57562015-12-21 21:21:11 -07002019 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002020 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002021 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002022 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002023 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002024 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002025 return false;
2026 }
John Kessenich140f3df2015-06-26 16:58:36 -06002027}
2028
John Kessenich9c14f772019-06-17 08:38:35 -06002029// Figure out what, if any, type changes are needed when accessing a specific built-in.
2030// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2031// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002032std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002033 const glslang::TType& glslangType)
2034{
Daniel Kochdb32b242020-03-17 20:42:47 -04002035 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002036 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002037 case glslang::EbvSubGroupEqMask:
2038 case glslang::EbvSubGroupGeMask:
2039 case glslang::EbvSubGroupGtMask:
2040 case glslang::EbvSubGroupLeMask:
2041 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002042 // these require changing a 64-bit scaler -> a vector of 32-bit components
2043 if (glslangType.isVector())
2044 break;
2045 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2046 builder.makeUintType(64));
2047 return ret;
2048 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002049 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2050 // builtins. During visitBinary we insert a transpose
2051 case glslang::EbvWorldToObject3x4:
2052 case glslang::EbvObjectToWorld3x4: {
2053 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2054 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2055 );
2056 return ret;
2057 }
John Kessenich9c14f772019-06-17 08:38:35 -06002058 default:
2059 break;
2060 }
2061
2062 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2063 return ret;
2064}
2065
2066// For an object previously identified (see getForcedType() and forceType)
2067// as needing type translations, do the translation needed for a load, turning
2068// an L-value into in R-value.
2069spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2070{
2071 const auto forceIt = forceType.find(object);
2072 if (forceIt == forceType.end())
2073 return object;
2074
2075 spv::Id desiredTypeId = forceIt->second;
2076 spv::Id objectTypeId = builder.getTypeId(object);
2077 assert(builder.isPointerType(objectTypeId));
2078 objectTypeId = builder.getContainedTypeId(objectTypeId);
2079 if (builder.isVectorType(objectTypeId) &&
2080 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2081 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2082 // handle 32-bit v.xy* -> 64-bit
2083 builder.clearAccessChain();
2084 builder.setAccessChainLValue(object);
2085 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2086 std::vector<spv::Id> components;
2087 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2088 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2089
2090 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2091 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2092 builder.createCompositeConstruct(vecType, components));
2093 } else {
2094 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2095 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002096 } else if (builder.isMatrixType(objectTypeId)) {
2097 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2098 // and we insert a transpose after loading the original non-transposed builtins
2099 builder.clearAccessChain();
2100 builder.setAccessChainLValue(object);
2101 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2102 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2103
2104 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002105 logger->missingFunctionality("forcing non 32-bit vector type");
2106 }
2107
2108 return object;
2109}
2110
John Kessenich140f3df2015-06-26 16:58:36 -06002111bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2112{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002113 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002114
qining40887662016-04-03 22:20:42 -04002115 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2116 if (node->getType().getQualifier().isSpecConstant())
2117 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2118
John Kessenichfc51d282015-08-19 13:34:18 -06002119 spv::Id result = spv::NoResult;
2120
2121 // try texturing first
2122 result = createImageTextureFunctionCall(node);
2123 if (result != spv::NoResult) {
2124 builder.clearAccessChain();
2125 builder.setAccessChainRValue(result);
2126
2127 return false; // done with this node
2128 }
2129
2130 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002131
2132 if (node->getOp() == glslang::EOpArrayLength) {
2133 // Quite special; won't want to evaluate the operand.
2134
John Kessenich5611c6d2018-04-05 11:25:02 -06002135 // Currently, the front-end does not allow .length() on an array until it is sized,
2136 // except for the last block membeor of an SSBO.
2137 // TODO: If this changes, link-time sized arrays might show up here, and need their
2138 // size extracted.
2139
John Kessenichc9a80832015-09-12 12:17:44 -06002140 // Normal .length() would have been constant folded by the front-end.
2141 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002142 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002143
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002144 spv::Id length;
2145 if (node->getOperand()->getType().isCoopMat()) {
2146 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2147
2148 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2149 assert(builder.isCooperativeMatrixType(typeId));
2150
2151 length = builder.createCooperativeMatrixLength(typeId);
2152 } else {
2153 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2154 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002155 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2156 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002157 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2158 }
John Kessenichc9a80832015-09-12 12:17:44 -06002159
John Kessenich8c869672018-11-28 07:01:37 -07002160 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2161 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2162 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002163 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2164 if (builder.isInSpecConstCodeGenMode()) {
2165 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2166 } else {
2167 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2168 }
2169 }
John Kessenich8c869672018-11-28 07:01:37 -07002170
John Kessenichc9a80832015-09-12 12:17:44 -06002171 builder.clearAccessChain();
2172 builder.setAccessChainRValue(length);
2173
2174 return false;
2175 }
2176
John Kessenichfc51d282015-08-19 13:34:18 -06002177 // Start by evaluating the operand
2178
John Kessenich8c8505c2016-07-26 12:50:38 -06002179 // Does it need a swizzle inversion? If so, evaluation is inverted;
2180 // operate first on the swizzle base, then apply the swizzle.
2181 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002182 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2183 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002184 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2185 invertedType = getInvertedSwizzleType(*node->getOperand());
2186
John Kessenich140f3df2015-06-26 16:58:36 -06002187 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002188 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002189 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002190 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002191 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002192 operandNode = node->getOperand();
2193
2194 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002195
Rex Xufc618912015-09-09 16:42:49 +08002196 spv::Id operand = spv::NoResult;
2197
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002198 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2199
John Kessenichfb4f2332019-08-09 03:49:15 -06002200#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002201 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2202 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002203 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002204 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2205 node->getOp() == glslang::EOpRayQueryProceed ||
2206 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2207 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2208 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2209 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2210 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2211 node->getOp() == glslang::EOpRayQueryTerminate ||
2212 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002213 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002214 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2215 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2216 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002217#endif
2218 {
John Kessenich32cfd492016-02-02 12:37:46 -07002219 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002220 }
John Kessenich140f3df2015-06-26 16:58:36 -06002221
John Kessenichead86222018-03-28 18:01:20 -06002222 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002223 TranslateNoContractionDecoration(node->getType().getQualifier()),
2224 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002225
2226 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002227 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002228 result = createConversion(node->getOp(), decorations, resultType(), operand,
2229 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002230
2231 // if not, then possibly an operation
2232 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002233 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2234 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002235
2236 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002237 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002238 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002239 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002240 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002241
John Kessenich140f3df2015-06-26 16:58:36 -06002242 builder.clearAccessChain();
2243 builder.setAccessChainRValue(result);
2244
2245 return false; // done with this node
2246 }
2247
2248 // it must be a special case, check...
2249 switch (node->getOp()) {
2250 case glslang::EOpPostIncrement:
2251 case glslang::EOpPostDecrement:
2252 case glslang::EOpPreIncrement:
2253 case glslang::EOpPreDecrement:
2254 {
2255 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002256 spv::Id one = 0;
2257 if (node->getBasicType() == glslang::EbtFloat)
2258 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002259#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002260 else if (node->getBasicType() == glslang::EbtDouble)
2261 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002262 else if (node->getBasicType() == glslang::EbtFloat16)
2263 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002264 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2265 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002266 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2267 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002268 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2269 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002270#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002271 else
2272 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002273 glslang::TOperator op;
2274 if (node->getOp() == glslang::EOpPreIncrement ||
2275 node->getOp() == glslang::EOpPostIncrement)
2276 op = glslang::EOpAdd;
2277 else
2278 op = glslang::EOpSub;
2279
John Kessenichead86222018-03-28 18:01:20 -06002280 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002281 convertGlslangToSpvType(node->getType()), operand, one,
2282 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002283 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002284
2285 // The result of operation is always stored, but conditionally the
2286 // consumed result. The consumed result is always an r-value.
2287 builder.accessChainStore(result);
2288 builder.clearAccessChain();
2289 if (node->getOp() == glslang::EOpPreIncrement ||
2290 node->getOp() == glslang::EOpPreDecrement)
2291 builder.setAccessChainRValue(result);
2292 else
2293 builder.setAccessChainRValue(operand);
2294 }
2295
2296 return false;
2297
John Kessenich155d3512019-08-08 23:29:20 -06002298#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002299 case glslang::EOpEmitStreamVertex:
2300 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2301 return false;
2302 case glslang::EOpEndStreamPrimitive:
2303 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2304 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002305 case glslang::EOpRayQueryTerminate:
2306 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2307 return false;
2308 case glslang::EOpRayQueryConfirmIntersection:
2309 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2310 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002311#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002312
2313 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002314 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002315 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002316 }
John Kessenich140f3df2015-06-26 16:58:36 -06002317}
2318
Jeff Bolz53134492019-06-25 13:31:10 -05002319// Construct a composite object, recursively copying members if their types don't match
2320spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2321{
2322 for (int c = 0; c < (int)constituents.size(); ++c) {
2323 spv::Id& constituent = constituents[c];
2324 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2325 spv::Id rType = builder.getTypeId(constituent);
2326 if (lType != rType) {
2327 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2328 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2329 } else if (builder.isStructType(rType)) {
2330 std::vector<spv::Id> rTypeConstituents;
2331 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2332 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002333 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2334 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002335 }
2336 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2337 } else {
2338 assert(builder.isArrayType(rType));
2339 std::vector<spv::Id> rTypeConstituents;
2340 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2341
2342 spv::Id elementRType = builder.getContainedTypeId(rType);
2343 for (int i = 0; i < numrTypeConstituents; ++i) {
2344 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2345 }
2346 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2347 }
2348 }
2349 }
2350 return builder.createCompositeConstruct(resultTypeId, constituents);
2351}
2352
John Kessenich140f3df2015-06-26 16:58:36 -06002353bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2354{
qining27e04a02016-04-14 16:40:20 -04002355 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2356 if (node->getType().getQualifier().isSpecConstant())
2357 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2358
John Kessenichfc51d282015-08-19 13:34:18 -06002359 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002360 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2361 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2362 // SPIR-V, for an out parameter
2363 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002364
John Kessenich8985fc92020-03-03 10:25:07 -07002365 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2366 invertedType :
2367 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002368
2369 // try texturing
2370 result = createImageTextureFunctionCall(node);
2371 if (result != spv::NoResult) {
2372 builder.clearAccessChain();
2373 builder.setAccessChainRValue(result);
2374
2375 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002376 }
2377#ifndef GLSLANG_WEB
2378 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002379 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002380 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002381 // "imageStore" is a special case, which has no result
2382 return false;
2383 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002384#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002385
John Kessenich140f3df2015-06-26 16:58:36 -06002386 glslang::TOperator binOp = glslang::EOpNull;
2387 bool reduceComparison = true;
2388 bool isMatrix = false;
2389 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002390 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002391
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002392 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2393
John Kessenich140f3df2015-06-26 16:58:36 -06002394 assert(node->getOp());
2395
John Kessenichf6640762016-08-01 19:44:00 -06002396 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002397
2398 switch (node->getOp()) {
2399 case glslang::EOpSequence:
2400 {
2401 if (preVisit)
2402 ++sequenceDepth;
2403 else
2404 --sequenceDepth;
2405
2406 if (sequenceDepth == 1) {
2407 // If this is the parent node of all the functions, we want to see them
2408 // early, so all call points have actual SPIR-V functions to reference.
2409 // In all cases, still let the traverser visit the children for us.
2410 makeFunctions(node->getAsAggregate()->getSequence());
2411
John Kessenich6fccb3c2016-09-19 16:01:41 -06002412 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002413 // anything else gets there, so visit out of order, doing them all now.
2414 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2415
John Kessenich6a60c2f2016-12-08 21:01:59 -07002416 // 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 -06002417 // so do them manually.
2418 visitFunctions(node->getAsAggregate()->getSequence());
2419
2420 return false;
2421 }
2422
2423 return true;
2424 }
2425 case glslang::EOpLinkerObjects:
2426 {
2427 if (visit == glslang::EvPreVisit)
2428 linkageOnly = true;
2429 else
2430 linkageOnly = false;
2431
2432 return true;
2433 }
2434 case glslang::EOpComma:
2435 {
2436 // processing from left to right naturally leaves the right-most
2437 // lying around in the access chain
2438 glslang::TIntermSequence& glslangOperands = node->getSequence();
2439 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2440 glslangOperands[i]->traverse(this);
2441
2442 return false;
2443 }
2444 case glslang::EOpFunction:
2445 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002446 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002447 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002448 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002449 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002450 } else {
2451 handleFunctionEntry(node);
2452 }
2453 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002454 if (inEntryPoint)
2455 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002456 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002457 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002458 }
2459
2460 return true;
2461 case glslang::EOpParameters:
2462 // Parameters will have been consumed by EOpFunction processing, but not
2463 // the body, so we still visited the function node's children, making this
2464 // child redundant.
2465 return false;
2466 case glslang::EOpFunctionCall:
2467 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002468 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002469 if (node->isUserDefined())
2470 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002471 if (result) {
2472 builder.clearAccessChain();
2473 builder.setAccessChainRValue(result);
2474 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002475 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002476
2477 return false;
2478 }
2479 case glslang::EOpConstructMat2x2:
2480 case glslang::EOpConstructMat2x3:
2481 case glslang::EOpConstructMat2x4:
2482 case glslang::EOpConstructMat3x2:
2483 case glslang::EOpConstructMat3x3:
2484 case glslang::EOpConstructMat3x4:
2485 case glslang::EOpConstructMat4x2:
2486 case glslang::EOpConstructMat4x3:
2487 case glslang::EOpConstructMat4x4:
2488 case glslang::EOpConstructDMat2x2:
2489 case glslang::EOpConstructDMat2x3:
2490 case glslang::EOpConstructDMat2x4:
2491 case glslang::EOpConstructDMat3x2:
2492 case glslang::EOpConstructDMat3x3:
2493 case glslang::EOpConstructDMat3x4:
2494 case glslang::EOpConstructDMat4x2:
2495 case glslang::EOpConstructDMat4x3:
2496 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002497 case glslang::EOpConstructIMat2x2:
2498 case glslang::EOpConstructIMat2x3:
2499 case glslang::EOpConstructIMat2x4:
2500 case glslang::EOpConstructIMat3x2:
2501 case glslang::EOpConstructIMat3x3:
2502 case glslang::EOpConstructIMat3x4:
2503 case glslang::EOpConstructIMat4x2:
2504 case glslang::EOpConstructIMat4x3:
2505 case glslang::EOpConstructIMat4x4:
2506 case glslang::EOpConstructUMat2x2:
2507 case glslang::EOpConstructUMat2x3:
2508 case glslang::EOpConstructUMat2x4:
2509 case glslang::EOpConstructUMat3x2:
2510 case glslang::EOpConstructUMat3x3:
2511 case glslang::EOpConstructUMat3x4:
2512 case glslang::EOpConstructUMat4x2:
2513 case glslang::EOpConstructUMat4x3:
2514 case glslang::EOpConstructUMat4x4:
2515 case glslang::EOpConstructBMat2x2:
2516 case glslang::EOpConstructBMat2x3:
2517 case glslang::EOpConstructBMat2x4:
2518 case glslang::EOpConstructBMat3x2:
2519 case glslang::EOpConstructBMat3x3:
2520 case glslang::EOpConstructBMat3x4:
2521 case glslang::EOpConstructBMat4x2:
2522 case glslang::EOpConstructBMat4x3:
2523 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002524 case glslang::EOpConstructF16Mat2x2:
2525 case glslang::EOpConstructF16Mat2x3:
2526 case glslang::EOpConstructF16Mat2x4:
2527 case glslang::EOpConstructF16Mat3x2:
2528 case glslang::EOpConstructF16Mat3x3:
2529 case glslang::EOpConstructF16Mat3x4:
2530 case glslang::EOpConstructF16Mat4x2:
2531 case glslang::EOpConstructF16Mat4x3:
2532 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002533 isMatrix = true;
2534 // fall through
2535 case glslang::EOpConstructFloat:
2536 case glslang::EOpConstructVec2:
2537 case glslang::EOpConstructVec3:
2538 case glslang::EOpConstructVec4:
2539 case glslang::EOpConstructDouble:
2540 case glslang::EOpConstructDVec2:
2541 case glslang::EOpConstructDVec3:
2542 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002543 case glslang::EOpConstructFloat16:
2544 case glslang::EOpConstructF16Vec2:
2545 case glslang::EOpConstructF16Vec3:
2546 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002547 case glslang::EOpConstructBool:
2548 case glslang::EOpConstructBVec2:
2549 case glslang::EOpConstructBVec3:
2550 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002551 case glslang::EOpConstructInt8:
2552 case glslang::EOpConstructI8Vec2:
2553 case glslang::EOpConstructI8Vec3:
2554 case glslang::EOpConstructI8Vec4:
2555 case glslang::EOpConstructUint8:
2556 case glslang::EOpConstructU8Vec2:
2557 case glslang::EOpConstructU8Vec3:
2558 case glslang::EOpConstructU8Vec4:
2559 case glslang::EOpConstructInt16:
2560 case glslang::EOpConstructI16Vec2:
2561 case glslang::EOpConstructI16Vec3:
2562 case glslang::EOpConstructI16Vec4:
2563 case glslang::EOpConstructUint16:
2564 case glslang::EOpConstructU16Vec2:
2565 case glslang::EOpConstructU16Vec3:
2566 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002567 case glslang::EOpConstructInt:
2568 case glslang::EOpConstructIVec2:
2569 case glslang::EOpConstructIVec3:
2570 case glslang::EOpConstructIVec4:
2571 case glslang::EOpConstructUint:
2572 case glslang::EOpConstructUVec2:
2573 case glslang::EOpConstructUVec3:
2574 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002575 case glslang::EOpConstructInt64:
2576 case glslang::EOpConstructI64Vec2:
2577 case glslang::EOpConstructI64Vec3:
2578 case glslang::EOpConstructI64Vec4:
2579 case glslang::EOpConstructUint64:
2580 case glslang::EOpConstructU64Vec2:
2581 case glslang::EOpConstructU64Vec3:
2582 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002583 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002584 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002585 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002586 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002587 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002588 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002589 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002590 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002591 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002592 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002593 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002594 else if (node->getOp() == glslang::EOpConstructStruct ||
2595 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2596 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002597 std::vector<spv::Id> constituents;
2598 for (int c = 0; c < (int)arguments.size(); ++c)
2599 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002600 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002601 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002602 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002603 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002604 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002605
2606 builder.clearAccessChain();
2607 builder.setAccessChainRValue(constructed);
2608
2609 return false;
2610 }
2611
2612 // These six are component-wise compares with component-wise results.
2613 // Forward on to createBinaryOperation(), requesting a vector result.
2614 case glslang::EOpLessThan:
2615 case glslang::EOpGreaterThan:
2616 case glslang::EOpLessThanEqual:
2617 case glslang::EOpGreaterThanEqual:
2618 case glslang::EOpVectorEqual:
2619 case glslang::EOpVectorNotEqual:
2620 {
2621 // Map the operation to a binary
2622 binOp = node->getOp();
2623 reduceComparison = false;
2624 switch (node->getOp()) {
2625 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2626 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2627 default: binOp = node->getOp(); break;
2628 }
2629
2630 break;
2631 }
2632 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002633 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002634 binOp = glslang::EOpMul;
2635 break;
2636 case glslang::EOpOuterProduct:
2637 // two vectors multiplied to make a matrix
2638 binOp = glslang::EOpOuterProduct;
2639 break;
2640 case glslang::EOpDot:
2641 {
qining25262b32016-05-06 17:25:16 -04002642 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002643 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002644 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002645 binOp = glslang::EOpMul;
2646 break;
2647 }
2648 case glslang::EOpMod:
2649 // when an aggregate, this is the floating-point mod built-in function,
2650 // which can be emitted by the one in createBinaryOperation()
2651 binOp = glslang::EOpMod;
2652 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002653
John Kessenich140f3df2015-06-26 16:58:36 -06002654 case glslang::EOpEmitVertex:
2655 case glslang::EOpEndPrimitive:
2656 case glslang::EOpBarrier:
2657 case glslang::EOpMemoryBarrier:
2658 case glslang::EOpMemoryBarrierAtomicCounter:
2659 case glslang::EOpMemoryBarrierBuffer:
2660 case glslang::EOpMemoryBarrierImage:
2661 case glslang::EOpMemoryBarrierShared:
2662 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002663 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002664 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002665 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002666 case glslang::EOpWorkgroupMemoryBarrier:
2667 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002668 case glslang::EOpSubgroupBarrier:
2669 case glslang::EOpSubgroupMemoryBarrier:
2670 case glslang::EOpSubgroupMemoryBarrierBuffer:
2671 case glslang::EOpSubgroupMemoryBarrierImage:
2672 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002673 noReturnValue = true;
2674 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2675 break;
2676
John Kessenich426394d2015-07-23 10:22:48 -06002677 case glslang::EOpAtomicAdd:
2678 case glslang::EOpAtomicMin:
2679 case glslang::EOpAtomicMax:
2680 case glslang::EOpAtomicAnd:
2681 case glslang::EOpAtomicOr:
2682 case glslang::EOpAtomicXor:
2683 case glslang::EOpAtomicExchange:
2684 case glslang::EOpAtomicCompSwap:
2685 atomic = true;
2686 break;
2687
John Kesseniche5eee8f2019-10-18 01:03:11 -06002688#ifndef GLSLANG_WEB
2689 case glslang::EOpAtomicStore:
2690 noReturnValue = true;
2691 // fallthrough
2692 case glslang::EOpAtomicLoad:
2693 atomic = true;
2694 break;
2695
John Kessenich0d0c6d32017-07-23 16:08:26 -06002696 case glslang::EOpAtomicCounterAdd:
2697 case glslang::EOpAtomicCounterSubtract:
2698 case glslang::EOpAtomicCounterMin:
2699 case glslang::EOpAtomicCounterMax:
2700 case glslang::EOpAtomicCounterAnd:
2701 case glslang::EOpAtomicCounterOr:
2702 case glslang::EOpAtomicCounterXor:
2703 case glslang::EOpAtomicCounterExchange:
2704 case glslang::EOpAtomicCounterCompSwap:
2705 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2706 builder.addCapability(spv::CapabilityAtomicStorageOps);
2707 atomic = true;
2708 break;
2709
Ian Romanickb3bd4022019-01-21 08:57:25 -08002710 case glslang::EOpAbsDifference:
2711 case glslang::EOpAddSaturate:
2712 case glslang::EOpSubSaturate:
2713 case glslang::EOpAverage:
2714 case glslang::EOpAverageRounded:
2715 case glslang::EOpMul32x16:
2716 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2717 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2718 binOp = node->getOp();
2719 break;
2720
Daniel Kochdb32b242020-03-17 20:42:47 -04002721 case glslang::EOpIgnoreIntersection:
2722 case glslang::EOpTerminateRay:
2723 case glslang::EOpTrace:
2724 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002725 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2726 noReturnValue = true;
2727 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002728 case glslang::EOpRayQueryInitialize:
2729 case glslang::EOpRayQueryTerminate:
2730 case glslang::EOpRayQueryGenerateIntersection:
2731 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002732 builder.addExtension("SPV_KHR_ray_query");
2733 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002734 noReturnValue = true;
2735 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002736 case glslang::EOpRayQueryProceed:
2737 case glslang::EOpRayQueryGetIntersectionType:
2738 case glslang::EOpRayQueryGetRayTMin:
2739 case glslang::EOpRayQueryGetRayFlags:
2740 case glslang::EOpRayQueryGetIntersectionT:
2741 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2742 case glslang::EOpRayQueryGetIntersectionInstanceId:
2743 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2744 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2745 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2746 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2747 case glslang::EOpRayQueryGetIntersectionFrontFace:
2748 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2749 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2750 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2751 case glslang::EOpRayQueryGetWorldRayDirection:
2752 case glslang::EOpRayQueryGetWorldRayOrigin:
2753 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2754 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2755 builder.addExtension("SPV_KHR_ray_query");
2756 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2757 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002758 case glslang::EOpCooperativeMatrixLoad:
2759 case glslang::EOpCooperativeMatrixStore:
2760 noReturnValue = true;
2761 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002762 case glslang::EOpBeginInvocationInterlock:
2763 case glslang::EOpEndInvocationInterlock:
2764 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2765 noReturnValue = true;
2766 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002767#endif
Chao Chen3c366992018-09-19 11:41:59 -07002768
Jeff Bolz04d73732019-05-31 13:06:01 -05002769 case glslang::EOpDebugPrintf:
2770 noReturnValue = true;
2771 break;
2772
John Kessenich140f3df2015-06-26 16:58:36 -06002773 default:
2774 break;
2775 }
2776
2777 //
2778 // See if it maps to a regular operation.
2779 //
John Kessenich140f3df2015-06-26 16:58:36 -06002780 if (binOp != glslang::EOpNull) {
2781 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2782 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2783 assert(left && right);
2784
2785 builder.clearAccessChain();
2786 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002787 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002788
2789 builder.clearAccessChain();
2790 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002791 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002792
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002793 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002794 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002795 TranslateNoContractionDecoration(node->getType().getQualifier()),
2796 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002797 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002798 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002799 left->getType().getBasicType(), reduceComparison);
2800
2801 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002802 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002803 builder.clearAccessChain();
2804 builder.setAccessChainRValue(result);
2805
2806 return false;
2807 }
2808
John Kessenich426394d2015-07-23 10:22:48 -06002809 //
2810 // Create the list of operands.
2811 //
John Kessenich140f3df2015-06-26 16:58:36 -06002812 glslang::TIntermSequence& glslangOperands = node->getSequence();
2813 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002814 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002815 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002816 // special case l-value operands; there are just a few
2817 bool lvalue = false;
2818 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002819 case glslang::EOpModf:
2820 if (arg == 1)
2821 lvalue = true;
2822 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002823
Torosdagli06c2eee2020-03-19 11:09:57 -04002824 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002825 case glslang::EOpRayQueryTerminate:
2826 case glslang::EOpRayQueryConfirmIntersection:
2827 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002828 case glslang::EOpRayQueryGenerateIntersection:
2829 case glslang::EOpRayQueryGetIntersectionType:
2830 case glslang::EOpRayQueryGetIntersectionT:
2831 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2832 case glslang::EOpRayQueryGetIntersectionInstanceId:
2833 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2834 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2835 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2836 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2837 case glslang::EOpRayQueryGetIntersectionFrontFace:
2838 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2839 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2840 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2841 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2842 if (arg == 0)
2843 lvalue = true;
2844 break;
2845
John Kesseniche5eee8f2019-10-18 01:03:11 -06002846 case glslang::EOpAtomicAdd:
2847 case glslang::EOpAtomicMin:
2848 case glslang::EOpAtomicMax:
2849 case glslang::EOpAtomicAnd:
2850 case glslang::EOpAtomicOr:
2851 case glslang::EOpAtomicXor:
2852 case glslang::EOpAtomicExchange:
2853 case glslang::EOpAtomicCompSwap:
2854 if (arg == 0)
2855 lvalue = true;
2856 break;
2857
John Kessenicha28f7a72019-08-06 07:00:58 -06002858#ifndef GLSLANG_WEB
2859 case glslang::EOpFrexp:
2860 if (arg == 1)
2861 lvalue = true;
2862 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002863 case glslang::EOpInterpolateAtSample:
2864 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002865 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002866 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002867 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002868
2869 // Does it need a swizzle inversion? If so, evaluation is inverted;
2870 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002871 // That is, we transform
2872 //
2873 // interpolate(v.zy) -> interpolate(v).zy
2874 //
John Kessenichecba76f2017-01-06 00:34:48 -07002875 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002876 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002877 invertedType = convertGlslangToSpvType(
2878 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002879 }
Rex Xu7a26c172015-12-08 17:12:09 +08002880 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002881 case glslang::EOpAtomicLoad:
2882 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002883 case glslang::EOpAtomicCounterAdd:
2884 case glslang::EOpAtomicCounterSubtract:
2885 case glslang::EOpAtomicCounterMin:
2886 case glslang::EOpAtomicCounterMax:
2887 case glslang::EOpAtomicCounterAnd:
2888 case glslang::EOpAtomicCounterOr:
2889 case glslang::EOpAtomicCounterXor:
2890 case glslang::EOpAtomicCounterExchange:
2891 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002892 if (arg == 0)
2893 lvalue = true;
2894 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002895 case glslang::EOpAddCarry:
2896 case glslang::EOpSubBorrow:
2897 if (arg == 2)
2898 lvalue = true;
2899 break;
2900 case glslang::EOpUMulExtended:
2901 case glslang::EOpIMulExtended:
2902 if (arg >= 2)
2903 lvalue = true;
2904 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002905 case glslang::EOpCooperativeMatrixLoad:
2906 if (arg == 0 || arg == 1)
2907 lvalue = true;
2908 break;
2909 case glslang::EOpCooperativeMatrixStore:
2910 if (arg == 1)
2911 lvalue = true;
2912 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002913#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002914 default:
2915 break;
2916 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002917 builder.clearAccessChain();
2918 if (invertedType != spv::NoType && arg == 0)
2919 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2920 else
2921 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002922
John Kessenichb9197c82019-08-11 07:41:45 -06002923#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002924 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2925 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2926
2927 if (arg == 1) {
2928 // fold "element" parameter into the access chain
2929 spv::Builder::AccessChain save = builder.getAccessChain();
2930 builder.clearAccessChain();
2931 glslangOperands[2]->traverse(this);
2932
2933 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2934
2935 builder.setAccessChain(save);
2936
2937 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002938 builder.accessChainPush(elementId,
2939 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2940 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002941
2942 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2943 unsigned int alignment = builder.getAccessChain().alignment;
2944
2945 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2946 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2947 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2948 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2949 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002950 if (builder.getStorageClass(builder.getAccessChain().base) ==
2951 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002952 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2953 }
2954
2955 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2956
2957 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2958 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2959 }
2960
John Kessenich8985fc92020-03-03 10:25:07 -07002961 if (memoryAccess &
2962 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2963 memoryAccessOperands.push_back(spv::IdImmediate(true,
2964 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002965 }
2966 } else if (arg == 2) {
2967 continue;
2968 }
2969 }
John Kessenichb9197c82019-08-11 07:41:45 -06002970#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002971
John Kessenichbbbd9a22020-03-03 07:21:37 -07002972 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002973 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002974 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2975 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2976 // reduce to a simple access chain. So, we need a temporary vector to
2977 // receive the result, and must later swizzle that into the original
2978 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002979 complexLvalues.push_back(builder.getAccessChain());
2980 temporaryLvalues.push_back(builder.createVariable(spv::StorageClassFunction,
2981 builder.accessChainGetInferredType(), "swizzleTemp"));
2982 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002983 } else {
2984 operands.push_back(builder.accessChainGetLValue());
2985 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002986 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2987 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2988 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002989 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002990 glslang::TOperator glslangOp = node->getOp();
2991 if (arg == 1 &&
2992 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2993 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2994 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2995 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
2996 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
2997 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
2998 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
2999 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3001 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3002 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3003 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3004 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3005 )) {
3006 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3007 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3008 }
3009 else {
3010 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3011 }
3012
John Kesseniche485c7a2017-05-31 18:50:53 -06003013 }
John Kessenich140f3df2015-06-26 16:58:36 -06003014 }
John Kessenich426394d2015-07-23 10:22:48 -06003015
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003016 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003017#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003018 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3019 std::vector<spv::IdImmediate> idImmOps;
3020
3021 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3022 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3023 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3024 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3025 // get the pointee type
3026 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3027 assert(builder.isCooperativeMatrixType(typeId));
3028 // do the op
3029 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3030 // store the result to the pointer (out param 'm')
3031 builder.createStore(result, operands[0]);
3032 result = 0;
3033 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3034 std::vector<spv::IdImmediate> idImmOps;
3035
3036 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3037 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3038 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3039 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3040 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3041
3042 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3043 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003044 } else
3045#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003046 if (atomic) {
3047 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003048 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3049 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003050 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3051 if (!nonSemanticDebugPrintf) {
3052 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3053 }
3054 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3055 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003056 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003057 // Pass through to generic operations.
3058 switch (glslangOperands.size()) {
3059 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003060 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003061 break;
3062 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003063 {
3064 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003065 TranslateNoContractionDecoration(node->getType().getQualifier()),
3066 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003067 result = createUnaryOperation(
3068 node->getOp(), decorations,
3069 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003070 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003071 }
John Kessenich426394d2015-07-23 10:22:48 -06003072 break;
3073 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003074 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003075 break;
3076 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003077
John Kessenichbbbd9a22020-03-03 07:21:37 -07003078 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003079 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003080
3081 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3082 builder.setAccessChain(complexLvalues[i]);
3083 builder.accessChainStore(builder.createLoad(temporaryLvalues[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003084 }
John Kessenich140f3df2015-06-26 16:58:36 -06003085 }
3086
3087 if (noReturnValue)
3088 return false;
3089
3090 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003091 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003092 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003093 } else {
3094 builder.clearAccessChain();
3095 builder.setAccessChainRValue(result);
3096 return false;
3097 }
3098}
3099
John Kessenich433e9ff2017-01-26 20:31:11 -07003100// This path handles both if-then-else and ?:
3101// The if-then-else has a node type of void, while
3102// ?: has either a void or a non-void node type
3103//
3104// Leaving the result, when not void:
3105// GLSL only has r-values as the result of a :?, but
3106// if we have an l-value, that can be more efficient if it will
3107// become the base of a complex r-value expression, because the
3108// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003109bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3110{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003111 // see if OpSelect can handle it
3112 const auto isOpSelectable = [&]() {
3113 if (node->getBasicType() == glslang::EbtVoid)
3114 return false;
3115 // OpSelect can do all other types starting with SPV 1.4
3116 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3117 // pre-1.4, only scalars and vectors can be handled
3118 if ((!node->getType().isScalar() && !node->getType().isVector()))
3119 return false;
3120 }
3121 return true;
3122 };
3123
John Kessenich4bee5312018-02-20 21:29:05 -07003124 // See if it simple and safe, or required, to execute both sides.
3125 // Crucially, side effects must be either semantically required or avoided,
3126 // and there are performance trade-offs.
3127 // Return true if required or a good idea (and safe) to execute both sides,
3128 // false otherwise.
3129 const auto bothSidesPolicy = [&]() -> bool {
3130 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003131 if (node->getTrueBlock() == nullptr ||
3132 node->getFalseBlock() == nullptr)
3133 return false;
3134
John Kessenich4bee5312018-02-20 21:29:05 -07003135 // required? (unless we write additional code to look for side effects
3136 // and make performance trade-offs if none are present)
3137 if (!node->getShortCircuit())
3138 return true;
3139
3140 // if not required to execute both, decide based on performance/practicality...
3141
John Kessenich0c1e71a2019-01-10 18:23:06 +07003142 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003143 return false;
3144
John Kessenich433e9ff2017-01-26 20:31:11 -07003145 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3146 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3147
3148 // return true if a single operand to ? : is okay for OpSelect
3149 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003150 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003151 };
3152
3153 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3154 operandOkay(node->getFalseBlock()->getAsTyped());
3155 };
3156
John Kessenich4bee5312018-02-20 21:29:05 -07003157 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3158 // emit the condition before doing anything with selection
3159 node->getCondition()->traverse(this);
3160 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3161
3162 // Find a way of executing both sides and selecting the right result.
3163 const auto executeBothSides = [&]() -> void {
3164 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003165 node->getTrueBlock()->traverse(this);
3166 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3167 node->getFalseBlock()->traverse(this);
3168 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3169
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003170 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003171
John Kessenich4bee5312018-02-20 21:29:05 -07003172 // done if void
3173 if (node->getBasicType() == glslang::EbtVoid)
3174 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003175
John Kessenich4bee5312018-02-20 21:29:05 -07003176 // emit code to select between trueValue and falseValue
3177
3178 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003179 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003180 // Emit OpSelect for this selection.
3181
3182 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003183 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3184 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003185 condition = builder.smearScalar(spv::NoPrecision, condition,
3186 builder.makeVectorType(builder.makeBoolType(),
3187 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003188 }
John Kessenich4bee5312018-02-20 21:29:05 -07003189
3190 // OpSelect
3191 result = builder.createTriOp(spv::OpSelect,
3192 convertGlslangToSpvType(node->getType()), condition,
3193 trueValue, falseValue);
3194
3195 builder.clearAccessChain();
3196 builder.setAccessChainRValue(result);
3197 } else {
3198 // We need control flow to select the result.
3199 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3200 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3201
3202 // Selection control:
3203 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3204
3205 // make an "if" based on the value created by the condition
3206 spv::Builder::If ifBuilder(condition, control, builder);
3207
3208 // emit the "then" statement
3209 builder.createStore(trueValue, result);
3210 ifBuilder.makeBeginElse();
3211 // emit the "else" statement
3212 builder.createStore(falseValue, result);
3213
3214 // finish off the control flow
3215 ifBuilder.makeEndIf();
3216
3217 builder.clearAccessChain();
3218 builder.setAccessChainLValue(result);
3219 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003220 };
3221
John Kessenich4bee5312018-02-20 21:29:05 -07003222 // Execute the one side needed, as per the condition
3223 const auto executeOneSide = [&]() {
3224 // Always emit control flow.
3225 if (node->getBasicType() != glslang::EbtVoid)
3226 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003227
John Kessenich4bee5312018-02-20 21:29:05 -07003228 // Selection control:
3229 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3230
3231 // make an "if" based on the value created by the condition
3232 spv::Builder::If ifBuilder(condition, control, builder);
3233
3234 // emit the "then" statement
3235 if (node->getTrueBlock() != nullptr) {
3236 node->getTrueBlock()->traverse(this);
3237 if (result != spv::NoResult)
3238 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3239 }
3240
3241 if (node->getFalseBlock() != nullptr) {
3242 ifBuilder.makeBeginElse();
3243 // emit the "else" statement
3244 node->getFalseBlock()->traverse(this);
3245 if (result != spv::NoResult)
3246 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3247 }
3248
3249 // finish off the control flow
3250 ifBuilder.makeEndIf();
3251
3252 if (result != spv::NoResult) {
3253 builder.clearAccessChain();
3254 builder.setAccessChainLValue(result);
3255 }
3256 };
3257
3258 // Try for OpSelect (or a requirement to execute both sides)
3259 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003260 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3261 if (node->getType().getQualifier().isSpecConstant())
3262 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003263 executeBothSides();
3264 } else
3265 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003266
3267 return false;
3268}
3269
3270bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3271{
3272 // emit and get the condition before doing anything with switch
3273 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003274 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003275
Rex Xu57e65922017-07-04 23:23:40 +08003276 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003277 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003278
John Kessenich140f3df2015-06-26 16:58:36 -06003279 // browse the children to sort out code segments
3280 int defaultSegment = -1;
3281 std::vector<TIntermNode*> codeSegments;
3282 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3283 std::vector<int> caseValues;
3284 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3285 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3286 TIntermNode* child = *c;
3287 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003288 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003289 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003290 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003291 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3292 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003293 } else
3294 codeSegments.push_back(child);
3295 }
3296
qining25262b32016-05-06 17:25:16 -04003297 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003298 // statements between the last case and the end of the switch statement
3299 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3300 (int)codeSegments.size() == defaultSegment)
3301 codeSegments.push_back(nullptr);
3302
3303 // make the switch statement
3304 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003305 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3306 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003307
3308 // emit all the code in the segments
3309 breakForLoop.push(false);
3310 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3311 builder.nextSwitchSegment(segmentBlocks, s);
3312 if (codeSegments[s])
3313 codeSegments[s]->traverse(this);
3314 else
3315 builder.addSwitchBreak();
3316 }
3317 breakForLoop.pop();
3318
3319 builder.endSwitch(segmentBlocks);
3320
3321 return false;
3322}
3323
3324void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3325{
3326 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003327 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003328
3329 builder.clearAccessChain();
3330 builder.setAccessChainRValue(constant);
3331}
3332
3333bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3334{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003335 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003336 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003337
3338 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003339 std::vector<unsigned int> operands;
3340 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003341
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003342 // Spec requires back edges to target header blocks, and every header block
3343 // must dominate its merge block. Make a header block first to ensure these
3344 // conditions are met. By definition, it will contain OpLoopMerge, followed
3345 // by a block-ending branch. But we don't want to put any other body/test
3346 // instructions in it, since the body/test may have arbitrary instructions,
3347 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003348 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003349 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003350 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003351 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003352 spv::Block& test = builder.makeNewBlock();
3353 builder.createBranch(&test);
3354
3355 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003356 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003357 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003358 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3359
3360 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003361 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003362 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003363 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003364 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003365 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003366
3367 builder.setBuildPoint(&blocks.continue_target);
3368 if (node->getTerminal())
3369 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003370 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003371 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003372 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003373 builder.createBranch(&blocks.body);
3374
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003375 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003376 builder.setBuildPoint(&blocks.body);
3377 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003378 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003379 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003380 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003381
3382 builder.setBuildPoint(&blocks.continue_target);
3383 if (node->getTerminal())
3384 node->getTerminal()->traverse(this);
3385 if (node->getTest()) {
3386 node->getTest()->traverse(this);
3387 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003388 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003389 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003390 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003391 // TODO: unless there was a break/return/discard instruction
3392 // somewhere in the body, this is an infinite loop, so we should
3393 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003394 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003395 }
John Kessenich140f3df2015-06-26 16:58:36 -06003396 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003397 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003398 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003399 return false;
3400}
3401
3402bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3403{
3404 if (node->getExpression())
3405 node->getExpression()->traverse(this);
3406
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003407 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003408
John Kessenich140f3df2015-06-26 16:58:36 -06003409 switch (node->getFlowOp()) {
3410 case glslang::EOpKill:
3411 builder.makeDiscard();
3412 break;
3413 case glslang::EOpBreak:
3414 if (breakForLoop.top())
3415 builder.createLoopExit();
3416 else
3417 builder.addSwitchBreak();
3418 break;
3419 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003420 builder.createLoopContinue();
3421 break;
3422 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003423 if (node->getExpression()) {
3424 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3425 spv::Id returnId = accessChainLoad(glslangReturnType);
3426 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3427 builder.clearAccessChain();
3428 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3429 builder.setAccessChainLValue(copyId);
3430 multiTypeStore(glslangReturnType, returnId);
3431 returnId = builder.createLoad(copyId);
3432 }
3433 builder.makeReturn(false, returnId);
3434 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003435 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003436
3437 builder.clearAccessChain();
3438 break;
3439
John Kessenichb9197c82019-08-11 07:41:45 -06003440#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003441 case glslang::EOpDemote:
3442 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3443 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3444 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3445 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003446#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003447
John Kessenich140f3df2015-06-26 16:58:36 -06003448 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003449 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003450 break;
3451 }
3452
3453 return false;
3454}
3455
John Kessenich9c14f772019-06-17 08:38:35 -06003456spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003457{
qining25262b32016-05-06 17:25:16 -04003458 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003459 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003460 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003461 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003462 spv::Id result = createSpvConstant(*node);
3463 if (result != spv::NoResult)
3464 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003465 }
3466
3467 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003468 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003469 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3470 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003471
John Kessenichb9197c82019-08-11 07:41:45 -06003472 const bool contains16BitType = node->getType().contains16BitFloat() ||
3473 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003474 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003475 switch (storageClass) {
3476 case spv::StorageClassInput:
3477 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003478 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003479 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003480 break;
John Kessenich18310872018-05-14 22:08:53 -06003481 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003482 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003483 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3484 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003485 else
3486 builder.addCapability(spv::CapabilityStorageUniform16);
3487 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003488#ifndef GLSLANG_WEB
3489 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003490 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003491 builder.addCapability(spv::CapabilityStoragePushConstant16);
3492 break;
John Kessenich18310872018-05-14 22:08:53 -06003493 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003494 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003495 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003496 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3497 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003498#endif
John Kessenich18310872018-05-14 22:08:53 -06003499 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003500 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003501 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003502 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003503 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003504 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003505 }
3506 }
Rex Xuf89ad982017-04-07 23:22:33 +08003507
John Kessenichb9197c82019-08-11 07:41:45 -06003508 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003509 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003510 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003511 builder.addCapability(spv::CapabilityStoragePushConstant8);
3512 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003513 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003514 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003515 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003516 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003517 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003518 } else {
3519 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003520 }
3521 }
3522
John Kessenich140f3df2015-06-26 16:58:36 -06003523 const char* name = node->getName().c_str();
3524 if (glslang::IsAnonymous(name))
3525 name = "";
3526
3527 return builder.createVariable(storageClass, spvType, name);
3528}
3529
3530// Return type Id of the sampled type.
3531spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3532{
3533 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003534 case glslang::EbtInt: return builder.makeIntType(32);
3535 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003536 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003537#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003538 case glslang::EbtFloat16:
3539 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3540 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3541 return builder.makeFloatType(16);
3542#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003543 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003544 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003545 return builder.makeFloatType(32);
3546 }
3547}
3548
John Kessenich8c8505c2016-07-26 12:50:38 -06003549// If node is a swizzle operation, return the type that should be used if
3550// the swizzle base is first consumed by another operation, before the swizzle
3551// is applied.
3552spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3553{
John Kessenichecba76f2017-01-06 00:34:48 -07003554 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003555 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3556 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3557 else
3558 return spv::NoType;
3559}
3560
3561// When inverting a swizzle with a parent op, this function
3562// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003563spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3564 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003565{
3566 std::vector<unsigned> swizzle;
3567 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3568 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3569}
3570
John Kessenich8c8505c2016-07-26 12:50:38 -06003571// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3572void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3573{
3574 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3575 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3576 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3577}
3578
John Kessenich3ac051e2015-12-20 11:29:16 -07003579// Convert from a glslang type to an SPV type, by calling into a
3580// recursive version of this function. This establishes the inherited
3581// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003582spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003583{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003584 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003585}
3586
3587// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003588// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003589// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003590spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003591 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3592 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003593{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003594 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003595
3596 switch (type.getBasicType()) {
3597 case glslang::EbtVoid:
3598 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003599 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003600 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003601 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003602 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3603 // a 32-bit int where non-0 means true.
3604 if (explicitLayout != glslang::ElpNone)
3605 spvType = builder.makeUintType(32);
3606 else
3607 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003608 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003609 case glslang::EbtInt:
3610 spvType = builder.makeIntType(32);
3611 break;
3612 case glslang::EbtUint:
3613 spvType = builder.makeUintType(32);
3614 break;
3615 case glslang::EbtFloat:
3616 spvType = builder.makeFloatType(32);
3617 break;
3618#ifndef GLSLANG_WEB
3619 case glslang::EbtDouble:
3620 spvType = builder.makeFloatType(64);
3621 break;
3622 case glslang::EbtFloat16:
3623 spvType = builder.makeFloatType(16);
3624 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003625 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003626 spvType = builder.makeIntType(8);
3627 break;
3628 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003629 spvType = builder.makeUintType(8);
3630 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003631 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003632 spvType = builder.makeIntType(16);
3633 break;
3634 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003635 spvType = builder.makeUintType(16);
3636 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003637 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003638 spvType = builder.makeIntType(64);
3639 break;
3640 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003641 spvType = builder.makeUintType(64);
3642 break;
John Kessenich426394d2015-07-23 10:22:48 -06003643 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003644 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003645 spvType = builder.makeUintType(32);
3646 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003647 case glslang::EbtAccStruct:
3648 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003649 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003650 case glslang::EbtRayQuery:
3651 spvType = builder.makeRayQueryType();
3652 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003653 case glslang::EbtReference:
3654 {
3655 // Make the forward pointer, then recurse to convert the structure type, then
3656 // patch up the forward pointer with a real pointer type.
3657 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3658 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3659 forwardPointers[type.getReferentType()] = forwardId;
3660 }
3661 spvType = forwardPointers[type.getReferentType()];
3662 if (!forwardReferenceOnly) {
3663 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3664 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3665 forwardPointers[type.getReferentType()],
3666 referentType);
3667 }
3668 }
3669 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003670#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003671 case glslang::EbtSampler:
3672 {
3673 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003674 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003675 spvType = builder.makeSamplerType();
3676 } else {
3677 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003678 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3679 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3680 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3681 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003682 // already has both image and sampler, make the combined type
3683 spvType = builder.makeSampledImageType(spvType);
3684 }
John Kessenich55e7d112015-11-15 21:33:39 -07003685 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003686 }
John Kessenich140f3df2015-06-26 16:58:36 -06003687 break;
3688 case glslang::EbtStruct:
3689 case glslang::EbtBlock:
3690 {
3691 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003692 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003693
3694 // Try to share structs for different layouts, but not yet for other
3695 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003696 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003697 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003698 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700
3701 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003702 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003703 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003704 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003705 }
3706 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003707 case glslang::EbtString:
3708 // no type used for OpString
3709 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003711 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003712 break;
3713 }
3714
3715 if (type.isMatrix())
3716 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3717 else {
3718 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3719 if (type.getVectorSize() > 1)
3720 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3721 }
3722
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003723 if (type.isCoopMat()) {
3724 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3725 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3726 if (type.getBasicType() == glslang::EbtFloat16)
3727 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003728 if (type.getBasicType() == glslang::EbtUint8 ||
3729 type.getBasicType() == glslang::EbtInt8) {
3730 builder.addCapability(spv::CapabilityInt8);
3731 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003732
3733 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3734 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3735 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3736
3737 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3738 }
3739
John Kessenich140f3df2015-06-26 16:58:36 -06003740 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003741 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3742
John Kessenichc9a80832015-09-12 12:17:44 -06003743 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003744 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003745 // We need to decorate array strides for types needing explicit layout, except blocks.
3746 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003747 // Use a dummy glslang type for querying internal strides of
3748 // arrays of arrays, but using just a one-dimensional array.
3749 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003750 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3751 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003752
3753 // Will compute the higher-order strides here, rather than making a whole
3754 // pile of types and doing repetitive recursion on their contents.
3755 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3756 }
John Kessenichf8842e52016-01-04 19:22:56 -07003757
3758 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003759 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003760 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003761 if (stride > 0)
3762 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003763 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003764 }
3765 } else {
3766 // single-dimensional array, and don't yet have stride
3767
John Kessenichf8842e52016-01-04 19:22:56 -07003768 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003769 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3770 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003771 }
John Kessenich31ed4832015-09-09 17:51:38 -06003772
John Kessenichead86222018-03-28 18:01:20 -06003773 // Do the outer dimension, which might not be known for a runtime-sized array.
3774 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3775 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003776 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003777 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003778#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003779 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003780 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003781 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3782 }
John Kessenichb9197c82019-08-11 07:41:45 -06003783#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003784 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003785 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003786 if (stride > 0)
3787 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003788 }
3789
3790 return spvType;
3791}
3792
John Kessenich0e737842017-03-24 18:38:16 -06003793// TODO: this functionality should exist at a higher level, in creating the AST
3794//
3795// Identify interface members that don't have their required extension turned on.
3796//
3797bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3798{
John Kessenicha28f7a72019-08-06 07:00:58 -06003799#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003800 auto& extensions = glslangIntermediate->getRequestedExtensions();
3801
Rex Xubcf291a2017-03-29 23:01:36 +08003802 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3803 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3804 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003805 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3806 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3807 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003808
3809 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3810 if (member.getFieldName() == "gl_ViewportMask" &&
3811 extensions.find("GL_NV_viewport_array2") == extensions.end())
3812 return true;
3813 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3814 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3815 return true;
3816 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3817 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3818 return true;
3819 }
3820#endif
John Kessenich0e737842017-03-24 18:38:16 -06003821
3822 return false;
3823};
3824
John Kessenich6090df02016-06-30 21:18:02 -06003825// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3826// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3827// Mutually recursive with convertGlslangToSpvType().
3828spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3829 const glslang::TTypeList* glslangMembers,
3830 glslang::TLayoutPacking explicitLayout,
3831 const glslang::TQualifier& qualifier)
3832{
3833 // Create a vector of struct types for SPIR-V to consume
3834 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003835 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3836 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003837 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003838 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3839 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3840 if (glslangMember.hiddenMember()) {
3841 ++memberDelta;
3842 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003843 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003844 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003845 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003846 if (filterMember(glslangMember)) {
3847 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003848 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003849 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003850 }
Roy05a5b532020-01-03 16:21:34 +08003851 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003852 }
John Kessenich6090df02016-06-30 21:18:02 -06003853 // modify just this child's view of the qualifier
3854 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3855 InheritQualifiers(memberQualifier, qualifier);
3856
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003857 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003858 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003859 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003860
3861 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003862 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3863 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003864
3865 // Make forward pointers for any pointer members, and create a list of members to
3866 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003867 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003868 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3869 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3870 }
3871 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003872 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3873 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003874 } else {
3875 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003876 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3877 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003878 }
John Kessenich6090df02016-06-30 21:18:02 -06003879 }
3880 }
3881
3882 // Make the SPIR-V type
3883 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003884 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003885 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3886
3887 // Decorate it
3888 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3889
John Kessenichd72f4882019-01-16 14:55:37 +07003890 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003891 auto it = deferredForwardPointers[i];
3892 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3893 }
3894
John Kessenich6090df02016-06-30 21:18:02 -06003895 return spvType;
3896}
3897
3898void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3899 const glslang::TTypeList* glslangMembers,
3900 glslang::TLayoutPacking explicitLayout,
3901 const glslang::TQualifier& qualifier,
3902 spv::Id spvType)
3903{
3904 // Name and decorate the non-hidden members
3905 int offset = -1;
3906 int locationOffset = 0; // for use within the members of this struct
3907 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3908 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3909 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003910 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003911 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003912 if (filterMember(glslangMember))
3913 continue;
3914 }
John Kessenich6090df02016-06-30 21:18:02 -06003915
3916 // modify just this child's view of the qualifier
3917 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3918 InheritQualifiers(memberQualifier, qualifier);
3919
3920 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003921 if (member < 0)
3922 continue;
3923
3924 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3925 builder.addMemberDecoration(spvType, member,
3926 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3927 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3928 // Add interpolation and auxiliary storage decorations only to
3929 // top-level members of Input and Output storage classes
3930 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3931 type.getQualifier().storage == glslang::EvqVaryingOut) {
3932 if (type.getBasicType() == glslang::EbtBlock ||
3933 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3934 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3935 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003936#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003937 addMeshNVDecoration(spvType, member, memberQualifier);
3938#endif
John Kessenich6090df02016-06-30 21:18:02 -06003939 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003940 }
3941 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003942
John Kessenichb9197c82019-08-11 07:41:45 -06003943#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003944 if (type.getBasicType() == glslang::EbtBlock &&
3945 qualifier.storage == glslang::EvqBuffer) {
3946 // Add memory decorations only to top-level members of shader storage block
3947 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003948 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003949 for (unsigned int i = 0; i < memory.size(); ++i)
3950 builder.addMemberDecoration(spvType, member, memory[i]);
3951 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003952
John Kessenichb9197c82019-08-11 07:41:45 -06003953#endif
John Kessenich6090df02016-06-30 21:18:02 -06003954
John Kessenich5d610ee2018-03-07 18:05:55 -07003955 // Location assignment was already completed correctly by the front end,
3956 // just track whether a member needs to be decorated.
3957 // Ignore member locations if the container is an array, as that's
3958 // ill-specified and decisions have been made to not allow this.
3959 if (! type.isArray() && memberQualifier.hasLocation())
3960 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003961
John Kessenich5d610ee2018-03-07 18:05:55 -07003962 if (qualifier.hasLocation()) // track for upcoming inheritance
3963 locationOffset += glslangIntermediate->computeTypeLocationSize(
3964 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003965
John Kessenich5d610ee2018-03-07 18:05:55 -07003966 // component, XFB, others
3967 if (glslangMember.getQualifier().hasComponent())
3968 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3969 glslangMember.getQualifier().layoutComponent);
3970 if (glslangMember.getQualifier().hasXfbOffset())
3971 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3972 glslangMember.getQualifier().layoutXfbOffset);
3973 else if (explicitLayout != glslang::ElpNone) {
3974 // figure out what to do with offset, which is accumulating
3975 int nextOffset;
3976 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3977 if (offset >= 0)
3978 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3979 offset = nextOffset;
3980 }
John Kessenich6090df02016-06-30 21:18:02 -06003981
John Kessenich5d610ee2018-03-07 18:05:55 -07003982 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3983 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3984 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003985
John Kessenich5d610ee2018-03-07 18:05:55 -07003986 // built-in variable decorations
3987 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3988 if (builtIn != spv::BuiltInMax)
3989 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003990
John Kessenichb9197c82019-08-11 07:41:45 -06003991#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003992 // nonuniform
3993 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3994
John Kessenichead86222018-03-28 18:01:20 -06003995 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3996 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3997 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3998 memberQualifier.semanticName);
3999 }
4000
John Kessenich5d610ee2018-03-07 18:05:55 -07004001 if (builtIn == spv::BuiltInLayer) {
4002 // SPV_NV_viewport_array2 extension
4003 if (glslangMember.getQualifier().layoutViewportRelative){
4004 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4005 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4006 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004007 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004008 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4009 builder.addMemberDecoration(spvType, member,
4010 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4011 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4012 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4013 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004014 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004015 }
4016 if (glslangMember.getQualifier().layoutPassthrough) {
4017 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4018 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4019 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4020 }
chaoc771d89f2017-01-13 01:10:53 -08004021#endif
John Kessenich6090df02016-06-30 21:18:02 -06004022 }
4023
4024 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004025 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4026 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004027}
4028
John Kessenich6c292d32016-02-15 20:58:50 -07004029// Turn the expression forming the array size into an id.
4030// This is not quite trivial, because of specialization constants.
4031// Sometimes, a raw constant is turned into an Id, and sometimes
4032// a specialization constant expression is.
4033spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4034{
4035 // First, see if this is sized with a node, meaning a specialization constant:
4036 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4037 if (specNode != nullptr) {
4038 builder.clearAccessChain();
4039 specNode->traverse(this);
4040 return accessChainLoad(specNode->getAsTyped()->getType());
4041 }
qining25262b32016-05-06 17:25:16 -04004042
John Kessenich6c292d32016-02-15 20:58:50 -07004043 // Otherwise, need a compile-time (front end) size, get it:
4044 int size = arraySizes.getDimSize(dim);
4045 assert(size > 0);
4046 return builder.makeUintConstant(size);
4047}
4048
John Kessenich103bef92016-02-08 21:38:15 -07004049// Wrap the builder's accessChainLoad to:
4050// - localize handling of RelaxedPrecision
4051// - use the SPIR-V inferred type instead of another conversion of the glslang type
4052// (avoids unnecessary work and possible type punning for structures)
4053// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004054spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4055{
John Kessenich103bef92016-02-08 21:38:15 -07004056 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004057
4058 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4059 coherentFlags |= TranslateCoherent(type);
4060
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004061 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004062 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004063
John Kessenich5611c6d2018-04-05 11:25:02 -06004064 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004065 TranslateNonUniformDecoration(type.getQualifier()),
4066 nominalTypeId,
4067 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4068 TranslateMemoryScope(coherentFlags),
4069 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004070
4071 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004072 if (type.getBasicType() == glslang::EbtBool) {
4073 if (builder.isScalarType(nominalTypeId)) {
4074 // Conversion for bool
4075 spv::Id boolType = builder.makeBoolType();
4076 if (nominalTypeId != boolType)
4077 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4078 } else if (builder.isVectorType(nominalTypeId)) {
4079 // Conversion for bvec
4080 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4081 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4082 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004083 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4084 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004085 }
4086 }
John Kessenich103bef92016-02-08 21:38:15 -07004087
4088 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004089}
4090
Rex Xu27253232016-02-23 17:51:09 +08004091// Wrap the builder's accessChainStore to:
4092// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004093//
4094// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004095void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4096{
4097 // Need to convert to abstract types when necessary
4098 if (type.getBasicType() == glslang::EbtBool) {
4099 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4100
4101 if (builder.isScalarType(nominalTypeId)) {
4102 // Conversion for bool
4103 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004104 if (nominalTypeId != boolType) {
4105 // keep these outside arguments, for determinant order-of-evaluation
4106 spv::Id one = builder.makeUintConstant(1);
4107 spv::Id zero = builder.makeUintConstant(0);
4108 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4109 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004110 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004111 } else if (builder.isVectorType(nominalTypeId)) {
4112 // Conversion for bvec
4113 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4114 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004115 if (nominalTypeId != bvecType) {
4116 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004117 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4118 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4119 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004120 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004121 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4122 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004123 }
4124 }
4125
Jeff Bolz36831c92018-09-05 10:11:41 -05004126 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4127 coherentFlags |= TranslateCoherent(type);
4128
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004129 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004130 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004131
Jeff Bolz36831c92018-09-05 10:11:41 -05004132 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004133 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4134 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004135 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004136}
4137
John Kessenich4bf71552016-09-02 11:20:21 -06004138// For storing when types match at the glslang level, but not might match at the
4139// SPIR-V level.
4140//
4141// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004142// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004143// as in a member-decorated way.
4144//
4145// NOTE: This function can handle any store request; if it's not special it
4146// simplifies to a simple OpStore.
4147//
4148// Implicitly uses the existing builder.accessChain as the storage target.
4149void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4150{
John Kessenichb3e24e42016-09-11 12:33:43 -06004151 // we only do the complex path here if it's an aggregate
4152 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004153 accessChainStore(type, rValue);
4154 return;
4155 }
4156
John Kessenichb3e24e42016-09-11 12:33:43 -06004157 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004158 spv::Id rType = builder.getTypeId(rValue);
4159 spv::Id lValue = builder.accessChainGetLValue();
4160 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4161 if (lType == rType) {
4162 accessChainStore(type, rValue);
4163 return;
4164 }
4165
John Kessenichb3e24e42016-09-11 12:33:43 -06004166 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004167 // where the two types were the same type in GLSL. This requires member
4168 // by member copy, recursively.
4169
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004170 // SPIR-V 1.4 added an instruction to do help do this.
4171 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4172 // However, bool in uniform space is changed to int, so
4173 // OpCopyLogical does not work for that.
4174 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4175 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4176 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4177 if (lBool == rBool) {
4178 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4179 accessChainStore(type, logicalCopy);
4180 return;
4181 }
4182 }
4183
John Kessenichb3e24e42016-09-11 12:33:43 -06004184 // If an array, copy element by element.
4185 if (type.isArray()) {
4186 glslang::TType glslangElementType(type, 0);
4187 spv::Id elementRType = builder.getContainedTypeId(rType);
4188 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4189 // get the source member
4190 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004191
John Kessenichb3e24e42016-09-11 12:33:43 -06004192 // set up the target storage
4193 builder.clearAccessChain();
4194 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004195 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4196 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004197
John Kessenichb3e24e42016-09-11 12:33:43 -06004198 // store the member
4199 multiTypeStore(glslangElementType, elementRValue);
4200 }
4201 } else {
4202 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004203
John Kessenichb3e24e42016-09-11 12:33:43 -06004204 // loop over structure members
4205 const glslang::TTypeList& members = *type.getStruct();
4206 for (int m = 0; m < (int)members.size(); ++m) {
4207 const glslang::TType& glslangMemberType = *members[m].type;
4208
4209 // get the source member
4210 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4211 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4212
4213 // set up the target storage
4214 builder.clearAccessChain();
4215 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004216 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4217 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004218
4219 // store the member
4220 multiTypeStore(glslangMemberType, memberRValue);
4221 }
John Kessenich4bf71552016-09-02 11:20:21 -06004222 }
4223}
4224
John Kessenichf85e8062015-12-19 13:57:10 -07004225// Decide whether or not this type should be
4226// decorated with offsets and strides, and if so
4227// whether std140 or std430 rules should be applied.
4228glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004229{
John Kessenichf85e8062015-12-19 13:57:10 -07004230 // has to be a block
4231 if (type.getBasicType() != glslang::EbtBlock)
4232 return glslang::ElpNone;
4233
Chao Chen3c366992018-09-19 11:41:59 -07004234 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004235 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004236 type.getQualifier().storage != glslang::EvqBuffer &&
4237 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004238 return glslang::ElpNone;
4239
4240 // return the layout to use
4241 switch (type.getQualifier().layoutPacking) {
4242 case glslang::ElpStd140:
4243 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004244 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004245 return type.getQualifier().layoutPacking;
4246 default:
4247 return glslang::ElpNone;
4248 }
John Kessenich31ed4832015-09-09 17:51:38 -06004249}
4250
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004251// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004252int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4253 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004254{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004255 int size;
John Kessenich49987892015-12-29 17:11:44 -07004256 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004257 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4258 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004259
4260 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004261}
4262
John Kessenich49987892015-12-29 17:11:44 -07004263// 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 -07004264// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004265int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4266 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004267{
John Kessenich49987892015-12-29 17:11:44 -07004268 glslang::TType elementType;
4269 elementType.shallowCopy(matrixType);
4270 elementType.clearArraySizes();
4271
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004272 int size;
John Kessenich49987892015-12-29 17:11:44 -07004273 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004274 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4275 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004276
4277 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004278}
4279
John Kessenich5e4b1242015-08-06 22:53:06 -06004280// Given a member type of a struct, realign the current offset for it, and compute
4281// the next (not yet aligned) offset for the next member, which will get aligned
4282// on the next call.
4283// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4284// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4285// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004286void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4287 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004288{
4289 // this will get a positive value when deemed necessary
4290 nextOffset = -1;
4291
John Kessenich5e4b1242015-08-06 22:53:06 -06004292 // override anything in currentOffset with user-set offset
4293 if (memberType.getQualifier().hasOffset())
4294 currentOffset = memberType.getQualifier().layoutOffset;
4295
4296 // It could be that current linker usage in glslang updated all the layoutOffset,
4297 // in which case the following code does not matter. But, that's not quite right
4298 // once cross-compilation unit GLSL validation is done, as the original user
4299 // settings are needed in layoutOffset, and then the following will come into play.
4300
John Kessenichf85e8062015-12-19 13:57:10 -07004301 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004302 if (! memberType.getQualifier().hasOffset())
4303 currentOffset = -1;
4304
4305 return;
4306 }
4307
John Kessenichf85e8062015-12-19 13:57:10 -07004308 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004309 if (currentOffset < 0)
4310 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004311
John Kessenich5e4b1242015-08-06 22:53:06 -06004312 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4313 // but possibly not yet correctly aligned.
4314
4315 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004316 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004317 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4318 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004319
4320 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004321 // TODO: make this consistent in early phases of code:
4322 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4323 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4324 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004325 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004326 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004327 int dummySize;
4328 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4329 if (componentAlignment <= 4)
4330 memberAlignment = componentAlignment;
4331 }
4332
4333 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004334 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004335
4336 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004337 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4338 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004339 glslang::RoundToPow2(currentOffset, 16);
4340
John Kessenich5e4b1242015-08-06 22:53:06 -06004341 nextOffset = currentOffset + memberSize;
4342}
4343
David Netoa901ffe2016-06-08 14:11:40 +01004344void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004345{
David Netoa901ffe2016-06-08 14:11:40 +01004346 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4347 switch (glslangBuiltIn)
4348 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004349 case glslang::EbvPointSize:
4350#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004351 case glslang::EbvClipDistance:
4352 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004353 case glslang::EbvViewportMaskNV:
4354 case glslang::EbvSecondaryPositionNV:
4355 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004356 case glslang::EbvPositionPerViewNV:
4357 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004358 case glslang::EbvTaskCountNV:
4359 case glslang::EbvPrimitiveCountNV:
4360 case glslang::EbvPrimitiveIndicesNV:
4361 case glslang::EbvClipDistancePerViewNV:
4362 case glslang::EbvCullDistancePerViewNV:
4363 case glslang::EbvLayerPerViewNV:
4364 case glslang::EbvMeshViewCountNV:
4365 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004366#endif
David Netoa901ffe2016-06-08 14:11:40 +01004367 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4368 // Alternately, we could just call this for any glslang built-in, since the
4369 // capability already guards against duplicates.
4370 TranslateBuiltInDecoration(glslangBuiltIn, false);
4371 break;
4372 default:
4373 // Capabilities were already generated when the struct was declared.
4374 break;
4375 }
John Kessenichebb50532016-05-16 19:22:05 -06004376}
4377
John Kessenich6fccb3c2016-09-19 16:01:41 -06004378bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004379{
John Kessenicheee9d532016-09-19 18:09:30 -06004380 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004381}
4382
John Kessenichd41993d2017-09-10 15:21:05 -06004383// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004384// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4385// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004386bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004387{
John Kessenich6a14f782017-12-04 02:48:10 -07004388 assert(qualifier == glslang::EvqIn ||
4389 qualifier == glslang::EvqOut ||
4390 qualifier == glslang::EvqInOut ||
4391 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004392 return qualifier != glslang::EvqConstReadOnly;
4393}
4394
4395// Is parameter pass-by-original?
4396bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4397 bool implicitThisParam)
4398{
4399 if (implicitThisParam) // implicit this
4400 return true;
4401 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004402 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004403 return paramType.containsOpaque() || // sampler, etc.
4404 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4405}
4406
John Kessenich140f3df2015-06-26 16:58:36 -06004407// Make all the functions, skeletally, without actually visiting their bodies.
4408void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4409{
John Kessenich8985fc92020-03-03 10:25:07 -07004410 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4411 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004412 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4413 if (paramPrecision != spv::NoPrecision)
4414 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004415 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004416 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004417 // Original and non-writable params pass the pointer directly and
4418 // use restrict/aliased, others are stored to a pointer in Function
4419 // memory and use RestrictPointer/AliasedPointer.
4420 if (originalParam(type.getQualifier().storage, type, false) ||
4421 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004422 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4423 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004424 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004425 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4426 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004427 }
4428 }
John Kessenichfad62972017-07-18 02:35:46 -06004429 };
4430
John Kessenich140f3df2015-06-26 16:58:36 -06004431 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4432 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004433 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004434 continue;
4435
4436 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004437 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004438 //
qining25262b32016-05-06 17:25:16 -04004439 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004440 // function. What it is an address of varies:
4441 //
John Kessenich4bf71552016-09-02 11:20:21 -06004442 // - "in" parameters not marked as "const" can be written to without modifying the calling
4443 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004444 //
4445 // - "const in" parameters can just be the r-value, as no writes need occur.
4446 //
John Kessenich4bf71552016-09-02 11:20:21 -06004447 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4448 // 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 -06004449
4450 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004451 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004452 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4453
John Kessenich155d3512019-08-08 23:29:20 -06004454#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004455 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4456 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004457#else
4458 bool implicitThis = false;
4459#endif
John Kessenich37789792017-03-21 23:56:40 -06004460
John Kessenichfad62972017-07-18 02:35:46 -06004461 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004462 for (int p = 0; p < (int)parameters.size(); ++p) {
4463 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4464 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004465 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004466 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004467 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004468 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4469 else
John Kessenich4bf71552016-09-02 11:20:21 -06004470 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004471 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004472 paramTypes.push_back(typeId);
4473 }
4474
4475 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004476 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4477 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004478 glslFunction->getName().c_str(), paramTypes,
4479 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004480 if (implicitThis)
4481 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004482
4483 // Track function to emit/call later
4484 functionMap[glslFunction->getName().c_str()] = function;
4485
4486 // Set the parameter id's
4487 for (int p = 0; p < (int)parameters.size(); ++p) {
4488 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4489 // give a name too
4490 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004491
4492 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004493 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004494 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004495 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004496 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004497 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004498 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004499 }
4500 }
4501}
4502
4503// Process all the initializers, while skipping the functions and link objects
4504void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4505{
4506 builder.setBuildPoint(shaderEntry->getLastBlock());
4507 for (int i = 0; i < (int)initializers.size(); ++i) {
4508 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004509 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4510 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004511
4512 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004513 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004514 initializer->traverse(this);
4515 }
4516 }
4517}
4518
4519// Process all the functions, while skipping initializers.
4520void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4521{
4522 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4523 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004524 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004525 node->traverse(this);
4526 }
4527}
4528
4529void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4530{
qining25262b32016-05-06 17:25:16 -04004531 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004532 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004533 currentFunction = functionMap[node->getName().c_str()];
4534 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004535 builder.setBuildPoint(functionBlock);
4536}
4537
John Kessenich8985fc92020-03-03 10:25:07 -07004538void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4539 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004540{
Rex Xufc618912015-09-09 16:42:49 +08004541 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004542
4543 glslang::TSampler sampler = {};
4544 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004545#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004546 bool f16ShadowCompare = false;
4547#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004548 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004549 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4550 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004551#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004552 f16ShadowCompare = sampler.shadow &&
4553 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004554#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004555 }
4556
John Kessenich140f3df2015-06-26 16:58:36 -06004557 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4558 builder.clearAccessChain();
4559 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004560
John Kessenicha28f7a72019-08-06 07:00:58 -06004561#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004562 // Special case l-value operands
4563 bool lvalue = false;
4564 switch (node.getOp()) {
4565 case glslang::EOpImageAtomicAdd:
4566 case glslang::EOpImageAtomicMin:
4567 case glslang::EOpImageAtomicMax:
4568 case glslang::EOpImageAtomicAnd:
4569 case glslang::EOpImageAtomicOr:
4570 case glslang::EOpImageAtomicXor:
4571 case glslang::EOpImageAtomicExchange:
4572 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004573 case glslang::EOpImageAtomicLoad:
4574 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004575 if (i == 0)
4576 lvalue = true;
4577 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004578 case glslang::EOpSparseImageLoad:
4579 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4580 lvalue = true;
4581 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004582 case glslang::EOpSparseTexture:
4583 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4584 lvalue = true;
4585 break;
4586 case glslang::EOpSparseTextureClamp:
4587 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4588 lvalue = true;
4589 break;
4590 case glslang::EOpSparseTextureLod:
4591 case glslang::EOpSparseTextureOffset:
4592 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4593 lvalue = true;
4594 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004595 case glslang::EOpSparseTextureFetch:
4596 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4597 lvalue = true;
4598 break;
4599 case glslang::EOpSparseTextureFetchOffset:
4600 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4601 lvalue = true;
4602 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004603 case glslang::EOpSparseTextureLodOffset:
4604 case glslang::EOpSparseTextureGrad:
4605 case glslang::EOpSparseTextureOffsetClamp:
4606 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4607 lvalue = true;
4608 break;
4609 case glslang::EOpSparseTextureGradOffset:
4610 case glslang::EOpSparseTextureGradClamp:
4611 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4612 lvalue = true;
4613 break;
4614 case glslang::EOpSparseTextureGradOffsetClamp:
4615 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4616 lvalue = true;
4617 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004618 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004619 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4620 lvalue = true;
4621 break;
4622 case glslang::EOpSparseTextureGatherOffset:
4623 case glslang::EOpSparseTextureGatherOffsets:
4624 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4625 lvalue = true;
4626 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004627 case glslang::EOpSparseTextureGatherLod:
4628 if (i == 3)
4629 lvalue = true;
4630 break;
4631 case glslang::EOpSparseTextureGatherLodOffset:
4632 case glslang::EOpSparseTextureGatherLodOffsets:
4633 if (i == 4)
4634 lvalue = true;
4635 break;
Rex Xu129799a2017-07-05 17:23:28 +08004636 case glslang::EOpSparseImageLoadLod:
4637 if (i == 3)
4638 lvalue = true;
4639 break;
Chao Chen3a137962018-09-19 11:41:27 -07004640 case glslang::EOpImageSampleFootprintNV:
4641 if (i == 4)
4642 lvalue = true;
4643 break;
4644 case glslang::EOpImageSampleFootprintClampNV:
4645 case glslang::EOpImageSampleFootprintLodNV:
4646 if (i == 5)
4647 lvalue = true;
4648 break;
4649 case glslang::EOpImageSampleFootprintGradNV:
4650 if (i == 6)
4651 lvalue = true;
4652 break;
4653 case glslang::EOpImageSampleFootprintGradClampNV:
4654 if (i == 7)
4655 lvalue = true;
4656 break;
Rex Xufc618912015-09-09 16:42:49 +08004657 default:
4658 break;
4659 }
4660
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004661 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004662 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004663 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4664 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4665 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004666#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004667 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004668 }
4669}
4670
John Kessenichfc51d282015-08-19 13:34:18 -06004671void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004672{
John Kessenichfc51d282015-08-19 13:34:18 -06004673 builder.clearAccessChain();
4674 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004675 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004676}
John Kessenich140f3df2015-06-26 16:58:36 -06004677
John Kessenichfc51d282015-08-19 13:34:18 -06004678spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4679{
John Kesseniche485c7a2017-05-31 18:50:53 -06004680 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004681 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004682
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004683 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004684
John Kessenichfc51d282015-08-19 13:34:18 -06004685 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004686
John Kessenichf43c7392019-03-31 10:51:57 -06004687 const glslang::TType &imageType = node->getAsAggregate()
4688 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4689 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004690 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004691#ifdef GLSLANG_WEB
4692 const bool f16ShadowCompare = false;
4693#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004694 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004695 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4696 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004697#endif
4698
John Kessenichf43c7392019-03-31 10:51:57 -06004699 const auto signExtensionMask = [&]() {
4700 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4701 if (sampler.type == glslang::EbtUint)
4702 return spv::ImageOperandsZeroExtendMask;
4703 else if (sampler.type == glslang::EbtInt)
4704 return spv::ImageOperandsSignExtendMask;
4705 }
4706 return spv::ImageOperandsMaskNone;
4707 };
4708
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004709 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4710
John Kessenichfc51d282015-08-19 13:34:18 -06004711 std::vector<spv::Id> arguments;
4712 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004713 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004714 else
4715 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004716 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004717
4718 spv::Builder::TextureParameters params = { };
4719 params.sampler = arguments[0];
4720
Rex Xu04db3f52015-09-16 11:44:02 +08004721 glslang::TCrackedTextureOp cracked;
4722 node->crackTexture(sampler, cracked);
4723
amhagan05506bb2017-06-13 16:53:02 -04004724 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004725
John Kessenichfc51d282015-08-19 13:34:18 -06004726 // Check for queries
4727 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004728 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4729 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004730 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004731
John Kessenichfc51d282015-08-19 13:34:18 -06004732 switch (node->getOp()) {
4733 case glslang::EOpImageQuerySize:
4734 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004735 if (arguments.size() > 1) {
4736 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004737 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004738 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004739 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004740#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004741 case glslang::EOpImageQuerySamples:
4742 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004743 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004744 case glslang::EOpTextureQueryLod:
4745 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004746 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004747 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004748 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004749 case glslang::EOpSparseTexelsResident:
4750 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004751#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004752 default:
4753 assert(0);
4754 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004755 }
John Kessenich140f3df2015-06-26 16:58:36 -06004756 }
4757
LoopDawg4425f242018-02-18 11:40:01 -07004758 int components = node->getType().getVectorSize();
4759
4760 if (node->getOp() == glslang::EOpTextureFetch) {
4761 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4762 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4763 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4764 // here around e.g. which ones return scalars or other types.
4765 components = 4;
4766 }
4767
4768 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4769
4770 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4771
Rex Xufc618912015-09-09 16:42:49 +08004772 // Check for image functions other than queries
4773 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004774 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004775 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004776 spv::IdImmediate image = { true, *(opIt++) };
4777 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004778
4779 // Handle subpass operations
4780 // TODO: GLSL should change to have the "MS" only on the type rather than the
4781 // built-in function.
4782 if (cracked.subpass) {
4783 // add on the (0,0) coordinate
4784 spv::Id zero = builder.makeIntConstant(0);
4785 std::vector<spv::Id> comps;
4786 comps.push_back(zero);
4787 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004788 spv::IdImmediate coord = { true,
4789 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4790 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004791 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4792 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004793 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004794 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4795 }
4796 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004797 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004798 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004799 spv::IdImmediate imageOperand = { true, *(opIt++) };
4800 operands.push_back(imageOperand);
4801 }
John Kessenich6c292d32016-02-15 20:58:50 -07004802 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004803 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4804 builder.setPrecision(result, precision);
4805 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004806 }
4807
John Kessenich149afc32018-08-14 13:31:43 -06004808 spv::IdImmediate coord = { true, *(opIt++) };
4809 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004810 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004811 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004812 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004813 mask = mask | spv::ImageOperandsSampleMask;
4814 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004815 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004816 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4817 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004818 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004819 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004820 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4821 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004822 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004823 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004824 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4825 operands.push_back(imageOperands);
4826 }
4827 if (mask & spv::ImageOperandsSampleMask) {
4828 spv::IdImmediate imageOperand = { true, *opIt++ };
4829 operands.push_back(imageOperand);
4830 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004831 if (mask & spv::ImageOperandsLodMask) {
4832 spv::IdImmediate imageOperand = { true, *opIt++ };
4833 operands.push_back(imageOperand);
4834 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004835 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004836 spv::IdImmediate imageOperand = { true,
4837 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004838 operands.push_back(imageOperand);
4839 }
4840
John Kessenich149afc32018-08-14 13:31:43 -06004841 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004842 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004843
John Kessenich149afc32018-08-14 13:31:43 -06004844 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004845 builder.setPrecision(result[0], precision);
4846
4847 // If needed, add a conversion constructor to the proper size.
4848 if (components != node->getType().getVectorSize())
4849 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4850
4851 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004852 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004853
Jeff Bolz36831c92018-09-05 10:11:41 -05004854 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004855 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004856 spv::IdImmediate texel = { true, *(opIt + 1) };
4857 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004858 } else {
4859 spv::IdImmediate texel = { true, *opIt };
4860 operands.push_back(texel);
4861 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004862
4863 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004864 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004865 mask = mask | spv::ImageOperandsSampleMask;
4866 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004867 if (cracked.lod) {
4868 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4869 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4870 mask = mask | spv::ImageOperandsLodMask;
4871 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004872 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4873 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004874 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004875 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004876 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4877 operands.push_back(imageOperands);
4878 }
4879 if (mask & spv::ImageOperandsSampleMask) {
4880 spv::IdImmediate imageOperand = { true, *opIt++ };
4881 operands.push_back(imageOperand);
4882 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004883 if (mask & spv::ImageOperandsLodMask) {
4884 spv::IdImmediate imageOperand = { true, *opIt++ };
4885 operands.push_back(imageOperand);
4886 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004887 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004888 spv::IdImmediate imageOperand = { true,
4889 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004890 operands.push_back(imageOperand);
4891 }
4892
John Kessenich56bab042015-09-16 10:54:31 -06004893 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004894 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004895 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004896 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004897 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4898 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004899 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004900 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004901 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4902
Jeff Bolz36831c92018-09-05 10:11:41 -05004903 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004904 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004905 mask = mask | spv::ImageOperandsSampleMask;
4906 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004907 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004908 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4909 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4910
Jeff Bolz36831c92018-09-05 10:11:41 -05004911 mask = mask | spv::ImageOperandsLodMask;
4912 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004913 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4914 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004915 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004916 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004917 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004918 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004919 }
4920 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004921 spv::IdImmediate imageOperand = { true, *opIt++ };
4922 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004923 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004924 if (mask & spv::ImageOperandsLodMask) {
4925 spv::IdImmediate imageOperand = { true, *opIt++ };
4926 operands.push_back(imageOperand);
4927 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004928 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004929 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4930 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004931 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004932 }
4933
4934 // Create the return type that was a special structure
4935 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004936 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004937 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4938 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4939
4940 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4941
4942 // Decode the return type
4943 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4944 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004945 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004946 // Process image atomic operations
4947
4948 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4949 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004950 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004951 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004952 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004953
Jeff Bolz36831c92018-09-05 10:11:41 -05004954 spv::Id resultTypeId;
4955 // imageAtomicStore has a void return type so base the pointer type on
4956 // the type of the value operand.
4957 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004958 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004959 } else {
4960 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4961 }
John Kessenich56bab042015-09-16 10:54:31 -06004962 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004963 if (imageType.getQualifier().nonUniform) {
4964 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4965 }
Rex Xufc618912015-09-09 16:42:49 +08004966
4967 std::vector<spv::Id> operands;
4968 operands.push_back(pointer);
4969 for (; opIt != arguments.end(); ++opIt)
4970 operands.push_back(*opIt);
4971
John Kessenich8985fc92020-03-03 10:25:07 -07004972 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4973 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004974 }
4975 }
4976
John Kessenicha28f7a72019-08-06 07:00:58 -06004977#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004978 // Check for fragment mask functions other than queries
4979 if (cracked.fragMask) {
4980 assert(sampler.ms);
4981
4982 auto opIt = arguments.begin();
4983 std::vector<spv::Id> operands;
4984
4985 // Extract the image if necessary
4986 if (builder.isSampledImage(params.sampler))
4987 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4988
4989 operands.push_back(params.sampler);
4990 ++opIt;
4991
4992 if (sampler.isSubpass()) {
4993 // add on the (0,0) coordinate
4994 spv::Id zero = builder.makeIntConstant(0);
4995 std::vector<spv::Id> comps;
4996 comps.push_back(zero);
4997 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07004998 operands.push_back(builder.makeCompositeConstant(
4999 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005000 }
5001
5002 for (; opIt != arguments.end(); ++opIt)
5003 operands.push_back(*opIt);
5004
5005 spv::Op fragMaskOp = spv::OpNop;
5006 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5007 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5008 else if (node->getOp() == glslang::EOpFragmentFetch)
5009 fragMaskOp = spv::OpFragmentFetchAMD;
5010
5011 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5012 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5013 return builder.createOp(fragMaskOp, resultType(), operands);
5014 }
5015#endif
5016
Rex Xufc618912015-09-09 16:42:49 +08005017 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005018 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005019 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005020 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005021
John Kessenichfc51d282015-08-19 13:34:18 -06005022 // check for bias argument
5023 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005024 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005025 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005026 if (cracked.gather)
5027 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005028
5029 if (f16ShadowCompare)
5030 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005031 if (cracked.offset)
5032 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005033 else if (cracked.offsets)
5034 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005035 if (cracked.grad)
5036 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005037 if (cracked.lodClamp)
5038 ++nonBiasArgCount;
5039 if (sparse)
5040 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005041 if (imageFootprint)
5042 //Following three extra arguments
5043 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5044 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005045 if ((int)arguments.size() > nonBiasArgCount)
5046 bias = true;
5047 }
5048
John Kessenicha5c33d62016-06-02 23:45:21 -06005049 // See if the sampler param should really be just the SPV image part
5050 if (cracked.fetch) {
5051 // a fetch needs to have the image extracted first
5052 if (builder.isSampledImage(params.sampler))
5053 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5054 }
5055
John Kessenicha28f7a72019-08-06 07:00:58 -06005056#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005057 if (cracked.gather) {
5058 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5059 if (bias || cracked.lod ||
5060 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5061 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005062 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005063 }
5064 }
5065#endif
5066
John Kessenichfc51d282015-08-19 13:34:18 -06005067 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005068
John Kessenichfc51d282015-08-19 13:34:18 -06005069 params.coords = arguments[1];
5070 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005071 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005072
5073 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005074 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005075 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005076 ++extraArgs;
5077 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005078 params.Dref = arguments[2];
5079 ++extraArgs;
5080 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005081 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005082 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005083 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005084 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005085 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005086 dRefComp = builder.getNumComponents(params.coords) - 1;
5087 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005088 params.Dref = builder.createCompositeExtract(params.coords,
5089 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005090 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005091
5092 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005093 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005094 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005095 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005096 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5097 !(glslangIntermediate->getStage() == EShLangCompute &&
5098 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005099 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5100 noImplicitLod = true;
5101 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005102
5103 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005104 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005105 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005106 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005107 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005108
5109 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005110 if (cracked.grad) {
5111 params.gradX = arguments[2 + extraArgs];
5112 params.gradY = arguments[3 + extraArgs];
5113 extraArgs += 2;
5114 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005115
5116 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005117 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005118 params.offset = arguments[2 + extraArgs];
5119 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005120 } else if (cracked.offsets) {
5121 params.offsets = arguments[2 + extraArgs];
5122 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005123 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005124
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005125#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005126 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005127 if (cracked.lodClamp) {
5128 params.lodClamp = arguments[2 + extraArgs];
5129 ++extraArgs;
5130 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005131 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005132 if (sparse) {
5133 params.texelOut = arguments[2 + extraArgs];
5134 ++extraArgs;
5135 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005136 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005137 if (cracked.gather && ! sampler.shadow) {
5138 // default component is 0, if missing, otherwise an argument
5139 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005140 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005141 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005142 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005143 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005144 }
Chao Chen3a137962018-09-19 11:41:27 -07005145 spv::Id resultStruct = spv::NoResult;
5146 if (imageFootprint) {
5147 //Following three extra arguments
5148 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5149 params.granularity = arguments[2 + extraArgs];
5150 params.coarse = arguments[3 + extraArgs];
5151 resultStruct = arguments[4 + extraArgs];
5152 extraArgs += 3;
5153 }
5154#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005155 // bias
5156 if (bias) {
5157 params.bias = arguments[2 + extraArgs];
5158 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005159 }
John Kessenichfc51d282015-08-19 13:34:18 -06005160
John Kessenicha28f7a72019-08-06 07:00:58 -06005161#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005162 if (imageFootprint) {
5163 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5164 builder.addCapability(spv::CapabilityImageFootprintNV);
5165
5166
5167 //resultStructType(OpenGL type) contains 5 elements:
5168 //struct gl_TextureFootprint2DNV {
5169 // uvec2 anchor;
5170 // uvec2 offset;
5171 // uvec2 mask;
5172 // uint lod;
5173 // uint granularity;
5174 //};
5175 //or
5176 //struct gl_TextureFootprint3DNV {
5177 // uvec3 anchor;
5178 // uvec3 offset;
5179 // uvec2 mask;
5180 // uint lod;
5181 // uint granularity;
5182 //};
5183 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5184 assert(builder.isStructType(resultStructType));
5185
5186 //resType (SPIR-V type) contains 6 elements:
5187 //Member 0 must be a Boolean type scalar(LOD),
5188 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5189 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5190 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5191 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5192 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5193 std::vector<spv::Id> members;
5194 members.push_back(resultType());
5195 for (int i = 0; i < 5; i++) {
5196 members.push_back(builder.getContainedTypeId(resultStructType, i));
5197 }
5198 spv::Id resType = builder.makeStructType(members, "ResType");
5199
5200 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005201 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5202 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005203
5204 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5205 for (int i = 0; i < 5; i++) {
5206 builder.clearAccessChain();
5207 builder.setAccessChainLValue(resultStruct);
5208
5209 //Accessing to a struct we created, no coherent flag is set
5210 spv::Builder::AccessChain::CoherentFlags flags;
5211 flags.clear();
5212
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005213 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005214 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5215 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005216 }
5217 return builder.createCompositeExtract(res, resultType(), 0);
5218 }
5219#endif
5220
John Kessenich65336482016-06-16 14:06:26 -06005221 // projective component (might not to move)
5222 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5223 // are divided by the last component of P."
5224 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5225 // unused components will appear after all used components."
5226 if (cracked.proj) {
5227 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5228 int projTargetComp;
5229 switch (sampler.dim) {
5230 case glslang::Esd1D: projTargetComp = 1; break;
5231 case glslang::Esd2D: projTargetComp = 2; break;
5232 case glslang::EsdRect: projTargetComp = 2; break;
5233 default: projTargetComp = projSourceComp; break;
5234 }
5235 // copy the projective coordinate if we have to
5236 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005237 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005238 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005239 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005240 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005241 }
5242 }
5243
John Kessenichf8d1d742019-10-21 06:55:11 -06005244#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005245 // nonprivate
5246 if (imageType.getQualifier().nonprivate) {
5247 params.nonprivate = true;
5248 }
5249
5250 // volatile
5251 if (imageType.getQualifier().volatil) {
5252 params.volatil = true;
5253 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005254#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005255
St0fFa1184dd2018-04-09 21:08:14 +02005256 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005257 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5258 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005259 );
LoopDawg4425f242018-02-18 11:40:01 -07005260
5261 if (components != node->getType().getVectorSize())
5262 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5263
5264 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005265}
5266
5267spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5268{
5269 // Grab the function's pointer from the previously created function
5270 spv::Function* function = functionMap[node->getName().c_str()];
5271 if (! function)
5272 return 0;
5273
5274 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5275 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5276
5277 // See comments in makeFunctions() for details about the semantics for parameter passing.
5278 //
5279 // These imply we need a four step process:
5280 // 1. Evaluate the arguments
5281 // 2. Allocate and make copies of in, out, and inout arguments
5282 // 3. Make the call
5283 // 4. Copy back the results
5284
John Kessenichd3ed90b2018-05-04 11:43:03 -06005285 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005286 std::vector<spv::Builder::AccessChain> lValues;
5287 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005288 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005289 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005290 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005291 // build l-value
5292 builder.clearAccessChain();
5293 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005294 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005295 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005296 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005297 // save l-value
5298 lValues.push_back(builder.getAccessChain());
5299 } else {
5300 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005301 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005302 }
5303 }
5304
5305 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5306 // copy the original into that space.
5307 //
5308 // Also, build up the list of actual arguments to pass in for the call
5309 int lValueCount = 0;
5310 int rValueCount = 0;
5311 std::vector<spv::Id> spvArgs;
5312 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5313 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005314 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005315 builder.setAccessChain(lValues[lValueCount]);
5316 arg = builder.accessChainGetLValue();
5317 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005318 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005319 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005320 arg = builder.createVariable(spv::StorageClassFunction,
5321 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005322 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5323 // need to copy the input into output space
5324 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005325 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005326 builder.clearAccessChain();
5327 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005328 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005329 }
5330 ++lValueCount;
5331 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005332 // process r-value, which involves a copy for a type mismatch
5333 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5334 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5335 builder.clearAccessChain();
5336 builder.setAccessChainLValue(argCopy);
5337 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5338 arg = builder.createLoad(argCopy);
5339 } else
5340 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005341 ++rValueCount;
5342 }
5343 spvArgs.push_back(arg);
5344 }
5345
5346 // 3. Make the call.
5347 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005348 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005349
5350 // 4. Copy back out an "out" arguments.
5351 lValueCount = 0;
5352 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005353 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005354 ++lValueCount;
5355 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005356 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5357 spv::Id copy = builder.createLoad(spvArgs[a]);
5358 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005359 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005360 }
5361 ++lValueCount;
5362 }
5363 }
5364
5365 return result;
5366}
5367
5368// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005369spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005370 spv::Id typeId, spv::Id left, spv::Id right,
5371 glslang::TBasicType typeProxy, bool reduceComparison)
5372{
John Kessenich66011cb2018-03-06 16:12:04 -07005373 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5374 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005375 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005376
5377 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005378 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005379 bool comparison = false;
5380
5381 switch (op) {
5382 case glslang::EOpAdd:
5383 case glslang::EOpAddAssign:
5384 if (isFloat)
5385 binOp = spv::OpFAdd;
5386 else
5387 binOp = spv::OpIAdd;
5388 break;
5389 case glslang::EOpSub:
5390 case glslang::EOpSubAssign:
5391 if (isFloat)
5392 binOp = spv::OpFSub;
5393 else
5394 binOp = spv::OpISub;
5395 break;
5396 case glslang::EOpMul:
5397 case glslang::EOpMulAssign:
5398 if (isFloat)
5399 binOp = spv::OpFMul;
5400 else
5401 binOp = spv::OpIMul;
5402 break;
5403 case glslang::EOpVectorTimesScalar:
5404 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005405 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005406 if (builder.isVector(right))
5407 std::swap(left, right);
5408 assert(builder.isScalar(right));
5409 needMatchingVectors = false;
5410 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005411 } else if (isFloat)
5412 binOp = spv::OpFMul;
5413 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005414 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005415 break;
5416 case glslang::EOpVectorTimesMatrix:
5417 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005418 binOp = spv::OpVectorTimesMatrix;
5419 break;
5420 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005421 binOp = spv::OpMatrixTimesVector;
5422 break;
5423 case glslang::EOpMatrixTimesScalar:
5424 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005425 binOp = spv::OpMatrixTimesScalar;
5426 break;
5427 case glslang::EOpMatrixTimesMatrix:
5428 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005429 binOp = spv::OpMatrixTimesMatrix;
5430 break;
5431 case glslang::EOpOuterProduct:
5432 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005433 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005434 break;
5435
5436 case glslang::EOpDiv:
5437 case glslang::EOpDivAssign:
5438 if (isFloat)
5439 binOp = spv::OpFDiv;
5440 else if (isUnsigned)
5441 binOp = spv::OpUDiv;
5442 else
5443 binOp = spv::OpSDiv;
5444 break;
5445 case glslang::EOpMod:
5446 case glslang::EOpModAssign:
5447 if (isFloat)
5448 binOp = spv::OpFMod;
5449 else if (isUnsigned)
5450 binOp = spv::OpUMod;
5451 else
5452 binOp = spv::OpSMod;
5453 break;
5454 case glslang::EOpRightShift:
5455 case glslang::EOpRightShiftAssign:
5456 if (isUnsigned)
5457 binOp = spv::OpShiftRightLogical;
5458 else
5459 binOp = spv::OpShiftRightArithmetic;
5460 break;
5461 case glslang::EOpLeftShift:
5462 case glslang::EOpLeftShiftAssign:
5463 binOp = spv::OpShiftLeftLogical;
5464 break;
5465 case glslang::EOpAnd:
5466 case glslang::EOpAndAssign:
5467 binOp = spv::OpBitwiseAnd;
5468 break;
5469 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005470 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 binOp = spv::OpLogicalAnd;
5472 break;
5473 case glslang::EOpInclusiveOr:
5474 case glslang::EOpInclusiveOrAssign:
5475 binOp = spv::OpBitwiseOr;
5476 break;
5477 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005478 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005479 binOp = spv::OpLogicalOr;
5480 break;
5481 case glslang::EOpExclusiveOr:
5482 case glslang::EOpExclusiveOrAssign:
5483 binOp = spv::OpBitwiseXor;
5484 break;
5485 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005486 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005487 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005488 break;
5489
Ian Romanickb3bd4022019-01-21 08:57:25 -08005490 case glslang::EOpAbsDifference:
5491 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5492 break;
5493
5494 case glslang::EOpAddSaturate:
5495 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5496 break;
5497
5498 case glslang::EOpSubSaturate:
5499 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5500 break;
5501
5502 case glslang::EOpAverage:
5503 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5504 break;
5505
5506 case glslang::EOpAverageRounded:
5507 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5508 break;
5509
5510 case glslang::EOpMul32x16:
5511 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5512 break;
5513
John Kessenich140f3df2015-06-26 16:58:36 -06005514 case glslang::EOpLessThan:
5515 case glslang::EOpGreaterThan:
5516 case glslang::EOpLessThanEqual:
5517 case glslang::EOpGreaterThanEqual:
5518 case glslang::EOpEqual:
5519 case glslang::EOpNotEqual:
5520 case glslang::EOpVectorEqual:
5521 case glslang::EOpVectorNotEqual:
5522 comparison = true;
5523 break;
5524 default:
5525 break;
5526 }
5527
John Kessenich7c1aa102015-10-15 13:29:11 -06005528 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005529 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005530 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005531 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5532 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005533 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005534
5535 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005536 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005537 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005538
qining25262b32016-05-06 17:25:16 -04005539 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005540 decorations.addNoContraction(builder, result);
5541 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005542 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005543 }
5544
5545 if (! comparison)
5546 return 0;
5547
John Kessenich7c1aa102015-10-15 13:29:11 -06005548 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005549
John Kessenich4583b612016-08-07 19:14:22 -06005550 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005551 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5552 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005553 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005554 return result;
5555 }
John Kessenich140f3df2015-06-26 16:58:36 -06005556
5557 switch (op) {
5558 case glslang::EOpLessThan:
5559 if (isFloat)
5560 binOp = spv::OpFOrdLessThan;
5561 else if (isUnsigned)
5562 binOp = spv::OpULessThan;
5563 else
5564 binOp = spv::OpSLessThan;
5565 break;
5566 case glslang::EOpGreaterThan:
5567 if (isFloat)
5568 binOp = spv::OpFOrdGreaterThan;
5569 else if (isUnsigned)
5570 binOp = spv::OpUGreaterThan;
5571 else
5572 binOp = spv::OpSGreaterThan;
5573 break;
5574 case glslang::EOpLessThanEqual:
5575 if (isFloat)
5576 binOp = spv::OpFOrdLessThanEqual;
5577 else if (isUnsigned)
5578 binOp = spv::OpULessThanEqual;
5579 else
5580 binOp = spv::OpSLessThanEqual;
5581 break;
5582 case glslang::EOpGreaterThanEqual:
5583 if (isFloat)
5584 binOp = spv::OpFOrdGreaterThanEqual;
5585 else if (isUnsigned)
5586 binOp = spv::OpUGreaterThanEqual;
5587 else
5588 binOp = spv::OpSGreaterThanEqual;
5589 break;
5590 case glslang::EOpEqual:
5591 case glslang::EOpVectorEqual:
5592 if (isFloat)
5593 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005594 else if (isBool)
5595 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005596 else
5597 binOp = spv::OpIEqual;
5598 break;
5599 case glslang::EOpNotEqual:
5600 case glslang::EOpVectorNotEqual:
5601 if (isFloat)
5602 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005603 else if (isBool)
5604 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005605 else
5606 binOp = spv::OpINotEqual;
5607 break;
5608 default:
5609 break;
5610 }
5611
qining25262b32016-05-06 17:25:16 -04005612 if (binOp != spv::OpNop) {
5613 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005614 decorations.addNoContraction(builder, result);
5615 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005616 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005617 }
John Kessenich140f3df2015-06-26 16:58:36 -06005618
5619 return 0;
5620}
5621
John Kessenich04bb8a02015-12-12 12:28:14 -07005622//
5623// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5624// These can be any of:
5625//
5626// matrix * scalar
5627// scalar * matrix
5628// matrix * matrix linear algebraic
5629// matrix * vector
5630// vector * matrix
5631// matrix * matrix componentwise
5632// matrix op matrix op in {+, -, /}
5633// matrix op scalar op in {+, -, /}
5634// scalar op matrix op in {+, -, /}
5635//
John Kessenichead86222018-03-28 18:01:20 -06005636spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5637 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005638{
5639 bool firstClass = true;
5640
5641 // First, handle first-class matrix operations (* and matrix/scalar)
5642 switch (op) {
5643 case spv::OpFDiv:
5644 if (builder.isMatrix(left) && builder.isScalar(right)) {
5645 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005646 spv::Id resultType = builder.getTypeId(right);
5647 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005648 op = spv::OpMatrixTimesScalar;
5649 } else
5650 firstClass = false;
5651 break;
5652 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005653 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005654 std::swap(left, right);
5655 assert(builder.isScalar(right));
5656 break;
5657 case spv::OpVectorTimesMatrix:
5658 assert(builder.isVector(left));
5659 assert(builder.isMatrix(right));
5660 break;
5661 case spv::OpMatrixTimesVector:
5662 assert(builder.isMatrix(left));
5663 assert(builder.isVector(right));
5664 break;
5665 case spv::OpMatrixTimesMatrix:
5666 assert(builder.isMatrix(left));
5667 assert(builder.isMatrix(right));
5668 break;
5669 default:
5670 firstClass = false;
5671 break;
5672 }
5673
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005674 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5675 firstClass = true;
5676
qining25262b32016-05-06 17:25:16 -04005677 if (firstClass) {
5678 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005679 decorations.addNoContraction(builder, result);
5680 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005681 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005682 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005683
LoopDawg592860c2016-06-09 08:57:35 -06005684 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005685 // The result type of all of them is the same type as the (a) matrix operand.
5686 // The algorithm is to:
5687 // - break the matrix(es) into vectors
5688 // - smear any scalar to a vector
5689 // - do vector operations
5690 // - make a matrix out the vector results
5691 switch (op) {
5692 case spv::OpFAdd:
5693 case spv::OpFSub:
5694 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005695 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005696 case spv::OpFMul:
5697 {
5698 // one time set up...
5699 bool leftMat = builder.isMatrix(left);
5700 bool rightMat = builder.isMatrix(right);
5701 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5702 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5703 spv::Id scalarType = builder.getScalarTypeId(typeId);
5704 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5705 std::vector<spv::Id> results;
5706 spv::Id smearVec = spv::NoResult;
5707 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005708 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005709 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005710 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005711
5712 // do each vector op
5713 for (unsigned int c = 0; c < numCols; ++c) {
5714 std::vector<unsigned int> indexes;
5715 indexes.push_back(c);
5716 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5717 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005718 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005719 decorations.addNoContraction(builder, result);
5720 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005721 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005722 }
5723
5724 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005725 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005726 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005727 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005728 }
5729 default:
5730 assert(0);
5731 return spv::NoResult;
5732 }
5733}
5734
John Kessenichead86222018-03-28 18:01:20 -06005735spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005736 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005737{
5738 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005739 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005740 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005741 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5742 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005743
5744 switch (op) {
5745 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005746 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005747 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005748 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005749 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005750 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005751 unaryOp = spv::OpSNegate;
5752 break;
5753
5754 case glslang::EOpLogicalNot:
5755 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005756 unaryOp = spv::OpLogicalNot;
5757 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005758 case glslang::EOpBitwiseNot:
5759 unaryOp = spv::OpNot;
5760 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005761
John Kessenich140f3df2015-06-26 16:58:36 -06005762 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005763 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005764 break;
5765 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005766 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005767 break;
5768 case glslang::EOpTranspose:
5769 unaryOp = spv::OpTranspose;
5770 break;
5771
5772 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005773 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005774 break;
5775 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005776 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005777 break;
5778 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005779 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005780 break;
5781 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005782 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005783 break;
5784 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005785 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005786 break;
5787 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005788 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005789 break;
5790 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005791 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005792 break;
5793 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005794 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005795 break;
5796
5797 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005798 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005799 break;
5800 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005801 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005802 break;
5803 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005804 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
5806 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005807 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005808 break;
5809 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005810 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005811 break;
5812 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005813 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005814 break;
5815
5816 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005817 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005818 break;
5819 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005820 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005821 break;
5822
5823 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005824 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005833 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005836 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005837 break;
5838 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005839 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005840 break;
5841
5842 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005843 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005844 break;
5845 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005846 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005847 break;
5848 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005849 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005850 break;
5851 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005852 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005853 break;
5854 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005855 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005856 break;
5857 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005858 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005859 break;
5860
5861 case glslang::EOpIsNan:
5862 unaryOp = spv::OpIsNan;
5863 break;
5864 case glslang::EOpIsInf:
5865 unaryOp = spv::OpIsInf;
5866 break;
LoopDawg592860c2016-06-09 08:57:35 -06005867 case glslang::EOpIsFinite:
5868 unaryOp = spv::OpIsFinite;
5869 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005870
Rex Xucbc426e2015-12-15 16:03:10 +08005871 case glslang::EOpFloatBitsToInt:
5872 case glslang::EOpFloatBitsToUint:
5873 case glslang::EOpIntBitsToFloat:
5874 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005875 case glslang::EOpDoubleBitsToInt64:
5876 case glslang::EOpDoubleBitsToUint64:
5877 case glslang::EOpInt64BitsToDouble:
5878 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005879 case glslang::EOpFloat16BitsToInt16:
5880 case glslang::EOpFloat16BitsToUint16:
5881 case glslang::EOpInt16BitsToFloat16:
5882 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005883 unaryOp = spv::OpBitcast;
5884 break;
5885
John Kessenich140f3df2015-06-26 16:58:36 -06005886 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005887 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005888 break;
5889 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005890 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005891 break;
5892 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005893 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005894 break;
5895 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005896 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005897 break;
5898 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005899 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005900 break;
5901 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005902 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005903 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005904#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005905 case glslang::EOpPackSnorm4x8:
5906 libCall = spv::GLSLstd450PackSnorm4x8;
5907 break;
5908 case glslang::EOpUnpackSnorm4x8:
5909 libCall = spv::GLSLstd450UnpackSnorm4x8;
5910 break;
5911 case glslang::EOpPackUnorm4x8:
5912 libCall = spv::GLSLstd450PackUnorm4x8;
5913 break;
5914 case glslang::EOpUnpackUnorm4x8:
5915 libCall = spv::GLSLstd450UnpackUnorm4x8;
5916 break;
5917 case glslang::EOpPackDouble2x32:
5918 libCall = spv::GLSLstd450PackDouble2x32;
5919 break;
5920 case glslang::EOpUnpackDouble2x32:
5921 libCall = spv::GLSLstd450UnpackDouble2x32;
5922 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005923#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005924
Rex Xu8ff43de2016-04-22 16:51:45 +08005925 case glslang::EOpPackInt2x32:
5926 case glslang::EOpUnpackInt2x32:
5927 case glslang::EOpPackUint2x32:
5928 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005929 case glslang::EOpPack16:
5930 case glslang::EOpPack32:
5931 case glslang::EOpPack64:
5932 case glslang::EOpUnpack32:
5933 case glslang::EOpUnpack16:
5934 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005935 case glslang::EOpPackInt2x16:
5936 case glslang::EOpUnpackInt2x16:
5937 case glslang::EOpPackUint2x16:
5938 case glslang::EOpUnpackUint2x16:
5939 case glslang::EOpPackInt4x16:
5940 case glslang::EOpUnpackInt4x16:
5941 case glslang::EOpPackUint4x16:
5942 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005943 case glslang::EOpPackFloat2x16:
5944 case glslang::EOpUnpackFloat2x16:
5945 unaryOp = spv::OpBitcast;
5946 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005947
John Kessenich140f3df2015-06-26 16:58:36 -06005948 case glslang::EOpDPdx:
5949 unaryOp = spv::OpDPdx;
5950 break;
5951 case glslang::EOpDPdy:
5952 unaryOp = spv::OpDPdy;
5953 break;
5954 case glslang::EOpFwidth:
5955 unaryOp = spv::OpFwidth;
5956 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005957
John Kessenich140f3df2015-06-26 16:58:36 -06005958 case glslang::EOpAny:
5959 unaryOp = spv::OpAny;
5960 break;
5961 case glslang::EOpAll:
5962 unaryOp = spv::OpAll;
5963 break;
5964
5965 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005966 if (isFloat)
5967 libCall = spv::GLSLstd450FAbs;
5968 else
5969 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005970 break;
5971 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005972 if (isFloat)
5973 libCall = spv::GLSLstd450FSign;
5974 else
5975 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005976 break;
5977
John Kessenicha28f7a72019-08-06 07:00:58 -06005978#ifndef GLSLANG_WEB
5979 case glslang::EOpDPdxFine:
5980 unaryOp = spv::OpDPdxFine;
5981 break;
5982 case glslang::EOpDPdyFine:
5983 unaryOp = spv::OpDPdyFine;
5984 break;
5985 case glslang::EOpFwidthFine:
5986 unaryOp = spv::OpFwidthFine;
5987 break;
5988 case glslang::EOpDPdxCoarse:
5989 unaryOp = spv::OpDPdxCoarse;
5990 break;
5991 case glslang::EOpDPdyCoarse:
5992 unaryOp = spv::OpDPdyCoarse;
5993 break;
5994 case glslang::EOpFwidthCoarse:
5995 unaryOp = spv::OpFwidthCoarse;
5996 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04005997 case glslang::EOpRayQueryProceed:
5998 unaryOp = spv::OpRayQueryProceedKHR;
5999 break;
6000 case glslang::EOpRayQueryGetRayTMin:
6001 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6002 break;
6003 case glslang::EOpRayQueryGetRayFlags:
6004 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6005 break;
6006 case glslang::EOpRayQueryGetWorldRayOrigin:
6007 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6008 break;
6009 case glslang::EOpRayQueryGetWorldRayDirection:
6010 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6011 break;
6012 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6013 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6014 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006015 case glslang::EOpInterpolateAtCentroid:
6016 if (typeProxy == glslang::EbtFloat16)
6017 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6018 libCall = spv::GLSLstd450InterpolateAtCentroid;
6019 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006020 case glslang::EOpAtomicCounterIncrement:
6021 case glslang::EOpAtomicCounterDecrement:
6022 case glslang::EOpAtomicCounter:
6023 {
6024 // Handle all of the atomics in one place, in createAtomicOperation()
6025 std::vector<spv::Id> operands;
6026 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006027 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006028 }
6029
John Kessenichfc51d282015-08-19 13:34:18 -06006030 case glslang::EOpBitFieldReverse:
6031 unaryOp = spv::OpBitReverse;
6032 break;
6033 case glslang::EOpBitCount:
6034 unaryOp = spv::OpBitCount;
6035 break;
6036 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006037 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006038 break;
6039 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006040 if (isUnsigned)
6041 libCall = spv::GLSLstd450FindUMsb;
6042 else
6043 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006044 break;
6045
Ian Romanickb3bd4022019-01-21 08:57:25 -08006046 case glslang::EOpCountLeadingZeros:
6047 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6048 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6049 unaryOp = spv::OpUCountLeadingZerosINTEL;
6050 break;
6051
6052 case glslang::EOpCountTrailingZeros:
6053 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6054 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6055 unaryOp = spv::OpUCountTrailingZerosINTEL;
6056 break;
6057
Rex Xu574ab042016-04-14 16:53:07 +08006058 case glslang::EOpBallot:
6059 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006060 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006061 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006062 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006063 case glslang::EOpMinInvocations:
6064 case glslang::EOpMaxInvocations:
6065 case glslang::EOpAddInvocations:
6066 case glslang::EOpMinInvocationsNonUniform:
6067 case glslang::EOpMaxInvocationsNonUniform:
6068 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006069 case glslang::EOpMinInvocationsInclusiveScan:
6070 case glslang::EOpMaxInvocationsInclusiveScan:
6071 case glslang::EOpAddInvocationsInclusiveScan:
6072 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6073 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6074 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6075 case glslang::EOpMinInvocationsExclusiveScan:
6076 case glslang::EOpMaxInvocationsExclusiveScan:
6077 case glslang::EOpAddInvocationsExclusiveScan:
6078 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6079 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6080 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006081 {
6082 std::vector<spv::Id> operands;
6083 operands.push_back(operand);
6084 return createInvocationsOperation(op, typeId, operands, typeProxy);
6085 }
John Kessenich66011cb2018-03-06 16:12:04 -07006086 case glslang::EOpSubgroupAll:
6087 case glslang::EOpSubgroupAny:
6088 case glslang::EOpSubgroupAllEqual:
6089 case glslang::EOpSubgroupBroadcastFirst:
6090 case glslang::EOpSubgroupBallot:
6091 case glslang::EOpSubgroupInverseBallot:
6092 case glslang::EOpSubgroupBallotBitCount:
6093 case glslang::EOpSubgroupBallotInclusiveBitCount:
6094 case glslang::EOpSubgroupBallotExclusiveBitCount:
6095 case glslang::EOpSubgroupBallotFindLSB:
6096 case glslang::EOpSubgroupBallotFindMSB:
6097 case glslang::EOpSubgroupAdd:
6098 case glslang::EOpSubgroupMul:
6099 case glslang::EOpSubgroupMin:
6100 case glslang::EOpSubgroupMax:
6101 case glslang::EOpSubgroupAnd:
6102 case glslang::EOpSubgroupOr:
6103 case glslang::EOpSubgroupXor:
6104 case glslang::EOpSubgroupInclusiveAdd:
6105 case glslang::EOpSubgroupInclusiveMul:
6106 case glslang::EOpSubgroupInclusiveMin:
6107 case glslang::EOpSubgroupInclusiveMax:
6108 case glslang::EOpSubgroupInclusiveAnd:
6109 case glslang::EOpSubgroupInclusiveOr:
6110 case glslang::EOpSubgroupInclusiveXor:
6111 case glslang::EOpSubgroupExclusiveAdd:
6112 case glslang::EOpSubgroupExclusiveMul:
6113 case glslang::EOpSubgroupExclusiveMin:
6114 case glslang::EOpSubgroupExclusiveMax:
6115 case glslang::EOpSubgroupExclusiveAnd:
6116 case glslang::EOpSubgroupExclusiveOr:
6117 case glslang::EOpSubgroupExclusiveXor:
6118 case glslang::EOpSubgroupQuadSwapHorizontal:
6119 case glslang::EOpSubgroupQuadSwapVertical:
6120 case glslang::EOpSubgroupQuadSwapDiagonal: {
6121 std::vector<spv::Id> operands;
6122 operands.push_back(operand);
6123 return createSubgroupOperation(op, typeId, operands, typeProxy);
6124 }
Rex Xu9d93a232016-05-05 12:30:44 +08006125 case glslang::EOpMbcnt:
6126 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6127 libCall = spv::MbcntAMD;
6128 break;
6129
6130 case glslang::EOpCubeFaceIndex:
6131 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6132 libCall = spv::CubeFaceIndexAMD;
6133 break;
6134
6135 case glslang::EOpCubeFaceCoord:
6136 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6137 libCall = spv::CubeFaceCoordAMD;
6138 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006139 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006140 unaryOp = spv::OpGroupNonUniformPartitionNV;
6141 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006142 case glslang::EOpConstructReference:
6143 unaryOp = spv::OpBitcast;
6144 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006145#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006146
6147 case glslang::EOpCopyObject:
6148 unaryOp = spv::OpCopyObject;
6149 break;
6150
John Kessenich140f3df2015-06-26 16:58:36 -06006151 default:
6152 return 0;
6153 }
6154
6155 spv::Id id;
6156 if (libCall >= 0) {
6157 std::vector<spv::Id> args;
6158 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006159 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006160 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006161 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006162 }
John Kessenich140f3df2015-06-26 16:58:36 -06006163
John Kessenichb9197c82019-08-11 07:41:45 -06006164 decorations.addNoContraction(builder, id);
6165 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006166 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006167}
6168
John Kessenich7a53f762016-01-20 11:19:27 -07006169// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006170spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6171 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006172{
6173 // Handle unary operations vector by vector.
6174 // The result type is the same type as the original type.
6175 // The algorithm is to:
6176 // - break the matrix into vectors
6177 // - apply the operation to each vector
6178 // - make a matrix out the vector results
6179
6180 // get the types sorted out
6181 int numCols = builder.getNumColumns(operand);
6182 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006183 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6184 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006185 std::vector<spv::Id> results;
6186
6187 // do each vector op
6188 for (int c = 0; c < numCols; ++c) {
6189 std::vector<unsigned int> indexes;
6190 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006191 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6192 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006193 decorations.addNoContraction(builder, destVec);
6194 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006195 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006196 }
6197
6198 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006199 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006200 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006201 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006202}
6203
John Kessenichad7645f2018-06-04 19:11:25 -06006204// For converting integers where both the bitwidth and the signedness could
6205// change, but only do the width change here. The caller is still responsible
6206// for the signedness conversion.
6207spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006208{
John Kessenichad7645f2018-06-04 19:11:25 -06006209 // Get the result type width, based on the type to convert to.
6210 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006211 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006212 case glslang::EOpConvInt16ToUint8:
6213 case glslang::EOpConvIntToUint8:
6214 case glslang::EOpConvInt64ToUint8:
6215 case glslang::EOpConvUint16ToInt8:
6216 case glslang::EOpConvUintToInt8:
6217 case glslang::EOpConvUint64ToInt8:
6218 width = 8;
6219 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006220 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006221 case glslang::EOpConvIntToUint16:
6222 case glslang::EOpConvInt64ToUint16:
6223 case glslang::EOpConvUint8ToInt16:
6224 case glslang::EOpConvUintToInt16:
6225 case glslang::EOpConvUint64ToInt16:
6226 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006227 break;
6228 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006229 case glslang::EOpConvInt16ToUint:
6230 case glslang::EOpConvInt64ToUint:
6231 case glslang::EOpConvUint8ToInt:
6232 case glslang::EOpConvUint16ToInt:
6233 case glslang::EOpConvUint64ToInt:
6234 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006235 break;
6236 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006237 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006238 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006239 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006240 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006241 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006242 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006243 break;
6244
6245 default:
6246 assert(false && "Default missing");
6247 break;
6248 }
6249
John Kessenichad7645f2018-06-04 19:11:25 -06006250 // Get the conversion operation and result type,
6251 // based on the target width, but the source type.
6252 spv::Id type = spv::NoType;
6253 spv::Op convOp = spv::OpNop;
6254 switch(op) {
6255 case glslang::EOpConvInt8ToUint16:
6256 case glslang::EOpConvInt8ToUint:
6257 case glslang::EOpConvInt8ToUint64:
6258 case glslang::EOpConvInt16ToUint8:
6259 case glslang::EOpConvInt16ToUint:
6260 case glslang::EOpConvInt16ToUint64:
6261 case glslang::EOpConvIntToUint8:
6262 case glslang::EOpConvIntToUint16:
6263 case glslang::EOpConvIntToUint64:
6264 case glslang::EOpConvInt64ToUint8:
6265 case glslang::EOpConvInt64ToUint16:
6266 case glslang::EOpConvInt64ToUint:
6267 convOp = spv::OpSConvert;
6268 type = builder.makeIntType(width);
6269 break;
6270 default:
6271 convOp = spv::OpUConvert;
6272 type = builder.makeUintType(width);
6273 break;
6274 }
6275
John Kessenich66011cb2018-03-06 16:12:04 -07006276 if (vectorSize > 0)
6277 type = builder.makeVectorType(type, vectorSize);
6278
John Kessenichad7645f2018-06-04 19:11:25 -06006279 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006280}
6281
John Kessenichead86222018-03-28 18:01:20 -06006282spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6283 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006284{
6285 spv::Op convOp = spv::OpNop;
6286 spv::Id zero = 0;
6287 spv::Id one = 0;
6288
6289 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6290
6291 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006292 case glslang::EOpConvIntToBool:
6293 case glslang::EOpConvUintToBool:
6294 zero = builder.makeUintConstant(0);
6295 zero = makeSmearedConstant(zero, vectorSize);
6296 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006297 case glslang::EOpConvFloatToBool:
6298 zero = builder.makeFloatConstant(0.0F);
6299 zero = makeSmearedConstant(zero, vectorSize);
6300 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006301 case glslang::EOpConvBoolToFloat:
6302 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006303 zero = builder.makeFloatConstant(0.0F);
6304 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006305 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006306
John Kessenich140f3df2015-06-26 16:58:36 -06006307 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006308 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006309#ifndef GLSLANG_WEB
6310 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006311 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006312 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006313 } else
6314#endif
6315 {
6316 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006317 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006318 }
Rex Xucabbb782017-03-24 13:41:14 +08006319
John Kessenich140f3df2015-06-26 16:58:36 -06006320 convOp = spv::OpSelect;
6321 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006322
John Kessenich140f3df2015-06-26 16:58:36 -06006323 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006324 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006325#ifndef GLSLANG_WEB
6326 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006327 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006328 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006329 } else
6330#endif
6331 {
6332 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006333 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006334 }
Rex Xucabbb782017-03-24 13:41:14 +08006335
John Kessenich140f3df2015-06-26 16:58:36 -06006336 convOp = spv::OpSelect;
6337 break;
6338
John Kessenich66011cb2018-03-06 16:12:04 -07006339 case glslang::EOpConvInt8ToFloat16:
6340 case glslang::EOpConvInt8ToFloat:
6341 case glslang::EOpConvInt8ToDouble:
6342 case glslang::EOpConvInt16ToFloat16:
6343 case glslang::EOpConvInt16ToFloat:
6344 case glslang::EOpConvInt16ToDouble:
6345 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006346 case glslang::EOpConvIntToFloat:
6347 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006348 case glslang::EOpConvInt64ToFloat:
6349 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006350 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006351 convOp = spv::OpConvertSToF;
6352 break;
6353
John Kessenich66011cb2018-03-06 16:12:04 -07006354 case glslang::EOpConvUint8ToFloat16:
6355 case glslang::EOpConvUint8ToFloat:
6356 case glslang::EOpConvUint8ToDouble:
6357 case glslang::EOpConvUint16ToFloat16:
6358 case glslang::EOpConvUint16ToFloat:
6359 case glslang::EOpConvUint16ToDouble:
6360 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006361 case glslang::EOpConvUintToFloat:
6362 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006363 case glslang::EOpConvUint64ToFloat:
6364 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006365 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006366 convOp = spv::OpConvertUToF;
6367 break;
6368
John Kessenich66011cb2018-03-06 16:12:04 -07006369 case glslang::EOpConvFloat16ToInt8:
6370 case glslang::EOpConvFloatToInt8:
6371 case glslang::EOpConvDoubleToInt8:
6372 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006373 case glslang::EOpConvFloatToInt16:
6374 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006375 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006376 case glslang::EOpConvFloatToInt:
6377 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006378 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006379 case glslang::EOpConvFloatToInt64:
6380 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006381 convOp = spv::OpConvertFToS;
6382 break;
6383
John Kessenich66011cb2018-03-06 16:12:04 -07006384 case glslang::EOpConvUint8ToInt8:
6385 case glslang::EOpConvInt8ToUint8:
6386 case glslang::EOpConvUint16ToInt16:
6387 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006388 case glslang::EOpConvUintToInt:
6389 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006390 case glslang::EOpConvUint64ToInt64:
6391 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006392 if (builder.isInSpecConstCodeGenMode()) {
6393 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006394#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006395 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6396 zero = builder.makeUint8Constant(0);
6397 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006398 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006399 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6400 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006401 } else
6402#endif
6403 {
Rex Xucabbb782017-03-24 13:41:14 +08006404 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006405 }
qining189b2032016-04-12 23:16:20 -04006406 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006407 // Use OpIAdd, instead of OpBitcast to do the conversion when
6408 // generating for OpSpecConstantOp instruction.
6409 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6410 }
6411 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006412 convOp = spv::OpBitcast;
6413 break;
6414
John Kessenich66011cb2018-03-06 16:12:04 -07006415 case glslang::EOpConvFloat16ToUint8:
6416 case glslang::EOpConvFloatToUint8:
6417 case glslang::EOpConvDoubleToUint8:
6418 case glslang::EOpConvFloat16ToUint16:
6419 case glslang::EOpConvFloatToUint16:
6420 case glslang::EOpConvDoubleToUint16:
6421 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006422 case glslang::EOpConvFloatToUint:
6423 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006424 case glslang::EOpConvFloatToUint64:
6425 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006426 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006427 convOp = spv::OpConvertFToU;
6428 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006429
John Kessenich39697cd2019-08-08 10:35:51 -06006430#ifndef GLSLANG_WEB
6431 case glslang::EOpConvInt8ToBool:
6432 case glslang::EOpConvUint8ToBool:
6433 zero = builder.makeUint8Constant(0);
6434 zero = makeSmearedConstant(zero, vectorSize);
6435 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6436 case glslang::EOpConvInt16ToBool:
6437 case glslang::EOpConvUint16ToBool:
6438 zero = builder.makeUint16Constant(0);
6439 zero = makeSmearedConstant(zero, vectorSize);
6440 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6441 case glslang::EOpConvInt64ToBool:
6442 case glslang::EOpConvUint64ToBool:
6443 zero = builder.makeUint64Constant(0);
6444 zero = makeSmearedConstant(zero, vectorSize);
6445 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6446 case glslang::EOpConvDoubleToBool:
6447 zero = builder.makeDoubleConstant(0.0);
6448 zero = makeSmearedConstant(zero, vectorSize);
6449 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6450 case glslang::EOpConvFloat16ToBool:
6451 zero = builder.makeFloat16Constant(0.0F);
6452 zero = makeSmearedConstant(zero, vectorSize);
6453 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6454 case glslang::EOpConvBoolToDouble:
6455 convOp = spv::OpSelect;
6456 zero = builder.makeDoubleConstant(0.0);
6457 one = builder.makeDoubleConstant(1.0);
6458 break;
6459 case glslang::EOpConvBoolToFloat16:
6460 convOp = spv::OpSelect;
6461 zero = builder.makeFloat16Constant(0.0F);
6462 one = builder.makeFloat16Constant(1.0F);
6463 break;
6464 case glslang::EOpConvBoolToInt8:
6465 zero = builder.makeInt8Constant(0);
6466 one = builder.makeInt8Constant(1);
6467 convOp = spv::OpSelect;
6468 break;
6469 case glslang::EOpConvBoolToUint8:
6470 zero = builder.makeUint8Constant(0);
6471 one = builder.makeUint8Constant(1);
6472 convOp = spv::OpSelect;
6473 break;
6474 case glslang::EOpConvBoolToInt16:
6475 zero = builder.makeInt16Constant(0);
6476 one = builder.makeInt16Constant(1);
6477 convOp = spv::OpSelect;
6478 break;
6479 case glslang::EOpConvBoolToUint16:
6480 zero = builder.makeUint16Constant(0);
6481 one = builder.makeUint16Constant(1);
6482 convOp = spv::OpSelect;
6483 break;
6484 case glslang::EOpConvDoubleToFloat:
6485 case glslang::EOpConvFloatToDouble:
6486 case glslang::EOpConvDoubleToFloat16:
6487 case glslang::EOpConvFloat16ToDouble:
6488 case glslang::EOpConvFloatToFloat16:
6489 case glslang::EOpConvFloat16ToFloat:
6490 convOp = spv::OpFConvert;
6491 if (builder.isMatrixType(destType))
6492 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6493 break;
6494
John Kessenich66011cb2018-03-06 16:12:04 -07006495 case glslang::EOpConvInt8ToInt16:
6496 case glslang::EOpConvInt8ToInt:
6497 case glslang::EOpConvInt8ToInt64:
6498 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006499 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006500 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006501 case glslang::EOpConvIntToInt8:
6502 case glslang::EOpConvIntToInt16:
6503 case glslang::EOpConvIntToInt64:
6504 case glslang::EOpConvInt64ToInt8:
6505 case glslang::EOpConvInt64ToInt16:
6506 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006507 convOp = spv::OpSConvert;
6508 break;
6509
John Kessenich66011cb2018-03-06 16:12:04 -07006510 case glslang::EOpConvUint8ToUint16:
6511 case glslang::EOpConvUint8ToUint:
6512 case glslang::EOpConvUint8ToUint64:
6513 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006514 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006515 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006516 case glslang::EOpConvUintToUint8:
6517 case glslang::EOpConvUintToUint16:
6518 case glslang::EOpConvUintToUint64:
6519 case glslang::EOpConvUint64ToUint8:
6520 case glslang::EOpConvUint64ToUint16:
6521 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006522 convOp = spv::OpUConvert;
6523 break;
6524
John Kessenich66011cb2018-03-06 16:12:04 -07006525 case glslang::EOpConvInt8ToUint16:
6526 case glslang::EOpConvInt8ToUint:
6527 case glslang::EOpConvInt8ToUint64:
6528 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006529 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006530 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006531 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006532 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006533 case glslang::EOpConvIntToUint64:
6534 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006535 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006536 case glslang::EOpConvInt64ToUint:
6537 case glslang::EOpConvUint8ToInt16:
6538 case glslang::EOpConvUint8ToInt:
6539 case glslang::EOpConvUint8ToInt64:
6540 case glslang::EOpConvUint16ToInt8:
6541 case glslang::EOpConvUint16ToInt:
6542 case glslang::EOpConvUint16ToInt64:
6543 case glslang::EOpConvUintToInt8:
6544 case glslang::EOpConvUintToInt16:
6545 case glslang::EOpConvUintToInt64:
6546 case glslang::EOpConvUint64ToInt8:
6547 case glslang::EOpConvUint64ToInt16:
6548 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006549 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006550 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006551
6552 if (builder.isInSpecConstCodeGenMode()) {
6553 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006554 switch(op) {
6555 case glslang::EOpConvInt16ToUint8:
6556 case glslang::EOpConvIntToUint8:
6557 case glslang::EOpConvInt64ToUint8:
6558 case glslang::EOpConvUint16ToInt8:
6559 case glslang::EOpConvUintToInt8:
6560 case glslang::EOpConvUint64ToInt8:
6561 zero = builder.makeUint8Constant(0);
6562 break;
6563 case glslang::EOpConvInt8ToUint16:
6564 case glslang::EOpConvIntToUint16:
6565 case glslang::EOpConvInt64ToUint16:
6566 case glslang::EOpConvUint8ToInt16:
6567 case glslang::EOpConvUintToInt16:
6568 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006569 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006570 break;
6571 case glslang::EOpConvInt8ToUint:
6572 case glslang::EOpConvInt16ToUint:
6573 case glslang::EOpConvInt64ToUint:
6574 case glslang::EOpConvUint8ToInt:
6575 case glslang::EOpConvUint16ToInt:
6576 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006577 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006578 break;
6579 case glslang::EOpConvInt8ToUint64:
6580 case glslang::EOpConvInt16ToUint64:
6581 case glslang::EOpConvIntToUint64:
6582 case glslang::EOpConvUint8ToInt64:
6583 case glslang::EOpConvUint16ToInt64:
6584 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006585 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006586 break;
6587 default:
6588 assert(false && "Default missing");
6589 break;
6590 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006591 zero = makeSmearedConstant(zero, vectorSize);
6592 // Use OpIAdd, instead of OpBitcast to do the conversion when
6593 // generating for OpSpecConstantOp instruction.
6594 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6595 }
6596 // For normal run-time conversion instruction, use OpBitcast.
6597 convOp = spv::OpBitcast;
6598 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006599 case glslang::EOpConvUint64ToPtr:
6600 convOp = spv::OpConvertUToPtr;
6601 break;
6602 case glslang::EOpConvPtrToUint64:
6603 convOp = spv::OpConvertPtrToU;
6604 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006605 case glslang::EOpConvPtrToUvec2:
6606 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006607 if (builder.isVector(operand))
6608 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6609 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006610 convOp = spv::OpBitcast;
6611 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006612#endif
6613
John Kessenich140f3df2015-06-26 16:58:36 -06006614 default:
6615 break;
6616 }
6617
6618 spv::Id result = 0;
6619 if (convOp == spv::OpNop)
6620 return result;
6621
6622 if (convOp == spv::OpSelect) {
6623 zero = makeSmearedConstant(zero, vectorSize);
6624 one = makeSmearedConstant(one, vectorSize);
6625 result = builder.createTriOp(convOp, destType, operand, one, zero);
6626 } else
6627 result = builder.createUnaryOp(convOp, destType, operand);
6628
John Kessenichead86222018-03-28 18:01:20 -06006629 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006630 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006631 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006632}
6633
6634spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6635{
6636 if (vectorSize == 0)
6637 return constant;
6638
6639 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6640 std::vector<spv::Id> components;
6641 for (int c = 0; c < vectorSize; ++c)
6642 components.push_back(constant);
6643 return builder.makeCompositeConstant(vectorTypeId, components);
6644}
6645
John Kessenich426394d2015-07-23 10:22:48 -06006646// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006647spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6648 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6649 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006650{
6651 spv::Op opCode = spv::OpNop;
6652
6653 switch (op) {
6654 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006655 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006656 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006657 opCode = spv::OpAtomicIAdd;
6658 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006659 case glslang::EOpAtomicCounterSubtract:
6660 opCode = spv::OpAtomicISub;
6661 break;
John Kessenich426394d2015-07-23 10:22:48 -06006662 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006663 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006664 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006665 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6666 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006667 break;
6668 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006669 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006670 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006671 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6672 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006673 break;
6674 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006675 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006676 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006677 opCode = spv::OpAtomicAnd;
6678 break;
6679 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006680 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006681 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006682 opCode = spv::OpAtomicOr;
6683 break;
6684 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006685 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006686 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006687 opCode = spv::OpAtomicXor;
6688 break;
6689 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006690 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006691 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006692 opCode = spv::OpAtomicExchange;
6693 break;
6694 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006695 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006696 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006697 opCode = spv::OpAtomicCompareExchange;
6698 break;
6699 case glslang::EOpAtomicCounterIncrement:
6700 opCode = spv::OpAtomicIIncrement;
6701 break;
6702 case glslang::EOpAtomicCounterDecrement:
6703 opCode = spv::OpAtomicIDecrement;
6704 break;
6705 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006706 case glslang::EOpImageAtomicLoad:
6707 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006708 opCode = spv::OpAtomicLoad;
6709 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006710 case glslang::EOpAtomicStore:
6711 case glslang::EOpImageAtomicStore:
6712 opCode = spv::OpAtomicStore;
6713 break;
John Kessenich426394d2015-07-23 10:22:48 -06006714 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006715 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006716 break;
6717 }
6718
Rex Xue8fe8b02017-09-26 15:42:56 +08006719 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6720 builder.addCapability(spv::CapabilityInt64Atomics);
6721
John Kessenich426394d2015-07-23 10:22:48 -06006722 // Sort out the operands
6723 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006724 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006725 // - compare-exchange swaps the value and comparator
6726 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006727 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006728 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6729 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6730 spv::Id scopeId;
6731 if (glslangIntermediate->usingVulkanMemoryModel()) {
6732 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6733 } else {
6734 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6735 }
6736 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006737 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6738 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006739 spv::MemorySemanticsVolatileMask :
6740 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006741 spv::Id semanticsId2 = semanticsId;
6742
6743 pointerId = operands[0];
6744 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6745 // no additional operands
6746 } else if (opCode == spv::OpAtomicCompareExchange) {
6747 compareId = operands[1];
6748 valueId = operands[2];
6749 if (operands.size() > 3) {
6750 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006751 semanticsId = builder.makeUintConstant(
6752 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6753 semanticsId2 = builder.makeUintConstant(
6754 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006755 }
6756 } else if (opCode == spv::OpAtomicLoad) {
6757 if (operands.size() > 1) {
6758 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006759 semanticsId = builder.makeUintConstant(
6760 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006761 }
6762 } else {
6763 // atomic store or RMW
6764 valueId = operands[1];
6765 if (operands.size() > 2) {
6766 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006767 semanticsId = builder.makeUintConstant
6768 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006769 }
Rex Xu04db3f52015-09-16 11:44:02 +08006770 }
John Kessenich426394d2015-07-23 10:22:48 -06006771
Jeff Bolz36831c92018-09-05 10:11:41 -05006772 // Check for capabilities
6773 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006774 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6775 spv::MemorySemanticsMakeVisibleKHRMask |
6776 spv::MemorySemanticsOutputMemoryKHRMask |
6777 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006778 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6779 }
John Kessenich426394d2015-07-23 10:22:48 -06006780
Jeff Bolz36831c92018-09-05 10:11:41 -05006781 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6782 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6783 }
John Kessenich48d6e792017-10-06 21:21:48 -06006784
Jeff Bolz36831c92018-09-05 10:11:41 -05006785 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6786 spvAtomicOperands.push_back(pointerId);
6787 spvAtomicOperands.push_back(scopeId);
6788 spvAtomicOperands.push_back(semanticsId);
6789 if (opCode == spv::OpAtomicCompareExchange) {
6790 spvAtomicOperands.push_back(semanticsId2);
6791 spvAtomicOperands.push_back(valueId);
6792 spvAtomicOperands.push_back(compareId);
6793 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6794 spvAtomicOperands.push_back(valueId);
6795 }
John Kessenich48d6e792017-10-06 21:21:48 -06006796
Jeff Bolz36831c92018-09-05 10:11:41 -05006797 if (opCode == spv::OpAtomicStore) {
6798 builder.createNoResultOp(opCode, spvAtomicOperands);
6799 return 0;
6800 } else {
6801 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6802
6803 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6804 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6805 if (op == glslang::EOpAtomicCounterDecrement)
6806 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6807
6808 return resultId;
6809 }
John Kessenich426394d2015-07-23 10:22:48 -06006810}
6811
John Kessenich91cef522016-05-05 16:45:40 -06006812// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006813spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6814 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006815{
John Kessenich66011cb2018-03-06 16:12:04 -07006816 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6817 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006818
Rex Xu51596642016-09-21 18:56:12 +08006819 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006820 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006821 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6822
chaocf200da82016-12-20 12:44:35 -08006823 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6824 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006825 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6826 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006827 } else if (op == glslang::EOpAnyInvocation ||
6828 op == glslang::EOpAllInvocations ||
6829 op == glslang::EOpAllInvocationsEqual) {
6830 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6831 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006832 } else {
6833 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006834 if (op == glslang::EOpMinInvocationsNonUniform ||
6835 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006836 op == glslang::EOpAddInvocationsNonUniform ||
6837 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6838 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6839 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6840 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6841 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6842 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006843 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006844
Rex Xu430ef402016-10-14 17:22:23 +08006845 switch (op) {
6846 case glslang::EOpMinInvocations:
6847 case glslang::EOpMaxInvocations:
6848 case glslang::EOpAddInvocations:
6849 case glslang::EOpMinInvocationsNonUniform:
6850 case glslang::EOpMaxInvocationsNonUniform:
6851 case glslang::EOpAddInvocationsNonUniform:
6852 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006853 break;
6854 case glslang::EOpMinInvocationsInclusiveScan:
6855 case glslang::EOpMaxInvocationsInclusiveScan:
6856 case glslang::EOpAddInvocationsInclusiveScan:
6857 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6858 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6859 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6860 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006861 break;
6862 case glslang::EOpMinInvocationsExclusiveScan:
6863 case glslang::EOpMaxInvocationsExclusiveScan:
6864 case glslang::EOpAddInvocationsExclusiveScan:
6865 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6866 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6867 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6868 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006869 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006870 default:
6871 break;
Rex Xu430ef402016-10-14 17:22:23 +08006872 }
John Kessenich149afc32018-08-14 13:31:43 -06006873 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6874 spvGroupOperands.push_back(scope);
6875 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006876 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006877 spvGroupOperands.push_back(groupOp);
6878 }
Rex Xu51596642016-09-21 18:56:12 +08006879 }
6880
John Kessenich149afc32018-08-14 13:31:43 -06006881 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6882 spv::IdImmediate op = { true, *opIt };
6883 spvGroupOperands.push_back(op);
6884 }
John Kessenich91cef522016-05-05 16:45:40 -06006885
6886 switch (op) {
6887 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006888 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006889 break;
John Kessenich91cef522016-05-05 16:45:40 -06006890 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006891 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006892 break;
John Kessenich91cef522016-05-05 16:45:40 -06006893 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006894 opCode = spv::OpSubgroupAllEqualKHR;
6895 break;
Rex Xu51596642016-09-21 18:56:12 +08006896 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006897 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006898 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006899 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006900 break;
6901 case glslang::EOpReadFirstInvocation:
6902 opCode = spv::OpSubgroupFirstInvocationKHR;
6903 break;
6904 case glslang::EOpBallot:
6905 {
6906 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6907 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6908 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6909 //
6910 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6911 //
6912 spv::Id uintType = builder.makeUintType(32);
6913 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6914 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6915
6916 std::vector<spv::Id> components;
6917 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6918 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6919
6920 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6921 return builder.createUnaryOp(spv::OpBitcast, typeId,
6922 builder.createCompositeConstruct(uvec2Type, components));
6923 }
6924
Rex Xu9d93a232016-05-05 12:30:44 +08006925 case glslang::EOpMinInvocations:
6926 case glslang::EOpMaxInvocations:
6927 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006928 case glslang::EOpMinInvocationsInclusiveScan:
6929 case glslang::EOpMaxInvocationsInclusiveScan:
6930 case glslang::EOpAddInvocationsInclusiveScan:
6931 case glslang::EOpMinInvocationsExclusiveScan:
6932 case glslang::EOpMaxInvocationsExclusiveScan:
6933 case glslang::EOpAddInvocationsExclusiveScan:
6934 if (op == glslang::EOpMinInvocations ||
6935 op == glslang::EOpMinInvocationsInclusiveScan ||
6936 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006937 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006938 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006939 else {
6940 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006941 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006942 else
Rex Xu51596642016-09-21 18:56:12 +08006943 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006944 }
Rex Xu430ef402016-10-14 17:22:23 +08006945 } else if (op == glslang::EOpMaxInvocations ||
6946 op == glslang::EOpMaxInvocationsInclusiveScan ||
6947 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006948 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006949 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006950 else {
6951 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006952 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006953 else
Rex Xu51596642016-09-21 18:56:12 +08006954 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006955 }
6956 } else {
6957 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006958 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006959 else
Rex Xu51596642016-09-21 18:56:12 +08006960 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006961 }
6962
Rex Xu2bbbe062016-08-23 15:41:05 +08006963 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006964 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006965
6966 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006967 case glslang::EOpMinInvocationsNonUniform:
6968 case glslang::EOpMaxInvocationsNonUniform:
6969 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006970 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6971 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6972 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6973 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6974 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6975 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6976 if (op == glslang::EOpMinInvocationsNonUniform ||
6977 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6978 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006979 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006980 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006981 else {
6982 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006983 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006984 else
Rex Xu51596642016-09-21 18:56:12 +08006985 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006986 }
6987 }
Rex Xu430ef402016-10-14 17:22:23 +08006988 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6989 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6990 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006991 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006992 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006993 else {
6994 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006995 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006996 else
Rex Xu51596642016-09-21 18:56:12 +08006997 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006998 }
6999 }
7000 else {
7001 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007002 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007003 else
Rex Xu51596642016-09-21 18:56:12 +08007004 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007005 }
7006
Rex Xu2bbbe062016-08-23 15:41:05 +08007007 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007008 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007009
7010 break;
John Kessenich91cef522016-05-05 16:45:40 -06007011 default:
7012 logger->missingFunctionality("invocation operation");
7013 return spv::NoResult;
7014 }
Rex Xu51596642016-09-21 18:56:12 +08007015
7016 assert(opCode != spv::OpNop);
7017 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007018}
7019
Rex Xu2bbbe062016-08-23 15:41:05 +08007020// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007021spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7022 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007023{
7024 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7025 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007026 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007027 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007028 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7029 op == spv::OpGroupSMinNonUniformAMD ||
7030 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7031 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007032 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7033
7034 // Handle group invocation operations scalar by scalar.
7035 // The result type is the same type as the original type.
7036 // The algorithm is to:
7037 // - break the vector into scalars
7038 // - apply the operation to each scalar
7039 // - make a vector out the scalar results
7040
7041 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007042 int numComponents = builder.getNumComponents(operands[0]);
7043 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007044 std::vector<spv::Id> results;
7045
7046 // do each scalar op
7047 for (int comp = 0; comp < numComponents; ++comp) {
7048 std::vector<unsigned int> indexes;
7049 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007050 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7051 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007052 if (op == spv::OpSubgroupReadInvocationKHR) {
7053 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007054 spv::IdImmediate operand = { true, operands[1] };
7055 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007056 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007057 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7058 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007059 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007060 spv::IdImmediate operand = { true, operands[1] };
7061 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007062 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007063 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7064 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007065 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007066 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007067 spvGroupOperands.push_back(scalar);
7068 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007069
Rex Xub7072052016-09-26 15:53:40 +08007070 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007071 }
7072
7073 // put the pieces together
7074 return builder.createCompositeConstruct(typeId, results);
7075}
Rex Xu2bbbe062016-08-23 15:41:05 +08007076
John Kessenich66011cb2018-03-06 16:12:04 -07007077// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007078spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7079 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007080{
7081 // Add the required capabilities.
7082 switch (op) {
7083 case glslang::EOpSubgroupElect:
7084 builder.addCapability(spv::CapabilityGroupNonUniform);
7085 break;
7086 case glslang::EOpSubgroupAll:
7087 case glslang::EOpSubgroupAny:
7088 case glslang::EOpSubgroupAllEqual:
7089 builder.addCapability(spv::CapabilityGroupNonUniform);
7090 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7091 break;
7092 case glslang::EOpSubgroupBroadcast:
7093 case glslang::EOpSubgroupBroadcastFirst:
7094 case glslang::EOpSubgroupBallot:
7095 case glslang::EOpSubgroupInverseBallot:
7096 case glslang::EOpSubgroupBallotBitExtract:
7097 case glslang::EOpSubgroupBallotBitCount:
7098 case glslang::EOpSubgroupBallotInclusiveBitCount:
7099 case glslang::EOpSubgroupBallotExclusiveBitCount:
7100 case glslang::EOpSubgroupBallotFindLSB:
7101 case glslang::EOpSubgroupBallotFindMSB:
7102 builder.addCapability(spv::CapabilityGroupNonUniform);
7103 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7104 break;
7105 case glslang::EOpSubgroupShuffle:
7106 case glslang::EOpSubgroupShuffleXor:
7107 builder.addCapability(spv::CapabilityGroupNonUniform);
7108 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7109 break;
7110 case glslang::EOpSubgroupShuffleUp:
7111 case glslang::EOpSubgroupShuffleDown:
7112 builder.addCapability(spv::CapabilityGroupNonUniform);
7113 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7114 break;
7115 case glslang::EOpSubgroupAdd:
7116 case glslang::EOpSubgroupMul:
7117 case glslang::EOpSubgroupMin:
7118 case glslang::EOpSubgroupMax:
7119 case glslang::EOpSubgroupAnd:
7120 case glslang::EOpSubgroupOr:
7121 case glslang::EOpSubgroupXor:
7122 case glslang::EOpSubgroupInclusiveAdd:
7123 case glslang::EOpSubgroupInclusiveMul:
7124 case glslang::EOpSubgroupInclusiveMin:
7125 case glslang::EOpSubgroupInclusiveMax:
7126 case glslang::EOpSubgroupInclusiveAnd:
7127 case glslang::EOpSubgroupInclusiveOr:
7128 case glslang::EOpSubgroupInclusiveXor:
7129 case glslang::EOpSubgroupExclusiveAdd:
7130 case glslang::EOpSubgroupExclusiveMul:
7131 case glslang::EOpSubgroupExclusiveMin:
7132 case glslang::EOpSubgroupExclusiveMax:
7133 case glslang::EOpSubgroupExclusiveAnd:
7134 case glslang::EOpSubgroupExclusiveOr:
7135 case glslang::EOpSubgroupExclusiveXor:
7136 builder.addCapability(spv::CapabilityGroupNonUniform);
7137 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7138 break;
7139 case glslang::EOpSubgroupClusteredAdd:
7140 case glslang::EOpSubgroupClusteredMul:
7141 case glslang::EOpSubgroupClusteredMin:
7142 case glslang::EOpSubgroupClusteredMax:
7143 case glslang::EOpSubgroupClusteredAnd:
7144 case glslang::EOpSubgroupClusteredOr:
7145 case glslang::EOpSubgroupClusteredXor:
7146 builder.addCapability(spv::CapabilityGroupNonUniform);
7147 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7148 break;
7149 case glslang::EOpSubgroupQuadBroadcast:
7150 case glslang::EOpSubgroupQuadSwapHorizontal:
7151 case glslang::EOpSubgroupQuadSwapVertical:
7152 case glslang::EOpSubgroupQuadSwapDiagonal:
7153 builder.addCapability(spv::CapabilityGroupNonUniform);
7154 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7155 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007156 case glslang::EOpSubgroupPartitionedAdd:
7157 case glslang::EOpSubgroupPartitionedMul:
7158 case glslang::EOpSubgroupPartitionedMin:
7159 case glslang::EOpSubgroupPartitionedMax:
7160 case glslang::EOpSubgroupPartitionedAnd:
7161 case glslang::EOpSubgroupPartitionedOr:
7162 case glslang::EOpSubgroupPartitionedXor:
7163 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7164 case glslang::EOpSubgroupPartitionedInclusiveMul:
7165 case glslang::EOpSubgroupPartitionedInclusiveMin:
7166 case glslang::EOpSubgroupPartitionedInclusiveMax:
7167 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7168 case glslang::EOpSubgroupPartitionedInclusiveOr:
7169 case glslang::EOpSubgroupPartitionedInclusiveXor:
7170 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7171 case glslang::EOpSubgroupPartitionedExclusiveMul:
7172 case glslang::EOpSubgroupPartitionedExclusiveMin:
7173 case glslang::EOpSubgroupPartitionedExclusiveMax:
7174 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7175 case glslang::EOpSubgroupPartitionedExclusiveOr:
7176 case glslang::EOpSubgroupPartitionedExclusiveXor:
7177 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7178 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7179 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007180 default: assert(0 && "Unhandled subgroup operation!");
7181 }
7182
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007183
7184 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7185 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007186 const bool isBool = typeProxy == glslang::EbtBool;
7187
7188 spv::Op opCode = spv::OpNop;
7189
7190 // Figure out which opcode to use.
7191 switch (op) {
7192 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7193 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7194 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7195 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7196 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7197 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7198 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7199 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7200 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7201 case glslang::EOpSubgroupBallotBitCount:
7202 case glslang::EOpSubgroupBallotInclusiveBitCount:
7203 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7204 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7205 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7206 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7207 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7208 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7209 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7210 case glslang::EOpSubgroupAdd:
7211 case glslang::EOpSubgroupInclusiveAdd:
7212 case glslang::EOpSubgroupExclusiveAdd:
7213 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007214 case glslang::EOpSubgroupPartitionedAdd:
7215 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7216 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007217 if (isFloat) {
7218 opCode = spv::OpGroupNonUniformFAdd;
7219 } else {
7220 opCode = spv::OpGroupNonUniformIAdd;
7221 }
7222 break;
7223 case glslang::EOpSubgroupMul:
7224 case glslang::EOpSubgroupInclusiveMul:
7225 case glslang::EOpSubgroupExclusiveMul:
7226 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007227 case glslang::EOpSubgroupPartitionedMul:
7228 case glslang::EOpSubgroupPartitionedInclusiveMul:
7229 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007230 if (isFloat) {
7231 opCode = spv::OpGroupNonUniformFMul;
7232 } else {
7233 opCode = spv::OpGroupNonUniformIMul;
7234 }
7235 break;
7236 case glslang::EOpSubgroupMin:
7237 case glslang::EOpSubgroupInclusiveMin:
7238 case glslang::EOpSubgroupExclusiveMin:
7239 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007240 case glslang::EOpSubgroupPartitionedMin:
7241 case glslang::EOpSubgroupPartitionedInclusiveMin:
7242 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007243 if (isFloat) {
7244 opCode = spv::OpGroupNonUniformFMin;
7245 } else if (isUnsigned) {
7246 opCode = spv::OpGroupNonUniformUMin;
7247 } else {
7248 opCode = spv::OpGroupNonUniformSMin;
7249 }
7250 break;
7251 case glslang::EOpSubgroupMax:
7252 case glslang::EOpSubgroupInclusiveMax:
7253 case glslang::EOpSubgroupExclusiveMax:
7254 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007255 case glslang::EOpSubgroupPartitionedMax:
7256 case glslang::EOpSubgroupPartitionedInclusiveMax:
7257 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007258 if (isFloat) {
7259 opCode = spv::OpGroupNonUniformFMax;
7260 } else if (isUnsigned) {
7261 opCode = spv::OpGroupNonUniformUMax;
7262 } else {
7263 opCode = spv::OpGroupNonUniformSMax;
7264 }
7265 break;
7266 case glslang::EOpSubgroupAnd:
7267 case glslang::EOpSubgroupInclusiveAnd:
7268 case glslang::EOpSubgroupExclusiveAnd:
7269 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007270 case glslang::EOpSubgroupPartitionedAnd:
7271 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7272 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007273 if (isBool) {
7274 opCode = spv::OpGroupNonUniformLogicalAnd;
7275 } else {
7276 opCode = spv::OpGroupNonUniformBitwiseAnd;
7277 }
7278 break;
7279 case glslang::EOpSubgroupOr:
7280 case glslang::EOpSubgroupInclusiveOr:
7281 case glslang::EOpSubgroupExclusiveOr:
7282 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007283 case glslang::EOpSubgroupPartitionedOr:
7284 case glslang::EOpSubgroupPartitionedInclusiveOr:
7285 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007286 if (isBool) {
7287 opCode = spv::OpGroupNonUniformLogicalOr;
7288 } else {
7289 opCode = spv::OpGroupNonUniformBitwiseOr;
7290 }
7291 break;
7292 case glslang::EOpSubgroupXor:
7293 case glslang::EOpSubgroupInclusiveXor:
7294 case glslang::EOpSubgroupExclusiveXor:
7295 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007296 case glslang::EOpSubgroupPartitionedXor:
7297 case glslang::EOpSubgroupPartitionedInclusiveXor:
7298 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007299 if (isBool) {
7300 opCode = spv::OpGroupNonUniformLogicalXor;
7301 } else {
7302 opCode = spv::OpGroupNonUniformBitwiseXor;
7303 }
7304 break;
7305 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7306 case glslang::EOpSubgroupQuadSwapHorizontal:
7307 case glslang::EOpSubgroupQuadSwapVertical:
7308 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7309 default: assert(0 && "Unhandled subgroup operation!");
7310 }
7311
John Kessenich149afc32018-08-14 13:31:43 -06007312 // get the right Group Operation
7313 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007314 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007315 default:
7316 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007317 case glslang::EOpSubgroupBallotBitCount:
7318 case glslang::EOpSubgroupAdd:
7319 case glslang::EOpSubgroupMul:
7320 case glslang::EOpSubgroupMin:
7321 case glslang::EOpSubgroupMax:
7322 case glslang::EOpSubgroupAnd:
7323 case glslang::EOpSubgroupOr:
7324 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007325 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007326 break;
7327 case glslang::EOpSubgroupBallotInclusiveBitCount:
7328 case glslang::EOpSubgroupInclusiveAdd:
7329 case glslang::EOpSubgroupInclusiveMul:
7330 case glslang::EOpSubgroupInclusiveMin:
7331 case glslang::EOpSubgroupInclusiveMax:
7332 case glslang::EOpSubgroupInclusiveAnd:
7333 case glslang::EOpSubgroupInclusiveOr:
7334 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007335 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007336 break;
7337 case glslang::EOpSubgroupBallotExclusiveBitCount:
7338 case glslang::EOpSubgroupExclusiveAdd:
7339 case glslang::EOpSubgroupExclusiveMul:
7340 case glslang::EOpSubgroupExclusiveMin:
7341 case glslang::EOpSubgroupExclusiveMax:
7342 case glslang::EOpSubgroupExclusiveAnd:
7343 case glslang::EOpSubgroupExclusiveOr:
7344 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007345 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007346 break;
7347 case glslang::EOpSubgroupClusteredAdd:
7348 case glslang::EOpSubgroupClusteredMul:
7349 case glslang::EOpSubgroupClusteredMin:
7350 case glslang::EOpSubgroupClusteredMax:
7351 case glslang::EOpSubgroupClusteredAnd:
7352 case glslang::EOpSubgroupClusteredOr:
7353 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007354 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007355 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007356 case glslang::EOpSubgroupPartitionedAdd:
7357 case glslang::EOpSubgroupPartitionedMul:
7358 case glslang::EOpSubgroupPartitionedMin:
7359 case glslang::EOpSubgroupPartitionedMax:
7360 case glslang::EOpSubgroupPartitionedAnd:
7361 case glslang::EOpSubgroupPartitionedOr:
7362 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007363 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007364 break;
7365 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7366 case glslang::EOpSubgroupPartitionedInclusiveMul:
7367 case glslang::EOpSubgroupPartitionedInclusiveMin:
7368 case glslang::EOpSubgroupPartitionedInclusiveMax:
7369 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7370 case glslang::EOpSubgroupPartitionedInclusiveOr:
7371 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007372 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007373 break;
7374 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7375 case glslang::EOpSubgroupPartitionedExclusiveMul:
7376 case glslang::EOpSubgroupPartitionedExclusiveMin:
7377 case glslang::EOpSubgroupPartitionedExclusiveMax:
7378 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7379 case glslang::EOpSubgroupPartitionedExclusiveOr:
7380 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007381 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007382 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007383 }
7384
John Kessenich149afc32018-08-14 13:31:43 -06007385 // build the instruction
7386 std::vector<spv::IdImmediate> spvGroupOperands;
7387
7388 // Every operation begins with the Execution Scope operand.
7389 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7390 spvGroupOperands.push_back(executionScope);
7391
7392 // Next, for all operations that use a Group Operation, push that as an operand.
7393 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007394 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007395 spvGroupOperands.push_back(groupOperand);
7396 }
7397
John Kessenich66011cb2018-03-06 16:12:04 -07007398 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007399 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7400 spv::IdImmediate operand = { true, *opIt };
7401 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007402 }
7403
7404 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007405 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007406 switch (op) {
7407 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007408 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7409 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7410 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7411 }
7412 if (directionId != spv::NoResult) {
7413 spv::IdImmediate direction = { true, directionId };
7414 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007415 }
7416
7417 return builder.createOp(opCode, typeId, spvGroupOperands);
7418}
7419
John Kessenich8985fc92020-03-03 10:25:07 -07007420spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7421 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007422{
John Kessenich66011cb2018-03-06 16:12:04 -07007423 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7424 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007425
John Kessenich140f3df2015-06-26 16:58:36 -06007426 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007427 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007428 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007429 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007430 spv::Id typeId0 = 0;
7431 if (consumedOperands > 0)
7432 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007433 spv::Id typeId1 = 0;
7434 if (consumedOperands > 1)
7435 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007436 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007437
7438 switch (op) {
7439 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007440 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007441 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007442 else if (isUnsigned)
7443 libCall = spv::GLSLstd450UMin;
7444 else
7445 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007446 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007447 break;
7448 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007449 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007450 break;
7451 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007452 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007453 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007454 else if (isUnsigned)
7455 libCall = spv::GLSLstd450UMax;
7456 else
7457 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007458 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007459 break;
7460 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007461 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007462 break;
7463 case glslang::EOpDot:
7464 opCode = spv::OpDot;
7465 break;
7466 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007467 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007468 break;
7469
7470 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007471 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007472 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007473 else if (isUnsigned)
7474 libCall = spv::GLSLstd450UClamp;
7475 else
7476 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007477 builder.promoteScalar(precision, operands.front(), operands[1]);
7478 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007479 break;
7480 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007481 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7482 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007483 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007484 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007485 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007486 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007487 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007488 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007489 break;
7490 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007491 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007492 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007493 break;
7494 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007495 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007496 builder.promoteScalar(precision, operands[0], operands[2]);
7497 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007498 break;
7499
7500 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007501 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007502 break;
7503 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007504 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007505 break;
7506 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007507 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007508 break;
7509 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007510 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007511 break;
7512 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007513 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007514 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007515 case glslang::EOpBarrier:
7516 {
7517 // This is for the extended controlBarrier function, with four operands.
7518 // The unextended barrier() goes through createNoArgOperation.
7519 assert(operands.size() == 4);
7520 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7521 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7522 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007523 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7524 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007525 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7526 spv::MemorySemanticsMakeVisibleKHRMask |
7527 spv::MemorySemanticsOutputMemoryKHRMask |
7528 spv::MemorySemanticsVolatileMask)) {
7529 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7530 }
John Kessenich8985fc92020-03-03 10:25:07 -07007531 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7532 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007533 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7534 }
7535 return 0;
7536 }
7537 break;
7538 case glslang::EOpMemoryBarrier:
7539 {
7540 // This is for the extended memoryBarrier function, with three operands.
7541 // The unextended memoryBarrier() goes through createNoArgOperation.
7542 assert(operands.size() == 3);
7543 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7544 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7545 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7546 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7547 spv::MemorySemanticsMakeVisibleKHRMask |
7548 spv::MemorySemanticsOutputMemoryKHRMask |
7549 spv::MemorySemanticsVolatileMask)) {
7550 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7551 }
7552 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7553 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7554 }
7555 return 0;
7556 }
7557 break;
7558
John Kessenicha28f7a72019-08-06 07:00:58 -06007559#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007560 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007561 if (typeProxy == glslang::EbtFloat16)
7562 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007563 libCall = spv::GLSLstd450InterpolateAtSample;
7564 break;
7565 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007566 if (typeProxy == glslang::EbtFloat16)
7567 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007568 libCall = spv::GLSLstd450InterpolateAtOffset;
7569 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007570 case glslang::EOpAddCarry:
7571 opCode = spv::OpIAddCarry;
7572 typeId = builder.makeStructResultType(typeId0, typeId0);
7573 consumedOperands = 2;
7574 break;
7575 case glslang::EOpSubBorrow:
7576 opCode = spv::OpISubBorrow;
7577 typeId = builder.makeStructResultType(typeId0, typeId0);
7578 consumedOperands = 2;
7579 break;
7580 case glslang::EOpUMulExtended:
7581 opCode = spv::OpUMulExtended;
7582 typeId = builder.makeStructResultType(typeId0, typeId0);
7583 consumedOperands = 2;
7584 break;
7585 case glslang::EOpIMulExtended:
7586 opCode = spv::OpSMulExtended;
7587 typeId = builder.makeStructResultType(typeId0, typeId0);
7588 consumedOperands = 2;
7589 break;
7590 case glslang::EOpBitfieldExtract:
7591 if (isUnsigned)
7592 opCode = spv::OpBitFieldUExtract;
7593 else
7594 opCode = spv::OpBitFieldSExtract;
7595 break;
7596 case glslang::EOpBitfieldInsert:
7597 opCode = spv::OpBitFieldInsert;
7598 break;
7599
7600 case glslang::EOpFma:
7601 libCall = spv::GLSLstd450Fma;
7602 break;
7603 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007604 {
7605 libCall = spv::GLSLstd450FrexpStruct;
7606 assert(builder.isPointerType(typeId1));
7607 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007608 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007609 if (width == 16)
7610 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7611 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007612 if (builder.getNumComponents(operands[0]) == 1)
7613 frexpIntType = builder.makeIntegerType(width, true);
7614 else
John Kessenich8985fc92020-03-03 10:25:07 -07007615 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7616 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007617 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7618 consumedOperands = 1;
7619 }
John Kessenich55e7d112015-11-15 21:33:39 -07007620 break;
7621 case glslang::EOpLdexp:
7622 libCall = spv::GLSLstd450Ldexp;
7623 break;
7624
Rex Xu574ab042016-04-14 16:53:07 +08007625 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007626 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007627
John Kessenich66011cb2018-03-06 16:12:04 -07007628 case glslang::EOpSubgroupBroadcast:
7629 case glslang::EOpSubgroupBallotBitExtract:
7630 case glslang::EOpSubgroupShuffle:
7631 case glslang::EOpSubgroupShuffleXor:
7632 case glslang::EOpSubgroupShuffleUp:
7633 case glslang::EOpSubgroupShuffleDown:
7634 case glslang::EOpSubgroupClusteredAdd:
7635 case glslang::EOpSubgroupClusteredMul:
7636 case glslang::EOpSubgroupClusteredMin:
7637 case glslang::EOpSubgroupClusteredMax:
7638 case glslang::EOpSubgroupClusteredAnd:
7639 case glslang::EOpSubgroupClusteredOr:
7640 case glslang::EOpSubgroupClusteredXor:
7641 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007642 case glslang::EOpSubgroupPartitionedAdd:
7643 case glslang::EOpSubgroupPartitionedMul:
7644 case glslang::EOpSubgroupPartitionedMin:
7645 case glslang::EOpSubgroupPartitionedMax:
7646 case glslang::EOpSubgroupPartitionedAnd:
7647 case glslang::EOpSubgroupPartitionedOr:
7648 case glslang::EOpSubgroupPartitionedXor:
7649 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7650 case glslang::EOpSubgroupPartitionedInclusiveMul:
7651 case glslang::EOpSubgroupPartitionedInclusiveMin:
7652 case glslang::EOpSubgroupPartitionedInclusiveMax:
7653 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7654 case glslang::EOpSubgroupPartitionedInclusiveOr:
7655 case glslang::EOpSubgroupPartitionedInclusiveXor:
7656 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7657 case glslang::EOpSubgroupPartitionedExclusiveMul:
7658 case glslang::EOpSubgroupPartitionedExclusiveMin:
7659 case glslang::EOpSubgroupPartitionedExclusiveMax:
7660 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7661 case glslang::EOpSubgroupPartitionedExclusiveOr:
7662 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007663 return createSubgroupOperation(op, typeId, operands, typeProxy);
7664
Rex Xu9d93a232016-05-05 12:30:44 +08007665 case glslang::EOpSwizzleInvocations:
7666 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7667 libCall = spv::SwizzleInvocationsAMD;
7668 break;
7669 case glslang::EOpSwizzleInvocationsMasked:
7670 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7671 libCall = spv::SwizzleInvocationsMaskedAMD;
7672 break;
7673 case glslang::EOpWriteInvocation:
7674 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7675 libCall = spv::WriteInvocationAMD;
7676 break;
7677
7678 case glslang::EOpMin3:
7679 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7680 if (isFloat)
7681 libCall = spv::FMin3AMD;
7682 else {
7683 if (isUnsigned)
7684 libCall = spv::UMin3AMD;
7685 else
7686 libCall = spv::SMin3AMD;
7687 }
7688 break;
7689 case glslang::EOpMax3:
7690 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7691 if (isFloat)
7692 libCall = spv::FMax3AMD;
7693 else {
7694 if (isUnsigned)
7695 libCall = spv::UMax3AMD;
7696 else
7697 libCall = spv::SMax3AMD;
7698 }
7699 break;
7700 case glslang::EOpMid3:
7701 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7702 if (isFloat)
7703 libCall = spv::FMid3AMD;
7704 else {
7705 if (isUnsigned)
7706 libCall = spv::UMid3AMD;
7707 else
7708 libCall = spv::SMid3AMD;
7709 }
7710 break;
7711
7712 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007713 if (typeProxy == glslang::EbtFloat16)
7714 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007715 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7716 libCall = spv::InterpolateAtVertexAMD;
7717 break;
Chao Chen3c366992018-09-19 11:41:59 -07007718
Daniel Kochdb32b242020-03-17 20:42:47 -04007719 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007720 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007721 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007722 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007723 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007724 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007725 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007726 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007727 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007728 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007729
7730 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007731 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7732 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007733 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007734 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7735 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007736 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007737 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7738 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007739 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007740 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7741 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007742 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007743 typeId = builder.makeBoolType();
7744 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007745 break;
7746 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007747 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007748 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007749 break;
7750 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007751 typeId = builder.makeFloatType(32);
7752 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007753 break;
7754 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007755 typeId = builder.makeIntType(32);
7756 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007757 break;
7758 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007759 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007760 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007761 break;
7762 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007763 typeId = builder.makeIntType(32);
7764 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007765 break;
7766 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007767 typeId = builder.makeIntType(32);
7768 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007769 break;
7770 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007771 typeId = builder.makeIntType(32);
7772 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007773 break;
7774 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007775 typeId = builder.makeIntType(32);
7776 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007777 break;
7778 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007779 typeId = builder.makeIntType(32);
7780 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007781 break;
7782 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007783 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7784 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007785 break;
7786 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007787 typeId = builder.makeBoolType();
7788 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007789 break;
7790 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007791 typeId = builder.makeBoolType();
7792 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007793 break;
7794 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007795 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7796 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007797 break;
7798 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007799 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7800 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007801 break;
7802 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007803 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7804 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007805 break;
7806 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007807 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7808 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007809 break;
7810 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007811 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007812 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007813 break;
7814 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007815 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007816 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007817 break;
Chao Chen3c366992018-09-19 11:41:59 -07007818 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7819 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7820 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007821 case glslang::EOpCooperativeMatrixMulAdd:
7822 opCode = spv::OpCooperativeMatrixMulAddNV;
7823 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007824#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007825 default:
7826 return 0;
7827 }
7828
7829 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007830 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007831 // Use an extended instruction from the standard library.
7832 // Construct the call arguments, without modifying the original operands vector.
7833 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7834 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007835 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007836 } else if (opCode == spv::OpDot && !isFloat) {
7837 // int dot(int, int)
7838 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7839 const int componentCount = builder.getNumComponents(operands[0]);
7840 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7841 builder.setPrecision(mulOp, precision);
7842 id = builder.createCompositeExtract(mulOp, typeId, 0);
7843 for (int i = 1; i < componentCount; ++i) {
7844 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007845 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007846 }
John Kessenich2359bd02015-12-06 19:29:11 -07007847 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007848 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007849 case 0:
7850 // should all be handled by visitAggregate and createNoArgOperation
7851 assert(0);
7852 return 0;
7853 case 1:
7854 // should all be handled by createUnaryOperation
7855 assert(0);
7856 return 0;
7857 case 2:
7858 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7859 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007860 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007861 // anything 3 or over doesn't have l-value operands, so all should be consumed
7862 assert(consumedOperands == operands.size());
7863 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007864 break;
7865 }
7866 }
7867
John Kessenichb9197c82019-08-11 07:41:45 -06007868#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007869 // Decode the return types that were structures
7870 switch (op) {
7871 case glslang::EOpAddCarry:
7872 case glslang::EOpSubBorrow:
7873 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7874 id = builder.createCompositeExtract(id, typeId0, 0);
7875 break;
7876 case glslang::EOpUMulExtended:
7877 case glslang::EOpIMulExtended:
7878 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7879 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7880 break;
7881 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007882 {
7883 assert(operands.size() == 2);
7884 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7885 // "exp" is floating-point type (from HLSL intrinsic)
7886 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7887 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7888 builder.createStore(member1, operands[1]);
7889 } else
7890 // "exp" is integer type (from GLSL built-in function)
7891 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7892 id = builder.createCompositeExtract(id, typeId0, 0);
7893 }
John Kessenich55e7d112015-11-15 21:33:39 -07007894 break;
7895 default:
7896 break;
7897 }
John Kessenichb9197c82019-08-11 07:41:45 -06007898#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007899
John Kessenich32cfd492016-02-02 12:37:46 -07007900 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007901}
7902
Rex Xu9d93a232016-05-05 12:30:44 +08007903// Intrinsics with no arguments (or no return value, and no precision).
7904spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007905{
Jeff Bolz36831c92018-09-05 10:11:41 -05007906 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007907 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7908 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007909
7910 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007911 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007912 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007913 if (glslangIntermediate->usingVulkanMemoryModel()) {
7914 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7915 spv::MemorySemanticsOutputMemoryKHRMask |
7916 spv::MemorySemanticsAcquireReleaseMask);
7917 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7918 } else {
7919 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7920 }
John Kessenich82979362017-12-11 04:02:24 -07007921 } else {
7922 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7923 spv::MemorySemanticsWorkgroupMemoryMask |
7924 spv::MemorySemanticsAcquireReleaseMask);
7925 }
John Kessenich140f3df2015-06-26 16:58:36 -06007926 return 0;
7927 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007928 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7929 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007930 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007931 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007932 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7933 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007934 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007935 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007936 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7937 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007938 return 0;
7939 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007940 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7941 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007942 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007943#ifndef GLSLANG_WEB
7944 case glslang::EOpMemoryBarrierAtomicCounter:
7945 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7946 spv::MemorySemanticsAcquireReleaseMask);
7947 return 0;
7948 case glslang::EOpMemoryBarrierImage:
7949 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7950 spv::MemorySemanticsAcquireReleaseMask);
7951 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007952 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007953 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007954 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007955 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007956 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007957 case glslang::EOpDeviceMemoryBarrier:
7958 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7959 spv::MemorySemanticsImageMemoryMask |
7960 spv::MemorySemanticsAcquireReleaseMask);
7961 return 0;
7962 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7963 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7964 spv::MemorySemanticsImageMemoryMask |
7965 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007966 return 0;
7967 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007968 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7969 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007970 return 0;
7971 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007972 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7973 spv::MemorySemanticsWorkgroupMemoryMask |
7974 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007975 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007976 case glslang::EOpSubgroupBarrier:
7977 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7978 spv::MemorySemanticsAcquireReleaseMask);
7979 return spv::NoResult;
7980 case glslang::EOpSubgroupMemoryBarrier:
7981 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7982 spv::MemorySemanticsAcquireReleaseMask);
7983 return spv::NoResult;
7984 case glslang::EOpSubgroupMemoryBarrierBuffer:
7985 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7986 spv::MemorySemanticsAcquireReleaseMask);
7987 return spv::NoResult;
7988 case glslang::EOpSubgroupMemoryBarrierImage:
7989 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7990 spv::MemorySemanticsAcquireReleaseMask);
7991 return spv::NoResult;
7992 case glslang::EOpSubgroupMemoryBarrierShared:
7993 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7994 spv::MemorySemanticsAcquireReleaseMask);
7995 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06007996
7997 case glslang::EOpEmitVertex:
7998 builder.createNoResultOp(spv::OpEmitVertex);
7999 return 0;
8000 case glslang::EOpEndPrimitive:
8001 builder.createNoResultOp(spv::OpEndPrimitive);
8002 return 0;
8003
John Kessenich66011cb2018-03-06 16:12:04 -07008004 case glslang::EOpSubgroupElect: {
8005 std::vector<spv::Id> operands;
8006 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8007 }
Rex Xu9d93a232016-05-05 12:30:44 +08008008 case glslang::EOpTime:
8009 {
8010 std::vector<spv::Id> args; // Dummy arguments
8011 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8012 return builder.setPrecision(id, precision);
8013 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008014 case glslang::EOpIgnoreIntersection:
8015 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008016 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008017 case glslang::EOpTerminateRay:
8018 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008019 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008020 case glslang::EOpRayQueryInitialize:
8021 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8022 return 0;
8023 case glslang::EOpRayQueryTerminate:
8024 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8025 return 0;
8026 case glslang::EOpRayQueryGenerateIntersection:
8027 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8028 return 0;
8029 case glslang::EOpRayQueryConfirmIntersection:
8030 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8031 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008032 case glslang::EOpBeginInvocationInterlock:
8033 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8034 return 0;
8035 case glslang::EOpEndInvocationInterlock:
8036 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8037 return 0;
8038
Jeff Bolzba6170b2019-07-01 09:23:23 -05008039 case glslang::EOpIsHelperInvocation:
8040 {
8041 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008042 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8043 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8044 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008045 }
8046
amhagan91fb0092019-07-10 21:14:38 -04008047 case glslang::EOpReadClockSubgroupKHR: {
8048 std::vector<spv::Id> args;
8049 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8050 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8051 builder.addCapability(spv::CapabilityShaderClockKHR);
8052 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8053 }
8054
8055 case glslang::EOpReadClockDeviceKHR: {
8056 std::vector<spv::Id> args;
8057 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8058 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8059 builder.addCapability(spv::CapabilityShaderClockKHR);
8060 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8061 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008062#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008063 default:
John Kessenich155d3512019-08-08 23:29:20 -06008064 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008065 }
John Kessenich155d3512019-08-08 23:29:20 -06008066
8067 logger->missingFunctionality("unknown operation with no arguments");
8068
8069 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008070}
8071
8072spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8073{
John Kessenich2f273362015-07-18 22:34:27 -06008074 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008075 spv::Id id;
8076 if (symbolValues.end() != iter) {
8077 id = iter->second;
8078 return id;
8079 }
8080
8081 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008082 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008083 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008084 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008085 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008086 if (forcedType.second != spv::NoType)
8087 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008088
Rex Xuc884b4a2016-06-29 15:03:44 +08008089 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008090 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8091 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8092 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008093#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008094 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008095 if (symbol->getQualifier().hasComponent())
8096 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8097 if (symbol->getQualifier().hasIndex())
8098 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008099#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008100 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008101 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008102 // atomic counters use this:
8103 if (symbol->getQualifier().hasOffset())
8104 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008105 }
8106
scygan2c864272016-05-18 18:09:17 +02008107 if (symbol->getQualifier().hasLocation())
8108 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008109 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008110 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008111 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008112 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008113 }
John Kessenich140f3df2015-06-26 16:58:36 -06008114 if (symbol->getQualifier().hasSet())
8115 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008116 else if (IsDescriptorResource(symbol->getType())) {
8117 // default to 0
8118 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8119 }
John Kessenich140f3df2015-06-26 16:58:36 -06008120 if (symbol->getQualifier().hasBinding())
8121 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008122 else if (IsDescriptorResource(symbol->getType())) {
8123 // default to 0
8124 builder.addDecoration(id, spv::DecorationBinding, 0);
8125 }
John Kessenich6c292d32016-02-15 20:58:50 -07008126 if (symbol->getQualifier().hasAttachment())
8127 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008128 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008129 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008130 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008131 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008132 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8133 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8134 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8135 }
8136 if (symbol->getQualifier().hasXfbOffset())
8137 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008138 }
8139
John Kessenichb9197c82019-08-11 07:41:45 -06008140 // add built-in variable decoration
8141 if (builtIn != spv::BuiltInMax) {
8142 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8143 }
8144
8145#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008146 if (symbol->getType().isImage()) {
8147 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008148 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8149 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008150 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008151 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008152 }
8153
John Kessenich5611c6d2018-04-05 11:25:02 -06008154 // nonuniform
8155 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8156
chaoc0ad6a4e2016-12-19 16:29:34 -08008157 if (builtIn == spv::BuiltInSampleMask) {
8158 spv::Decoration decoration;
8159 // GL_NV_sample_mask_override_coverage extension
8160 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008161 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008162 else
8163 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008164 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008165 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008166 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008167 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8168 }
8169 }
chaoc771d89f2017-01-13 01:10:53 -08008170 else if (builtIn == spv::BuiltInLayer) {
8171 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008172 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008173 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008174 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8175 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8176 }
John Kessenichb41bff62017-08-11 13:07:17 -06008177 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008178 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8179 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008180 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8181 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8182 }
8183 }
8184
chaoc6e5acae2016-12-20 13:28:52 -08008185 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008186 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008187 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008188 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8189 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008190 if (symbol->getQualifier().pervertexNV) {
8191 builder.addDecoration(id, spv::DecorationPerVertexNV);
8192 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8193 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8194 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008195
John Kessenich5d610ee2018-03-07 18:05:55 -07008196 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8197 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8198 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8199 symbol->getType().getQualifier().semanticName);
8200 }
8201
John Kessenich7015bd62019-08-01 03:28:08 -06008202 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008203 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8204 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008205 }
John Kessenichb9197c82019-08-11 07:41:45 -06008206#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008207
John Kessenich140f3df2015-06-26 16:58:36 -06008208 return id;
8209}
8210
John Kessenicha28f7a72019-08-06 07:00:58 -06008211#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008212// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8213void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8214{
8215 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008216 if (qualifier.perPrimitiveNV) {
8217 // Need to add capability/extension for fragment shader.
8218 // Mesh shader already adds this by default.
8219 if (glslangIntermediate->getStage() == EShLangFragment) {
8220 builder.addCapability(spv::CapabilityMeshShadingNV);
8221 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8222 }
Chao Chen3c366992018-09-19 11:41:59 -07008223 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008224 }
Chao Chen3c366992018-09-19 11:41:59 -07008225 if (qualifier.perViewNV)
8226 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8227 if (qualifier.perTaskNV)
8228 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8229 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008230 if (qualifier.perPrimitiveNV) {
8231 // Need to add capability/extension for fragment shader.
8232 // Mesh shader already adds this by default.
8233 if (glslangIntermediate->getStage() == EShLangFragment) {
8234 builder.addCapability(spv::CapabilityMeshShadingNV);
8235 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8236 }
Chao Chen3c366992018-09-19 11:41:59 -07008237 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008238 }
Chao Chen3c366992018-09-19 11:41:59 -07008239 if (qualifier.perViewNV)
8240 builder.addDecoration(id, spv::DecorationPerViewNV);
8241 if (qualifier.perTaskNV)
8242 builder.addDecoration(id, spv::DecorationPerTaskNV);
8243 }
8244}
8245#endif
8246
John Kessenich55e7d112015-11-15 21:33:39 -07008247// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008248// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008249//
8250// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8251//
8252// Recursively walk the nodes. The nodes form a tree whose leaves are
8253// regular constants, which themselves are trees that createSpvConstant()
8254// recursively walks. So, this function walks the "top" of the tree:
8255// - emit specialization constant-building instructions for specConstant
8256// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008257spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008258{
John Kessenich7cc0e282016-03-20 00:46:02 -06008259 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008260
qining4f4bb812016-04-03 23:55:17 -04008261 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008262 if (! node.getQualifier().specConstant) {
8263 // hand off to the non-spec-constant path
8264 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8265 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008266 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8267 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8268 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008269 }
8270
8271 // We now know we have a specialization constant to build
8272
John Kessenichd94c0032016-05-30 19:29:40 -06008273 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008274 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8275 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8276 std::vector<spv::Id> dimConstId;
8277 for (int dim = 0; dim < 3; ++dim) {
8278 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8279 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008280 if (specConst) {
8281 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8282 glslangIntermediate->getLocalSizeSpecId(dim));
8283 }
qining4f4bb812016-04-03 23:55:17 -04008284 }
8285 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8286 }
8287
8288 // An AST node labelled as specialization constant should be a symbol node.
8289 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8290 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008291 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008292 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008293 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8294 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8295 // will set the builder into spec constant op instruction generating mode.
8296 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008297 result = accessChainLoad(sub_tree->getType());
8298 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008299 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008300 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008301 } else {
8302 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008303 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008304 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008305 builder.addName(result, sn->getName().c_str());
8306 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008307 }
qining4f4bb812016-04-03 23:55:17 -04008308
8309 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8310 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008311 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008312 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008313}
8314
John Kessenich140f3df2015-06-26 16:58:36 -06008315// Use 'consts' as the flattened glslang source of scalar constants to recursively
8316// build the aggregate SPIR-V constant.
8317//
8318// If there are not enough elements present in 'consts', 0 will be substituted;
8319// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8320//
John Kessenich8985fc92020-03-03 10:25:07 -07008321spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8322 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008323{
8324 // vector of constants for SPIR-V
8325 std::vector<spv::Id> spvConsts;
8326
8327 // Type is used for struct and array constants
8328 spv::Id typeId = convertGlslangToSpvType(glslangType);
8329
8330 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008331 glslang::TType elementType(glslangType, 0);
8332 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008333 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008334 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008335 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008336 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008337 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008338 } else if (glslangType.isCoopMat()) {
8339 glslang::TType componentType(glslangType.getBasicType());
8340 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008341 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008342 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8343 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008344 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008345 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008346 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8347 bool zero = nextConst >= consts.size();
8348 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008349 case glslang::EbtInt:
8350 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8351 break;
8352 case glslang::EbtUint:
8353 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8354 break;
8355 case glslang::EbtFloat:
8356 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8357 break;
8358 case glslang::EbtBool:
8359 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8360 break;
8361#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008362 case glslang::EbtInt8:
8363 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8364 break;
8365 case glslang::EbtUint8:
8366 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8367 break;
8368 case glslang::EbtInt16:
8369 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8370 break;
8371 case glslang::EbtUint16:
8372 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8373 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008374 case glslang::EbtInt64:
8375 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8376 break;
8377 case glslang::EbtUint64:
8378 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8379 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008380 case glslang::EbtDouble:
8381 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8382 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008383 case glslang::EbtFloat16:
8384 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8385 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008386#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008387 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008388 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008389 break;
8390 }
8391 ++nextConst;
8392 }
8393 } else {
8394 // we have a non-aggregate (scalar) constant
8395 bool zero = nextConst >= consts.size();
8396 spv::Id scalar = 0;
8397 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008398 case glslang::EbtInt:
8399 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8400 break;
8401 case glslang::EbtUint:
8402 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8403 break;
8404 case glslang::EbtFloat:
8405 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8406 break;
8407 case glslang::EbtBool:
8408 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8409 break;
8410#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008411 case glslang::EbtInt8:
8412 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8413 break;
8414 case glslang::EbtUint8:
8415 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8416 break;
8417 case glslang::EbtInt16:
8418 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8419 break;
8420 case glslang::EbtUint16:
8421 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8422 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008423 case glslang::EbtInt64:
8424 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8425 break;
8426 case glslang::EbtUint64:
8427 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8428 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008429 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008430 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008431 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008432 case glslang::EbtFloat16:
8433 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8434 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008435 case glslang::EbtReference:
8436 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8437 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8438 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008439#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008440 case glslang::EbtString:
8441 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8442 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008443 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008444 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008445 break;
8446 }
8447 ++nextConst;
8448 return scalar;
8449 }
8450
8451 return builder.makeCompositeConstant(typeId, spvConsts);
8452}
8453
John Kessenich7c1aa102015-10-15 13:29:11 -06008454// Return true if the node is a constant or symbol whose reading has no
8455// non-trivial observable cost or effect.
8456bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8457{
8458 // don't know what this is
8459 if (node == nullptr)
8460 return false;
8461
8462 // a constant is safe
8463 if (node->getAsConstantUnion() != nullptr)
8464 return true;
8465
8466 // not a symbol means non-trivial
8467 if (node->getAsSymbolNode() == nullptr)
8468 return false;
8469
8470 // a symbol, depends on what's being read
8471 switch (node->getType().getQualifier().storage) {
8472 case glslang::EvqTemporary:
8473 case glslang::EvqGlobal:
8474 case glslang::EvqIn:
8475 case glslang::EvqInOut:
8476 case glslang::EvqConst:
8477 case glslang::EvqConstReadOnly:
8478 case glslang::EvqUniform:
8479 return true;
8480 default:
8481 return false;
8482 }
qining25262b32016-05-06 17:25:16 -04008483}
John Kessenich7c1aa102015-10-15 13:29:11 -06008484
8485// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008486// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008487// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008488// Return true if trivial.
8489bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8490{
8491 if (node == nullptr)
8492 return false;
8493
John Kessenich84cc15f2017-05-24 16:44:47 -06008494 // count non scalars as trivial, as well as anything coming from HLSL
8495 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008496 return true;
8497
John Kessenich7c1aa102015-10-15 13:29:11 -06008498 // symbols and constants are trivial
8499 if (isTrivialLeaf(node))
8500 return true;
8501
8502 // otherwise, it needs to be a simple operation or one or two leaf nodes
8503
8504 // not a simple operation
8505 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8506 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8507 if (binaryNode == nullptr && unaryNode == nullptr)
8508 return false;
8509
8510 // not on leaf nodes
8511 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8512 return false;
8513
8514 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8515 return false;
8516 }
8517
8518 switch (node->getAsOperator()->getOp()) {
8519 case glslang::EOpLogicalNot:
8520 case glslang::EOpConvIntToBool:
8521 case glslang::EOpConvUintToBool:
8522 case glslang::EOpConvFloatToBool:
8523 case glslang::EOpConvDoubleToBool:
8524 case glslang::EOpEqual:
8525 case glslang::EOpNotEqual:
8526 case glslang::EOpLessThan:
8527 case glslang::EOpGreaterThan:
8528 case glslang::EOpLessThanEqual:
8529 case glslang::EOpGreaterThanEqual:
8530 case glslang::EOpIndexDirect:
8531 case glslang::EOpIndexDirectStruct:
8532 case glslang::EOpLogicalXor:
8533 case glslang::EOpAny:
8534 case glslang::EOpAll:
8535 return true;
8536 default:
8537 return false;
8538 }
8539}
8540
8541// Emit short-circuiting code, where 'right' is never evaluated unless
8542// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008543spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8544 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008545{
8546 spv::Id boolTypeId = builder.makeBoolType();
8547
8548 // emit left operand
8549 builder.clearAccessChain();
8550 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008551 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008552
8553 // Operands to accumulate OpPhi operands
8554 std::vector<spv::Id> phiOperands;
8555 // accumulate left operand's phi information
8556 phiOperands.push_back(leftId);
8557 phiOperands.push_back(builder.getBuildPoint()->getId());
8558
8559 // Make the two kinds of operation symmetric with a "!"
8560 // || => emit "if (! left) result = right"
8561 // && => emit "if ( left) result = right"
8562 //
8563 // TODO: this runtime "not" for || could be avoided by adding functionality
8564 // to 'builder' to have an "else" without an "then"
8565 if (op == glslang::EOpLogicalOr)
8566 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8567
8568 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008569 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008570
8571 // emit right operand as the "then" part of the "if"
8572 builder.clearAccessChain();
8573 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008574 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008575
8576 // accumulate left operand's phi information
8577 phiOperands.push_back(rightId);
8578 phiOperands.push_back(builder.getBuildPoint()->getId());
8579
8580 // finish the "if"
8581 ifBuilder.makeEndIf();
8582
8583 // phi together the two results
8584 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8585}
8586
John Kessenicha28f7a72019-08-06 07:00:58 -06008587#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008588// Return type Id of the imported set of extended instructions corresponds to the name.
8589// Import this set if it has not been imported yet.
8590spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8591{
8592 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8593 return extBuiltinMap[name];
8594 else {
Rex Xu51596642016-09-21 18:56:12 +08008595 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008596 spv::Id extBuiltins = builder.import(name);
8597 extBuiltinMap[name] = extBuiltins;
8598 return extBuiltins;
8599 }
8600}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008601#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008602
John Kessenich140f3df2015-06-26 16:58:36 -06008603}; // end anonymous namespace
8604
8605namespace glslang {
8606
John Kessenich68d78fd2015-07-12 19:28:10 -06008607void GetSpirvVersion(std::string& version)
8608{
John Kessenich9e55f632015-07-15 10:03:39 -06008609 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008610 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008611 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008612 version = buf;
8613}
8614
John Kessenicha372a3e2017-11-02 22:32:14 -06008615// For low-order part of the generator's magic number. Bump up
8616// when there is a change in the style (e.g., if SSA form changes,
8617// or a different instruction sequence to do something gets used).
8618int GetSpirvGeneratorVersion()
8619{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008620 // return 1; // start
8621 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008622 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008623 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008624 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008625 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8626 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008627 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8628 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008629}
8630
John Kessenich140f3df2015-06-26 16:58:36 -06008631// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008632void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008633{
8634 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008635 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008636 if (out.fail())
8637 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008638 for (int i = 0; i < (int)spirv.size(); ++i) {
8639 unsigned int word = spirv[i];
8640 out.write((const char*)&word, 4);
8641 }
8642 out.close();
8643}
8644
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008645// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008646void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008647{
John Kessenich155d3512019-08-08 23:29:20 -06008648#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008649 std::ofstream out;
8650 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008651 if (out.fail())
8652 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008653 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008654 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008655 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008656 if (varName != nullptr) {
8657 out << "\t #pragma once" << std::endl;
8658 out << "const uint32_t " << varName << "[] = {" << std::endl;
8659 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008660 const int WORDS_PER_LINE = 8;
8661 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8662 out << "\t";
8663 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8664 const unsigned int word = spirv[i + j];
8665 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8666 if (i + j + 1 < (int)spirv.size()) {
8667 out << ",";
8668 }
8669 }
8670 out << std::endl;
8671 }
Flavio15017db2017-02-15 14:29:33 -08008672 if (varName != nullptr) {
8673 out << "};";
8674 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008675 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008676#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008677}
8678
John Kessenich140f3df2015-06-26 16:58:36 -06008679//
8680// Set up the glslang traversal
8681//
John Kessenich4e11b612018-08-30 16:56:59 -06008682void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008683{
Lei Zhang17535f72016-05-04 15:55:59 -04008684 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008685 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008686}
8687
John Kessenich4e11b612018-08-30 16:56:59 -06008688void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008689 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008690{
John Kessenich140f3df2015-06-26 16:58:36 -06008691 TIntermNode* root = intermediate.getTreeRoot();
8692
8693 if (root == 0)
8694 return;
8695
John Kessenich4e11b612018-08-30 16:56:59 -06008696 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008697 if (options == nullptr)
8698 options = &defaultOptions;
8699
John Kessenich4e11b612018-08-30 16:56:59 -06008700 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008701
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008702 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008703 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008704 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008705 it.dumpSpv(spirv);
8706
GregFfb03a552018-03-29 11:49:14 -06008707#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008708 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8709 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008710 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8711 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008712 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008713 prelegalization = false;
8714 }
John Kessenich717c80a2018-08-23 15:17:10 -06008715
John Kessenich4e11b612018-08-30 16:56:59 -06008716 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008717 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008718
John Kessenich717c80a2018-08-23 15:17:10 -06008719 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008720 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008721
GregFcd1f1692017-09-21 18:40:22 -06008722#endif
8723
John Kessenich4e11b612018-08-30 16:56:59 -06008724 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008725}
8726
8727}; // end namespace glslang