blob: 24203a16ed8128731525f206d00e6e149d6481ea [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.
alelenv999d4fd2020-06-01 23:24:41 -07001295 if (type.getBasicType() == glslang::EbtSampler ||
1296 type.getBasicType() == glslang::EbtAccStruct)
John Kessenich6c292d32016-02-15 20:58:50 -07001297 return type.getQualifier().isUniformOrBuffer();
1298
1299 // None of the above.
1300 return false;
1301}
1302
John Kesseniche0b6cad2015-12-24 10:30:13 -07001303void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1304{
1305 if (child.layoutMatrix == glslang::ElmNone)
1306 child.layoutMatrix = parent.layoutMatrix;
1307
1308 if (parent.invariant)
1309 child.invariant = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001310 if (parent.flat)
1311 child.flat = true;
1312 if (parent.centroid)
1313 child.centroid = true;
John Kessenich7015bd62019-08-01 03:28:08 -06001314#ifndef GLSLANG_WEB
John Kesseniche0b6cad2015-12-24 10:30:13 -07001315 if (parent.nopersp)
1316 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001317 if (parent.explicitInterp)
1318 child.explicitInterp = true;
John Kessenicha28f7a72019-08-06 07:00:58 -06001319 if (parent.perPrimitiveNV)
1320 child.perPrimitiveNV = true;
1321 if (parent.perViewNV)
1322 child.perViewNV = true;
1323 if (parent.perTaskNV)
1324 child.perTaskNV = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001325 if (parent.patch)
1326 child.patch = true;
1327 if (parent.sample)
1328 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001329 if (parent.coherent)
1330 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001331 if (parent.devicecoherent)
1332 child.devicecoherent = true;
1333 if (parent.queuefamilycoherent)
1334 child.queuefamilycoherent = true;
1335 if (parent.workgroupcoherent)
1336 child.workgroupcoherent = true;
1337 if (parent.subgroupcoherent)
1338 child.subgroupcoherent = true;
Daniel Kochdb32b242020-03-17 20:42:47 -04001339 if (parent.shadercallcoherent)
1340 child.shadercallcoherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001341 if (parent.nonprivate)
1342 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001343 if (parent.volatil)
1344 child.volatil = true;
1345 if (parent.restrict)
1346 child.restrict = true;
1347 if (parent.readonly)
1348 child.readonly = true;
1349 if (parent.writeonly)
1350 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001351#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001352}
1353
John Kessenichf2b7f332016-09-01 17:05:23 -06001354bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001355{
John Kessenich7b9fa252016-01-21 18:56:57 -07001356 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001357 // - struct members might inherit from a struct declaration
1358 // (note that non-block structs don't explicitly inherit,
1359 // only implicitly, meaning no decoration involved)
1360 // - affect decorations on the struct members
1361 // (note smooth does not, and expecting something like volatile
1362 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001363 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001364 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001365}
1366
John Kessenich140f3df2015-06-26 16:58:36 -06001367//
1368// Implement the TGlslangToSpvTraverser class.
1369//
1370
John Kessenich8985fc92020-03-03 10:25:07 -07001371TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
1372 const glslang::TIntermediate* glslangIntermediate,
1373 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
1374 TIntermTraverser(true, false, true),
1375 options(options),
1376 shaderEntry(nullptr), currentFunction(nullptr),
1377 sequenceDepth(0), logger(buildLogger),
1378 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
1379 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
1380 glslangIntermediate(glslangIntermediate),
Jeff Bolz04d73732019-05-31 13:06:01 -05001381 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
1382 nonSemanticDebugPrintf(0)
John Kessenich140f3df2015-06-26 16:58:36 -06001383{
1384 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1385
1386 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001387 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1388 glslangIntermediate->getVersion());
1389
John Kessenich121853f2017-05-31 17:11:16 -06001390 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001391 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001392 builder.setSourceFile(glslangIntermediate->getSourceFile());
1393
1394 // Set the source shader's text. If for SPV version 1.0, include
1395 // a preamble in comments stating the OpModuleProcessed instructions.
1396 // Otherwise, emit those as actual instructions.
1397 std::string text;
1398 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1399 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001400 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001401 text.append("// OpModuleProcessed ");
1402 text.append(processes[p]);
1403 text.append("\n");
1404 } else
1405 builder.addModuleProcessed(processes[p]);
1406 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001407 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001408 text.append("#line 1\n");
1409 text.append(glslangIntermediate->getSourceText());
1410 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001411 // Pass name and text for all included files
1412 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1413 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1414 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001415 }
John Kessenich140f3df2015-06-26 16:58:36 -06001416 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001417
1418 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1419 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1420
1421 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1422 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
John Kessenich1ff0c182019-10-10 12:01:13 -06001423 builder.addIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer, spv::Spv_1_5);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001424 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
John Kessenich8985fc92020-03-03 10:25:07 -07001425 }
Jeff Bolz36831c92018-09-05 10:11:41 -05001426 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001427 memoryModel = spv::MemoryModelVulkanKHR;
1428 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
John Kessenich8317e6c2019-08-18 23:58:08 -06001429 builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
Jeff Bolz36831c92018-09-05 10:11:41 -05001430 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001431 builder.setMemoryModel(addressingModel, memoryModel);
1432
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001433 if (glslangIntermediate->usingVariablePointers()) {
1434 builder.addCapability(spv::CapabilityVariablePointers);
1435 }
1436
John Kessenicheee9d532016-09-19 18:09:30 -06001437 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1438 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001439
1440 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001441 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1442 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
Pankaj Mistry2a8ead22020-04-26 17:52:31 -07001443 builder.addSourceExtension(it->first.c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001444
1445 // Add the top-level modes for this shader.
1446
John Kessenich92187592016-02-01 13:45:25 -07001447 if (glslangIntermediate->getXfbMode()) {
1448 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001450 }
John Kessenich140f3df2015-06-26 16:58:36 -06001451
alelenv59216d52020-05-21 04:38:41 -07001452 if (glslangIntermediate->getLayoutPrimitiveCulling()) {
alelenv75de1962020-04-08 21:09:20 -07001453 builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR);
1454 }
1455
John Kessenich140f3df2015-06-26 16:58:36 -06001456 unsigned int mode;
1457 switch (glslangIntermediate->getStage()) {
1458 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001459 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001460 break;
1461
John Kessenicha28f7a72019-08-06 07:00:58 -06001462 case EShLangFragment:
1463 builder.addCapability(spv::CapabilityShader);
1464 if (glslangIntermediate->getPixelCenterInteger())
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
1466
1467 if (glslangIntermediate->getOriginUpperLeft())
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
1469 else
1470 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
1471
1472 if (glslangIntermediate->getEarlyFragmentTests())
1473 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1474
1475 if (glslangIntermediate->getPostDepthCoverage()) {
1476 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1477 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1478 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1479 }
1480
John Kessenichb9197c82019-08-11 07:41:45 -06001481 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
1483
1484#ifndef GLSLANG_WEB
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001485
John Kessenicha28f7a72019-08-06 07:00:58 -06001486 switch(glslangIntermediate->getDepth()) {
1487 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1488 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
1489 default: mode = spv::ExecutionModeMax; break;
1490 }
1491 if (mode != spv::ExecutionModeMax)
1492 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kessenicha28f7a72019-08-06 07:00:58 -06001493 switch (glslangIntermediate->getInterlockOrdering()) {
John Kessenichf8d1d742019-10-21 06:55:11 -06001494 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
1495 break;
1496 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
1497 break;
1498 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
1499 break;
1500 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
1501 break;
1502 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
1503 break;
1504 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
1505 break;
1506 default: mode = spv::ExecutionModeMax;
1507 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001508 }
1509 if (mode != spv::ExecutionModeMax) {
1510 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1511 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1512 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1513 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1514 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1515 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1516 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1517 } else {
1518 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1519 }
1520 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1521 }
John Kessenichb9197c82019-08-11 07:41:45 -06001522#endif
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04001523 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06001524
John Kessenicha28f7a72019-08-06 07:00:58 -06001525 case EShLangCompute:
1526 builder.addCapability(spv::CapabilityShader);
1527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1528 glslangIntermediate->getLocalSize(1),
1529 glslangIntermediate->getLocalSize(2));
1530 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1531 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1532 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1533 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1534 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1535 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1537 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1538 }
1539 break;
John Kessenich51ed01c2019-10-10 11:40:11 -06001540#ifndef GLSLANG_WEB
steve-lunarge7412492017-03-23 11:56:07 -06001541 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001542 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001543 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001544
steve-lunarge7412492017-03-23 11:56:07 -06001545 glslang::TLayoutGeometry primitive;
1546
1547 if (glslangIntermediate->getStage() == EShLangTessControl) {
John Kessenich8985fc92020-03-03 10:25:07 -07001548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1549 glslangIntermediate->getVertices());
steve-lunarge7412492017-03-23 11:56:07 -06001550 primitive = glslangIntermediate->getOutputPrimitive();
1551 } else {
1552 primitive = glslangIntermediate->getInputPrimitive();
1553 }
1554
1555 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001556 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1557 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1558 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001559 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001560 }
John Kessenich4016e382016-07-15 11:53:56 -06001561 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001562 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1563
John Kesseniche6903322015-10-13 16:29:02 -06001564 switch (glslangIntermediate->getVertexSpacing()) {
1565 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1566 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1567 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001568 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001569 }
John Kessenich4016e382016-07-15 11:53:56 -06001570 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001571 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1572
1573 switch (glslangIntermediate->getVertexOrder()) {
1574 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1575 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001576 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001577 }
John Kessenich4016e382016-07-15 11:53:56 -06001578 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001579 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1580
1581 if (glslangIntermediate->getPointMode())
1582 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 break;
1584
1585 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001586 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001587 switch (glslangIntermediate->getInputPrimitive()) {
1588 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1589 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1590 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001591 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001592 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001593 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001594 }
John Kessenich4016e382016-07-15 11:53:56 -06001595 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001596 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001597
John Kessenich140f3df2015-06-26 16:58:36 -06001598 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1599
1600 switch (glslangIntermediate->getOutputPrimitive()) {
1601 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1602 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1603 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001604 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001605 }
John Kessenich4016e382016-07-15 11:53:56 -06001606 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1608 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1609 break;
1610
Daniel Kochdb32b242020-03-17 20:42:47 -04001611 case EShLangRayGen:
1612 case EShLangIntersect:
1613 case EShLangAnyHit:
1614 case EShLangClosestHit:
1615 case EShLangMiss:
1616 case EShLangCallable:
1617 {
1618 auto& extensions = glslangIntermediate->getRequestedExtensions();
1619 if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
1620 builder.addCapability(spv::CapabilityRayTracingProvisionalKHR);
1621 builder.addExtension("SPV_KHR_ray_tracing");
1622 }
1623 else {
1624 builder.addCapability(spv::CapabilityRayTracingNV);
1625 builder.addExtension("SPV_NV_ray_tracing");
1626 }
Chao Chenb50c02e2018-09-19 11:42:24 -07001627 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04001628 }
Chao Chen3c366992018-09-19 11:41:59 -07001629 case EShLangTaskNV:
1630 case EShLangMeshNV:
1631 builder.addCapability(spv::CapabilityMeshShadingNV);
1632 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1633 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1634 glslangIntermediate->getLocalSize(1),
1635 glslangIntermediate->getLocalSize(2));
1636 if (glslangIntermediate->getStage() == EShLangMeshNV) {
John Kessenich8985fc92020-03-03 10:25:07 -07001637 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
1638 glslangIntermediate->getVertices());
1639 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
1640 glslangIntermediate->getPrimitives());
Chao Chen3c366992018-09-19 11:41:59 -07001641
1642 switch (glslangIntermediate->getOutputPrimitive()) {
1643 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1644 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1645 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1646 default: mode = spv::ExecutionModeMax; break;
1647 }
1648 if (mode != spv::ExecutionModeMax)
1649 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1650 }
1651 break;
1652#endif
1653
John Kessenich140f3df2015-06-26 16:58:36 -06001654 default:
1655 break;
1656 }
John Kessenich140f3df2015-06-26 16:58:36 -06001657}
1658
John Kessenichfca82622016-11-26 13:23:20 -07001659// Finish creating SPV, after the traversal is complete.
1660void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001661{
John Kessenichf04c51b2018-08-03 15:56:12 -06001662 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001663 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001664 builder.setBuildPoint(shaderEntry->getLastBlock());
1665 builder.leaveFunction();
1666 }
1667
John Kessenich7ba63412015-12-20 17:37:07 -07001668 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001669 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1670 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001671
David Neto8c3d5b42019-10-21 14:50:31 -04001672 // Add capabilities, extensions, remove unneeded decorations, etc.,
John Kessenichf04c51b2018-08-03 15:56:12 -06001673 // based on the resulting SPIR-V.
David Neto8c3d5b42019-10-21 14:50:31 -04001674 // Note: WebGPU code generation must have the opportunity to aggressively
1675 // prune unreachable merge blocks and continue targets.
John Kessenichf04c51b2018-08-03 15:56:12 -06001676 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001677}
1678
John Kessenichfca82622016-11-26 13:23:20 -07001679// Write the SPV into 'out'.
1680void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001681{
John Kessenichfca82622016-11-26 13:23:20 -07001682 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001683}
1684
1685//
1686// Implement the traversal functions.
1687//
1688// Return true from interior nodes to have the external traversal
1689// continue on to children. Return false if children were
1690// already processed.
1691//
1692
1693//
qining25262b32016-05-06 17:25:16 -04001694// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001695// - uniform/input reads
1696// - output writes
1697// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1698// - something simple that degenerates into the last bullet
1699//
1700void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1701{
qining75d1d802016-04-06 14:42:01 -04001702 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
Roy05a5b532020-01-03 16:21:34 +08001703 if (symbol->getType().isStruct())
1704 glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
1705
qining75d1d802016-04-06 14:42:01 -04001706 if (symbol->getType().getQualifier().isSpecConstant())
1707 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1708
John Kessenich140f3df2015-06-26 16:58:36 -06001709 // getSymbolId() will set up all the IO decorations on the first call.
1710 // Formal function parameters were mapped during makeFunctions().
1711 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001712
John Kessenich7ba63412015-12-20 17:37:07 -07001713 if (builder.isPointer(id)) {
John Kessenichc30d3352020-06-10 07:15:24 -06001714 if (!symbol->getType().getQualifier().isParamInput() &&
1715 !symbol->getType().getQualifier().isParamOutput()) {
1716 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1717 // Consider adding to the OpEntryPoint interface list.
1718 // Only looking at structures if they have at least one member.
1719 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1720 spv::StorageClass sc = builder.getStorageClass(id);
1721 // Before SPIR-V 1.4, we only want to include Input and Output.
1722 // Starting with SPIR-V 1.4, we want all globals.
1723 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1724 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
1725 iOSet.insert(id);
1726 }
John Kessenich7c7731e2019-01-04 16:47:06 +07001727 }
John Kessenich5f77d862017-09-19 11:09:59 -06001728 }
John Kessenich9c14f772019-06-17 08:38:35 -06001729
Daniel Kochdb32b242020-03-17 20:42:47 -04001730 // If the SPIR-V type is required to be different than the AST type
1731 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001732 // translate now from the SPIR-V type to the AST type, for the consuming
1733 // operation.
1734 // Note this turns it from an l-value to an r-value.
1735 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1736 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1737 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001738 }
1739
1740 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001741 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001742 // Prepare to generate code for the access
1743
1744 // L-value chains will be computed left to right. We're on the symbol now,
1745 // which is the left-most part of the access chain, so now is "clear" time,
1746 // followed by setting the base.
1747 builder.clearAccessChain();
1748
1749 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001750 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001751 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001752 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001753 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001754 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001755 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001756 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001757 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1758 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001759 builder.setAccessChainRValue(id);
1760 else
1761 builder.setAccessChainLValue(id);
1762 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001763
John Kessenichb9197c82019-08-11 07:41:45 -06001764#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001765 // Process linkage-only nodes for any special additional interface work.
1766 if (linkageOnly) {
1767 if (glslangIntermediate->getHlslFunctionality1()) {
1768 // Map implicit counter buffers to their originating buffers, which should have been
1769 // seen by now, given earlier pruning of unused counters, and preservation of order
1770 // of declaration.
1771 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1772 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1773 // Save possible originating buffers for counter buffers, keyed by
1774 // making the potential counter-buffer name.
1775 std::string keyName = symbol->getName().c_str();
1776 keyName = glslangIntermediate->addCounterBufferName(keyName);
1777 counterOriginator[keyName] = symbol;
1778 } else {
1779 // Handle a counter buffer, by finding the saved originating buffer.
1780 std::string keyName = symbol->getName().c_str();
1781 auto it = counterOriginator.find(keyName);
1782 if (it != counterOriginator.end()) {
1783 id = getSymbolId(it->second);
1784 if (id != spv::NoResult) {
1785 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001786 if (counterId != spv::NoResult) {
1787 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001788 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001789 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001790 }
1791 }
1792 }
1793 }
1794 }
1795 }
John Kessenich155d3512019-08-08 23:29:20 -06001796#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001797}
1798
1799bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1800{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001801 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001802 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1803 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1804 }
1805 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1806 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1807 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001808
qining40887662016-04-03 22:20:42 -04001809 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1810 if (node->getType().getQualifier().isSpecConstant())
1811 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1812
John Kessenich140f3df2015-06-26 16:58:36 -06001813 // First, handle special cases
1814 switch (node->getOp()) {
1815 case glslang::EOpAssign:
1816 case glslang::EOpAddAssign:
1817 case glslang::EOpSubAssign:
1818 case glslang::EOpMulAssign:
1819 case glslang::EOpVectorTimesMatrixAssign:
1820 case glslang::EOpVectorTimesScalarAssign:
1821 case glslang::EOpMatrixTimesScalarAssign:
1822 case glslang::EOpMatrixTimesMatrixAssign:
1823 case glslang::EOpDivAssign:
1824 case glslang::EOpModAssign:
1825 case glslang::EOpAndAssign:
1826 case glslang::EOpInclusiveOrAssign:
1827 case glslang::EOpExclusiveOrAssign:
1828 case glslang::EOpLeftShiftAssign:
1829 case glslang::EOpRightShiftAssign:
1830 // A bin-op assign "a += b" means the same thing as "a = a + b"
1831 // where a is evaluated before b. For a simple assignment, GLSL
1832 // says to evaluate the left before the right. So, always, left
1833 // node then right node.
1834 {
1835 // get the left l-value, save it away
1836 builder.clearAccessChain();
1837 node->getLeft()->traverse(this);
1838 spv::Builder::AccessChain lValue = builder.getAccessChain();
1839
1840 // evaluate the right
1841 builder.clearAccessChain();
1842 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001843 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001844
1845 if (node->getOp() != glslang::EOpAssign) {
1846 // the left is also an r-value
1847 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001848 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001849
1850 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001851 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001852 TranslateNoContractionDecoration(node->getType().getQualifier()),
1853 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001854 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001855 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1856 node->getType().getBasicType());
1857
1858 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001859 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861
1862 // store the result
1863 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001864 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001865
1866 // assignments are expressions having an rValue after they are evaluated...
1867 builder.clearAccessChain();
1868 builder.setAccessChainRValue(rValue);
1869 }
1870 return false;
1871 case glslang::EOpIndexDirect:
1872 case glslang::EOpIndexDirectStruct:
1873 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001874 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001875 // Get the left part of the access chain.
1876 node->getLeft()->traverse(this);
1877
1878 // Add the next element in the chain
1879
David Netoa901ffe2016-06-08 14:11:40 +01001880 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001881 if (! node->getLeft()->getType().isArray() &&
1882 node->getLeft()->getType().isVector() &&
1883 node->getOp() == glslang::EOpIndexDirect) {
1884 // This is essentially a hard-coded vector swizzle of size 1,
1885 // so short circuit the access-chain stuff with a swizzle.
1886 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001887 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001888 int dummySize;
1889 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1890 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001891 glslangIntermediate->getBaseAlignmentScalar(
1892 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001893 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001894
1895 // Load through a block reference is performed with a dot operator that
1896 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1897 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001898 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001899 !node->getLeft()->getType().isArray() &&
1900 node->getOp() == glslang::EOpIndexDirectStruct)
1901 {
1902 spv::Id left = accessChainLoad(node->getLeft()->getType());
1903 builder.clearAccessChain();
1904 builder.setAccessChainLValue(left);
1905 }
1906
David Netoa901ffe2016-06-08 14:11:40 +01001907 int spvIndex = glslangIndex;
1908 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1909 node->getOp() == glslang::EOpIndexDirectStruct)
1910 {
1911 // This may be, e.g., an anonymous block-member selection, which generally need
1912 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001913 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1914 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1915 std::vector<int>& remapper = memberRemapper[glslangId];
1916 assert(remapper.size() > 0);
1917 spvIndex = remapper[glslangIndex];
1918 }
David Netoa901ffe2016-06-08 14:11:40 +01001919 }
John Kessenichebb50532016-05-16 19:22:05 -06001920
David Netoa901ffe2016-06-08 14:11:40 +01001921 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001922 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1923 TranslateCoherent(node->getLeft()->getType()),
1924 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001925
1926 // Add capabilities here for accessing PointSize and clip/cull distance.
1927 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001928 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001929 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001930 }
1931 }
1932 return false;
1933 case glslang::EOpIndexIndirect:
1934 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001935 // Array, matrix, or vector indirection with variable index.
1936 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001937 // matrices are arrays of vectors, so will also work for a matrix.
1938 // Will use the access chain's 'component' for variable index into a vector.
1939
1940 // This adapter is building access chains left to right.
1941 // Set up the access chain to the left.
1942 node->getLeft()->traverse(this);
1943
1944 // save it so that computing the right side doesn't trash it
1945 spv::Builder::AccessChain partial = builder.getAccessChain();
1946
1947 // compute the next index in the chain
1948 builder.clearAccessChain();
1949 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001950 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001951
John Kessenich5611c6d2018-04-05 11:25:02 -06001952 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1953
John Kessenich140f3df2015-06-26 16:58:36 -06001954 // restore the saved access chain
1955 builder.setAccessChain(partial);
1956
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001957 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1958 int dummySize;
1959 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1960 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001961 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1962 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001963 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001964 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1965 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001966 }
1967 return false;
1968 case glslang::EOpVectorSwizzle:
1969 {
1970 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001971 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001972 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001973 int dummySize;
1974 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1975 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001976 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1977 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001978 }
1979 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001980 case glslang::EOpMatrixSwizzle:
1981 logger->missingFunctionality("matrix swizzle");
1982 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001983 case glslang::EOpLogicalOr:
1984 case glslang::EOpLogicalAnd:
1985 {
1986
1987 // These may require short circuiting, but can sometimes be done as straight
1988 // binary operations. The right operand must be short circuited if it has
1989 // side effects, and should probably be if it is complex.
1990 if (isTrivial(node->getRight()->getAsTyped()))
1991 break; // handle below as a normal binary operation
1992 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001993 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1994 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001995 builder.clearAccessChain();
1996 builder.setAccessChainRValue(result);
1997 }
1998 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001999 default:
2000 break;
2001 }
2002
2003 // Assume generic binary op...
2004
John Kessenich32cfd492016-02-02 12:37:46 -07002005 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002006 builder.clearAccessChain();
2007 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002008 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002009
John Kessenich32cfd492016-02-02 12:37:46 -07002010 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002011 builder.clearAccessChain();
2012 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002013 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002014
John Kessenich32cfd492016-02-02 12:37:46 -07002015 // get result
John Kessenichead86222018-03-28 18:01:20 -06002016 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002017 TranslateNoContractionDecoration(node->getType().getQualifier()),
2018 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002019 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002020 convertGlslangToSpvType(node->getType()), left, right,
2021 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002022
John Kessenich50e57562015-12-21 21:21:11 -07002023 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002024 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002025 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002026 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002027 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002028 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002029 return false;
2030 }
John Kessenich140f3df2015-06-26 16:58:36 -06002031}
2032
John Kessenich9c14f772019-06-17 08:38:35 -06002033// Figure out what, if any, type changes are needed when accessing a specific built-in.
2034// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2035// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002036std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002037 const glslang::TType& glslangType)
2038{
Daniel Kochdb32b242020-03-17 20:42:47 -04002039 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002040 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002041 case glslang::EbvSubGroupEqMask:
2042 case glslang::EbvSubGroupGeMask:
2043 case glslang::EbvSubGroupGtMask:
2044 case glslang::EbvSubGroupLeMask:
2045 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002046 // these require changing a 64-bit scaler -> a vector of 32-bit components
2047 if (glslangType.isVector())
2048 break;
2049 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2050 builder.makeUintType(64));
2051 return ret;
2052 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002053 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2054 // builtins. During visitBinary we insert a transpose
2055 case glslang::EbvWorldToObject3x4:
2056 case glslang::EbvObjectToWorld3x4: {
2057 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2058 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2059 );
2060 return ret;
2061 }
John Kessenich9c14f772019-06-17 08:38:35 -06002062 default:
2063 break;
2064 }
2065
2066 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2067 return ret;
2068}
2069
2070// For an object previously identified (see getForcedType() and forceType)
2071// as needing type translations, do the translation needed for a load, turning
2072// an L-value into in R-value.
2073spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2074{
2075 const auto forceIt = forceType.find(object);
2076 if (forceIt == forceType.end())
2077 return object;
2078
2079 spv::Id desiredTypeId = forceIt->second;
2080 spv::Id objectTypeId = builder.getTypeId(object);
2081 assert(builder.isPointerType(objectTypeId));
2082 objectTypeId = builder.getContainedTypeId(objectTypeId);
2083 if (builder.isVectorType(objectTypeId) &&
2084 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2085 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2086 // handle 32-bit v.xy* -> 64-bit
2087 builder.clearAccessChain();
2088 builder.setAccessChainLValue(object);
2089 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2090 std::vector<spv::Id> components;
2091 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2092 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2093
2094 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2095 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2096 builder.createCompositeConstruct(vecType, components));
2097 } else {
2098 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2099 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002100 } else if (builder.isMatrixType(objectTypeId)) {
2101 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2102 // and we insert a transpose after loading the original non-transposed builtins
2103 builder.clearAccessChain();
2104 builder.setAccessChainLValue(object);
2105 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2106 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2107
2108 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002109 logger->missingFunctionality("forcing non 32-bit vector type");
2110 }
2111
2112 return object;
2113}
2114
John Kessenich140f3df2015-06-26 16:58:36 -06002115bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2116{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002117 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002118
qining40887662016-04-03 22:20:42 -04002119 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2120 if (node->getType().getQualifier().isSpecConstant())
2121 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2122
John Kessenichfc51d282015-08-19 13:34:18 -06002123 spv::Id result = spv::NoResult;
2124
2125 // try texturing first
2126 result = createImageTextureFunctionCall(node);
2127 if (result != spv::NoResult) {
2128 builder.clearAccessChain();
2129 builder.setAccessChainRValue(result);
2130
2131 return false; // done with this node
2132 }
2133
2134 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002135
2136 if (node->getOp() == glslang::EOpArrayLength) {
2137 // Quite special; won't want to evaluate the operand.
2138
John Kessenich5611c6d2018-04-05 11:25:02 -06002139 // Currently, the front-end does not allow .length() on an array until it is sized,
2140 // except for the last block membeor of an SSBO.
2141 // TODO: If this changes, link-time sized arrays might show up here, and need their
2142 // size extracted.
2143
John Kessenichc9a80832015-09-12 12:17:44 -06002144 // Normal .length() would have been constant folded by the front-end.
2145 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002146 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002147
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002148 spv::Id length;
2149 if (node->getOperand()->getType().isCoopMat()) {
2150 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2151
2152 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2153 assert(builder.isCooperativeMatrixType(typeId));
2154
2155 length = builder.createCooperativeMatrixLength(typeId);
2156 } else {
2157 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2158 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002159 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2160 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002161 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2162 }
John Kessenichc9a80832015-09-12 12:17:44 -06002163
John Kessenich8c869672018-11-28 07:01:37 -07002164 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2165 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2166 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002167 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2168 if (builder.isInSpecConstCodeGenMode()) {
2169 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2170 } else {
2171 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2172 }
2173 }
John Kessenich8c869672018-11-28 07:01:37 -07002174
John Kessenichc9a80832015-09-12 12:17:44 -06002175 builder.clearAccessChain();
2176 builder.setAccessChainRValue(length);
2177
2178 return false;
2179 }
2180
John Kessenichfc51d282015-08-19 13:34:18 -06002181 // Start by evaluating the operand
2182
John Kessenich8c8505c2016-07-26 12:50:38 -06002183 // Does it need a swizzle inversion? If so, evaluation is inverted;
2184 // operate first on the swizzle base, then apply the swizzle.
2185 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002186 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2187 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002188 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2189 invertedType = getInvertedSwizzleType(*node->getOperand());
2190
John Kessenich140f3df2015-06-26 16:58:36 -06002191 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002192 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002193 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002194 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002195 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002196 operandNode = node->getOperand();
2197
2198 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002199
Rex Xufc618912015-09-09 16:42:49 +08002200 spv::Id operand = spv::NoResult;
2201
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002202 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2203
John Kessenichfb4f2332019-08-09 03:49:15 -06002204#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002205 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2206 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002207 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002208 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2209 node->getOp() == glslang::EOpRayQueryProceed ||
2210 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2211 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2212 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2213 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2214 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2215 node->getOp() == glslang::EOpRayQueryTerminate ||
2216 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002217 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002218 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2219 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2220 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002221#endif
2222 {
John Kessenich32cfd492016-02-02 12:37:46 -07002223 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002224 }
John Kessenich140f3df2015-06-26 16:58:36 -06002225
John Kessenichead86222018-03-28 18:01:20 -06002226 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002227 TranslateNoContractionDecoration(node->getType().getQualifier()),
2228 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002229
2230 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002231 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002232 result = createConversion(node->getOp(), decorations, resultType(), operand,
2233 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002234
2235 // if not, then possibly an operation
2236 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002237 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2238 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002239
2240 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002241 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002242 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002243 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002244 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002245
John Kessenich140f3df2015-06-26 16:58:36 -06002246 builder.clearAccessChain();
2247 builder.setAccessChainRValue(result);
2248
2249 return false; // done with this node
2250 }
2251
2252 // it must be a special case, check...
2253 switch (node->getOp()) {
2254 case glslang::EOpPostIncrement:
2255 case glslang::EOpPostDecrement:
2256 case glslang::EOpPreIncrement:
2257 case glslang::EOpPreDecrement:
2258 {
2259 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002260 spv::Id one = 0;
2261 if (node->getBasicType() == glslang::EbtFloat)
2262 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002263#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002264 else if (node->getBasicType() == glslang::EbtDouble)
2265 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002266 else if (node->getBasicType() == glslang::EbtFloat16)
2267 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002268 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2269 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002270 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2271 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002272 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2273 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002274#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002275 else
2276 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002277 glslang::TOperator op;
2278 if (node->getOp() == glslang::EOpPreIncrement ||
2279 node->getOp() == glslang::EOpPostIncrement)
2280 op = glslang::EOpAdd;
2281 else
2282 op = glslang::EOpSub;
2283
John Kessenichead86222018-03-28 18:01:20 -06002284 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002285 convertGlslangToSpvType(node->getType()), operand, one,
2286 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002287 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002288
2289 // The result of operation is always stored, but conditionally the
2290 // consumed result. The consumed result is always an r-value.
2291 builder.accessChainStore(result);
2292 builder.clearAccessChain();
2293 if (node->getOp() == glslang::EOpPreIncrement ||
2294 node->getOp() == glslang::EOpPreDecrement)
2295 builder.setAccessChainRValue(result);
2296 else
2297 builder.setAccessChainRValue(operand);
2298 }
2299
2300 return false;
2301
John Kessenich155d3512019-08-08 23:29:20 -06002302#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002303 case glslang::EOpEmitStreamVertex:
2304 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2305 return false;
2306 case glslang::EOpEndStreamPrimitive:
2307 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2308 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002309 case glslang::EOpRayQueryTerminate:
2310 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2311 return false;
2312 case glslang::EOpRayQueryConfirmIntersection:
2313 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2314 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002315#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002316
2317 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002318 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002319 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002320 }
John Kessenich140f3df2015-06-26 16:58:36 -06002321}
2322
Jeff Bolz53134492019-06-25 13:31:10 -05002323// Construct a composite object, recursively copying members if their types don't match
2324spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2325{
2326 for (int c = 0; c < (int)constituents.size(); ++c) {
2327 spv::Id& constituent = constituents[c];
2328 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2329 spv::Id rType = builder.getTypeId(constituent);
2330 if (lType != rType) {
2331 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2332 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2333 } else if (builder.isStructType(rType)) {
2334 std::vector<spv::Id> rTypeConstituents;
2335 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2336 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002337 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2338 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002339 }
2340 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2341 } else {
2342 assert(builder.isArrayType(rType));
2343 std::vector<spv::Id> rTypeConstituents;
2344 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2345
2346 spv::Id elementRType = builder.getContainedTypeId(rType);
2347 for (int i = 0; i < numrTypeConstituents; ++i) {
2348 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2349 }
2350 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2351 }
2352 }
2353 }
2354 return builder.createCompositeConstruct(resultTypeId, constituents);
2355}
2356
John Kessenich140f3df2015-06-26 16:58:36 -06002357bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2358{
qining27e04a02016-04-14 16:40:20 -04002359 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2360 if (node->getType().getQualifier().isSpecConstant())
2361 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2362
John Kessenichfc51d282015-08-19 13:34:18 -06002363 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002364 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2365 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2366 // SPIR-V, for an out parameter
2367 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002368
John Kessenich8985fc92020-03-03 10:25:07 -07002369 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2370 invertedType :
2371 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002372
2373 // try texturing
2374 result = createImageTextureFunctionCall(node);
2375 if (result != spv::NoResult) {
2376 builder.clearAccessChain();
2377 builder.setAccessChainRValue(result);
2378
2379 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002380 }
2381#ifndef GLSLANG_WEB
2382 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002383 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002384 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002385 // "imageStore" is a special case, which has no result
2386 return false;
2387 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002388#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002389
John Kessenich140f3df2015-06-26 16:58:36 -06002390 glslang::TOperator binOp = glslang::EOpNull;
2391 bool reduceComparison = true;
2392 bool isMatrix = false;
2393 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002394 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002395
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002396 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2397
John Kessenich140f3df2015-06-26 16:58:36 -06002398 assert(node->getOp());
2399
John Kessenichf6640762016-08-01 19:44:00 -06002400 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002401
2402 switch (node->getOp()) {
2403 case glslang::EOpSequence:
2404 {
2405 if (preVisit)
2406 ++sequenceDepth;
2407 else
2408 --sequenceDepth;
2409
2410 if (sequenceDepth == 1) {
2411 // If this is the parent node of all the functions, we want to see them
2412 // early, so all call points have actual SPIR-V functions to reference.
2413 // In all cases, still let the traverser visit the children for us.
2414 makeFunctions(node->getAsAggregate()->getSequence());
2415
John Kessenich6fccb3c2016-09-19 16:01:41 -06002416 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002417 // anything else gets there, so visit out of order, doing them all now.
2418 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2419
John Kessenich6a60c2f2016-12-08 21:01:59 -07002420 // 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 -06002421 // so do them manually.
2422 visitFunctions(node->getAsAggregate()->getSequence());
2423
2424 return false;
2425 }
2426
2427 return true;
2428 }
2429 case glslang::EOpLinkerObjects:
2430 {
2431 if (visit == glslang::EvPreVisit)
2432 linkageOnly = true;
2433 else
2434 linkageOnly = false;
2435
2436 return true;
2437 }
2438 case glslang::EOpComma:
2439 {
2440 // processing from left to right naturally leaves the right-most
2441 // lying around in the access chain
2442 glslang::TIntermSequence& glslangOperands = node->getSequence();
2443 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2444 glslangOperands[i]->traverse(this);
2445
2446 return false;
2447 }
2448 case glslang::EOpFunction:
2449 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002450 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002451 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002453 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 } else {
2455 handleFunctionEntry(node);
2456 }
2457 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002458 if (inEntryPoint)
2459 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002460 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002461 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002462 }
2463
2464 return true;
2465 case glslang::EOpParameters:
2466 // Parameters will have been consumed by EOpFunction processing, but not
2467 // the body, so we still visited the function node's children, making this
2468 // child redundant.
2469 return false;
2470 case glslang::EOpFunctionCall:
2471 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002472 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002473 if (node->isUserDefined())
2474 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002475 if (result) {
2476 builder.clearAccessChain();
2477 builder.setAccessChainRValue(result);
2478 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002479 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002480
2481 return false;
2482 }
2483 case glslang::EOpConstructMat2x2:
2484 case glslang::EOpConstructMat2x3:
2485 case glslang::EOpConstructMat2x4:
2486 case glslang::EOpConstructMat3x2:
2487 case glslang::EOpConstructMat3x3:
2488 case glslang::EOpConstructMat3x4:
2489 case glslang::EOpConstructMat4x2:
2490 case glslang::EOpConstructMat4x3:
2491 case glslang::EOpConstructMat4x4:
2492 case glslang::EOpConstructDMat2x2:
2493 case glslang::EOpConstructDMat2x3:
2494 case glslang::EOpConstructDMat2x4:
2495 case glslang::EOpConstructDMat3x2:
2496 case glslang::EOpConstructDMat3x3:
2497 case glslang::EOpConstructDMat3x4:
2498 case glslang::EOpConstructDMat4x2:
2499 case glslang::EOpConstructDMat4x3:
2500 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002501 case glslang::EOpConstructIMat2x2:
2502 case glslang::EOpConstructIMat2x3:
2503 case glslang::EOpConstructIMat2x4:
2504 case glslang::EOpConstructIMat3x2:
2505 case glslang::EOpConstructIMat3x3:
2506 case glslang::EOpConstructIMat3x4:
2507 case glslang::EOpConstructIMat4x2:
2508 case glslang::EOpConstructIMat4x3:
2509 case glslang::EOpConstructIMat4x4:
2510 case glslang::EOpConstructUMat2x2:
2511 case glslang::EOpConstructUMat2x3:
2512 case glslang::EOpConstructUMat2x4:
2513 case glslang::EOpConstructUMat3x2:
2514 case glslang::EOpConstructUMat3x3:
2515 case glslang::EOpConstructUMat3x4:
2516 case glslang::EOpConstructUMat4x2:
2517 case glslang::EOpConstructUMat4x3:
2518 case glslang::EOpConstructUMat4x4:
2519 case glslang::EOpConstructBMat2x2:
2520 case glslang::EOpConstructBMat2x3:
2521 case glslang::EOpConstructBMat2x4:
2522 case glslang::EOpConstructBMat3x2:
2523 case glslang::EOpConstructBMat3x3:
2524 case glslang::EOpConstructBMat3x4:
2525 case glslang::EOpConstructBMat4x2:
2526 case glslang::EOpConstructBMat4x3:
2527 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002528 case glslang::EOpConstructF16Mat2x2:
2529 case glslang::EOpConstructF16Mat2x3:
2530 case glslang::EOpConstructF16Mat2x4:
2531 case glslang::EOpConstructF16Mat3x2:
2532 case glslang::EOpConstructF16Mat3x3:
2533 case glslang::EOpConstructF16Mat3x4:
2534 case glslang::EOpConstructF16Mat4x2:
2535 case glslang::EOpConstructF16Mat4x3:
2536 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002537 isMatrix = true;
2538 // fall through
2539 case glslang::EOpConstructFloat:
2540 case glslang::EOpConstructVec2:
2541 case glslang::EOpConstructVec3:
2542 case glslang::EOpConstructVec4:
2543 case glslang::EOpConstructDouble:
2544 case glslang::EOpConstructDVec2:
2545 case glslang::EOpConstructDVec3:
2546 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002547 case glslang::EOpConstructFloat16:
2548 case glslang::EOpConstructF16Vec2:
2549 case glslang::EOpConstructF16Vec3:
2550 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002551 case glslang::EOpConstructBool:
2552 case glslang::EOpConstructBVec2:
2553 case glslang::EOpConstructBVec3:
2554 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002555 case glslang::EOpConstructInt8:
2556 case glslang::EOpConstructI8Vec2:
2557 case glslang::EOpConstructI8Vec3:
2558 case glslang::EOpConstructI8Vec4:
2559 case glslang::EOpConstructUint8:
2560 case glslang::EOpConstructU8Vec2:
2561 case glslang::EOpConstructU8Vec3:
2562 case glslang::EOpConstructU8Vec4:
2563 case glslang::EOpConstructInt16:
2564 case glslang::EOpConstructI16Vec2:
2565 case glslang::EOpConstructI16Vec3:
2566 case glslang::EOpConstructI16Vec4:
2567 case glslang::EOpConstructUint16:
2568 case glslang::EOpConstructU16Vec2:
2569 case glslang::EOpConstructU16Vec3:
2570 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002571 case glslang::EOpConstructInt:
2572 case glslang::EOpConstructIVec2:
2573 case glslang::EOpConstructIVec3:
2574 case glslang::EOpConstructIVec4:
2575 case glslang::EOpConstructUint:
2576 case glslang::EOpConstructUVec2:
2577 case glslang::EOpConstructUVec3:
2578 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002579 case glslang::EOpConstructInt64:
2580 case glslang::EOpConstructI64Vec2:
2581 case glslang::EOpConstructI64Vec3:
2582 case glslang::EOpConstructI64Vec4:
2583 case glslang::EOpConstructUint64:
2584 case glslang::EOpConstructU64Vec2:
2585 case glslang::EOpConstructU64Vec3:
2586 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002587 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002588 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002589 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002590 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002591 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002592 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002593 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002594 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002595 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002596 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002597 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002598 else if (node->getOp() == glslang::EOpConstructStruct ||
2599 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2600 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002601 std::vector<spv::Id> constituents;
2602 for (int c = 0; c < (int)arguments.size(); ++c)
2603 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002604 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002605 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002606 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002607 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002608 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002609
2610 builder.clearAccessChain();
2611 builder.setAccessChainRValue(constructed);
2612
2613 return false;
2614 }
2615
2616 // These six are component-wise compares with component-wise results.
2617 // Forward on to createBinaryOperation(), requesting a vector result.
2618 case glslang::EOpLessThan:
2619 case glslang::EOpGreaterThan:
2620 case glslang::EOpLessThanEqual:
2621 case glslang::EOpGreaterThanEqual:
2622 case glslang::EOpVectorEqual:
2623 case glslang::EOpVectorNotEqual:
2624 {
2625 // Map the operation to a binary
2626 binOp = node->getOp();
2627 reduceComparison = false;
2628 switch (node->getOp()) {
2629 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2630 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2631 default: binOp = node->getOp(); break;
2632 }
2633
2634 break;
2635 }
2636 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002637 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002638 binOp = glslang::EOpMul;
2639 break;
2640 case glslang::EOpOuterProduct:
2641 // two vectors multiplied to make a matrix
2642 binOp = glslang::EOpOuterProduct;
2643 break;
2644 case glslang::EOpDot:
2645 {
qining25262b32016-05-06 17:25:16 -04002646 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002647 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002648 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002649 binOp = glslang::EOpMul;
2650 break;
2651 }
2652 case glslang::EOpMod:
2653 // when an aggregate, this is the floating-point mod built-in function,
2654 // which can be emitted by the one in createBinaryOperation()
2655 binOp = glslang::EOpMod;
2656 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002657
John Kessenich140f3df2015-06-26 16:58:36 -06002658 case glslang::EOpEmitVertex:
2659 case glslang::EOpEndPrimitive:
2660 case glslang::EOpBarrier:
2661 case glslang::EOpMemoryBarrier:
2662 case glslang::EOpMemoryBarrierAtomicCounter:
2663 case glslang::EOpMemoryBarrierBuffer:
2664 case glslang::EOpMemoryBarrierImage:
2665 case glslang::EOpMemoryBarrierShared:
2666 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002667 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002668 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002669 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002670 case glslang::EOpWorkgroupMemoryBarrier:
2671 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002672 case glslang::EOpSubgroupBarrier:
2673 case glslang::EOpSubgroupMemoryBarrier:
2674 case glslang::EOpSubgroupMemoryBarrierBuffer:
2675 case glslang::EOpSubgroupMemoryBarrierImage:
2676 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002677 noReturnValue = true;
2678 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2679 break;
2680
John Kessenich426394d2015-07-23 10:22:48 -06002681 case glslang::EOpAtomicAdd:
2682 case glslang::EOpAtomicMin:
2683 case glslang::EOpAtomicMax:
2684 case glslang::EOpAtomicAnd:
2685 case glslang::EOpAtomicOr:
2686 case glslang::EOpAtomicXor:
2687 case glslang::EOpAtomicExchange:
2688 case glslang::EOpAtomicCompSwap:
2689 atomic = true;
2690 break;
2691
John Kesseniche5eee8f2019-10-18 01:03:11 -06002692#ifndef GLSLANG_WEB
2693 case glslang::EOpAtomicStore:
2694 noReturnValue = true;
2695 // fallthrough
2696 case glslang::EOpAtomicLoad:
2697 atomic = true;
2698 break;
2699
John Kessenich0d0c6d32017-07-23 16:08:26 -06002700 case glslang::EOpAtomicCounterAdd:
2701 case glslang::EOpAtomicCounterSubtract:
2702 case glslang::EOpAtomicCounterMin:
2703 case glslang::EOpAtomicCounterMax:
2704 case glslang::EOpAtomicCounterAnd:
2705 case glslang::EOpAtomicCounterOr:
2706 case glslang::EOpAtomicCounterXor:
2707 case glslang::EOpAtomicCounterExchange:
2708 case glslang::EOpAtomicCounterCompSwap:
2709 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2710 builder.addCapability(spv::CapabilityAtomicStorageOps);
2711 atomic = true;
2712 break;
2713
Ian Romanickb3bd4022019-01-21 08:57:25 -08002714 case glslang::EOpAbsDifference:
2715 case glslang::EOpAddSaturate:
2716 case glslang::EOpSubSaturate:
2717 case glslang::EOpAverage:
2718 case glslang::EOpAverageRounded:
2719 case glslang::EOpMul32x16:
2720 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2721 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2722 binOp = node->getOp();
2723 break;
2724
Daniel Kochdb32b242020-03-17 20:42:47 -04002725 case glslang::EOpIgnoreIntersection:
2726 case glslang::EOpTerminateRay:
2727 case glslang::EOpTrace:
2728 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002729 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2730 noReturnValue = true;
2731 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002732 case glslang::EOpRayQueryInitialize:
2733 case glslang::EOpRayQueryTerminate:
2734 case glslang::EOpRayQueryGenerateIntersection:
2735 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002736 builder.addExtension("SPV_KHR_ray_query");
2737 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002738 noReturnValue = true;
2739 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002740 case glslang::EOpRayQueryProceed:
2741 case glslang::EOpRayQueryGetIntersectionType:
2742 case glslang::EOpRayQueryGetRayTMin:
2743 case glslang::EOpRayQueryGetRayFlags:
2744 case glslang::EOpRayQueryGetIntersectionT:
2745 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2746 case glslang::EOpRayQueryGetIntersectionInstanceId:
2747 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2748 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2749 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2750 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2751 case glslang::EOpRayQueryGetIntersectionFrontFace:
2752 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2753 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2754 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2755 case glslang::EOpRayQueryGetWorldRayDirection:
2756 case glslang::EOpRayQueryGetWorldRayOrigin:
2757 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2758 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2759 builder.addExtension("SPV_KHR_ray_query");
2760 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2761 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002762 case glslang::EOpCooperativeMatrixLoad:
2763 case glslang::EOpCooperativeMatrixStore:
2764 noReturnValue = true;
2765 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002766 case glslang::EOpBeginInvocationInterlock:
2767 case glslang::EOpEndInvocationInterlock:
2768 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2769 noReturnValue = true;
2770 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002771#endif
Chao Chen3c366992018-09-19 11:41:59 -07002772
Jeff Bolz04d73732019-05-31 13:06:01 -05002773 case glslang::EOpDebugPrintf:
2774 noReturnValue = true;
2775 break;
2776
John Kessenich140f3df2015-06-26 16:58:36 -06002777 default:
2778 break;
2779 }
2780
2781 //
2782 // See if it maps to a regular operation.
2783 //
John Kessenich140f3df2015-06-26 16:58:36 -06002784 if (binOp != glslang::EOpNull) {
2785 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2786 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2787 assert(left && right);
2788
2789 builder.clearAccessChain();
2790 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002791 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002792
2793 builder.clearAccessChain();
2794 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002795 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002796
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002797 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002798 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002799 TranslateNoContractionDecoration(node->getType().getQualifier()),
2800 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002801 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002802 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002803 left->getType().getBasicType(), reduceComparison);
2804
2805 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002806 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002807 builder.clearAccessChain();
2808 builder.setAccessChainRValue(result);
2809
2810 return false;
2811 }
2812
John Kessenich426394d2015-07-23 10:22:48 -06002813 //
2814 // Create the list of operands.
2815 //
John Kessenich140f3df2015-06-26 16:58:36 -06002816 glslang::TIntermSequence& glslangOperands = node->getSequence();
2817 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002818 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002819 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002820 // special case l-value operands; there are just a few
2821 bool lvalue = false;
2822 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002823 case glslang::EOpModf:
2824 if (arg == 1)
2825 lvalue = true;
2826 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002827
Torosdagli06c2eee2020-03-19 11:09:57 -04002828 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002829 case glslang::EOpRayQueryTerminate:
2830 case glslang::EOpRayQueryConfirmIntersection:
2831 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002832 case glslang::EOpRayQueryGenerateIntersection:
2833 case glslang::EOpRayQueryGetIntersectionType:
2834 case glslang::EOpRayQueryGetIntersectionT:
2835 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2836 case glslang::EOpRayQueryGetIntersectionInstanceId:
2837 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2838 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2839 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2840 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2841 case glslang::EOpRayQueryGetIntersectionFrontFace:
2842 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2843 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2844 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2845 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2846 if (arg == 0)
2847 lvalue = true;
2848 break;
2849
John Kesseniche5eee8f2019-10-18 01:03:11 -06002850 case glslang::EOpAtomicAdd:
2851 case glslang::EOpAtomicMin:
2852 case glslang::EOpAtomicMax:
2853 case glslang::EOpAtomicAnd:
2854 case glslang::EOpAtomicOr:
2855 case glslang::EOpAtomicXor:
2856 case glslang::EOpAtomicExchange:
2857 case glslang::EOpAtomicCompSwap:
2858 if (arg == 0)
2859 lvalue = true;
2860 break;
2861
John Kessenicha28f7a72019-08-06 07:00:58 -06002862#ifndef GLSLANG_WEB
2863 case glslang::EOpFrexp:
2864 if (arg == 1)
2865 lvalue = true;
2866 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002867 case glslang::EOpInterpolateAtSample:
2868 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002869 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002870 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002871 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002872
2873 // Does it need a swizzle inversion? If so, evaluation is inverted;
2874 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002875 // That is, we transform
2876 //
2877 // interpolate(v.zy) -> interpolate(v).zy
2878 //
John Kessenichecba76f2017-01-06 00:34:48 -07002879 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002880 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002881 invertedType = convertGlslangToSpvType(
2882 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002883 }
Rex Xu7a26c172015-12-08 17:12:09 +08002884 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002885 case glslang::EOpAtomicLoad:
2886 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002887 case glslang::EOpAtomicCounterAdd:
2888 case glslang::EOpAtomicCounterSubtract:
2889 case glslang::EOpAtomicCounterMin:
2890 case glslang::EOpAtomicCounterMax:
2891 case glslang::EOpAtomicCounterAnd:
2892 case glslang::EOpAtomicCounterOr:
2893 case glslang::EOpAtomicCounterXor:
2894 case glslang::EOpAtomicCounterExchange:
2895 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002896 if (arg == 0)
2897 lvalue = true;
2898 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002899 case glslang::EOpAddCarry:
2900 case glslang::EOpSubBorrow:
2901 if (arg == 2)
2902 lvalue = true;
2903 break;
2904 case glslang::EOpUMulExtended:
2905 case glslang::EOpIMulExtended:
2906 if (arg >= 2)
2907 lvalue = true;
2908 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002909 case glslang::EOpCooperativeMatrixLoad:
2910 if (arg == 0 || arg == 1)
2911 lvalue = true;
2912 break;
2913 case glslang::EOpCooperativeMatrixStore:
2914 if (arg == 1)
2915 lvalue = true;
2916 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002917#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002918 default:
2919 break;
2920 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002921 builder.clearAccessChain();
2922 if (invertedType != spv::NoType && arg == 0)
2923 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2924 else
2925 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002926
John Kessenichb9197c82019-08-11 07:41:45 -06002927#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002928 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2929 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2930
2931 if (arg == 1) {
2932 // fold "element" parameter into the access chain
2933 spv::Builder::AccessChain save = builder.getAccessChain();
2934 builder.clearAccessChain();
2935 glslangOperands[2]->traverse(this);
2936
2937 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2938
2939 builder.setAccessChain(save);
2940
2941 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002942 builder.accessChainPush(elementId,
2943 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2944 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002945
2946 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2947 unsigned int alignment = builder.getAccessChain().alignment;
2948
2949 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2950 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2951 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2952 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2953 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002954 if (builder.getStorageClass(builder.getAccessChain().base) ==
2955 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002956 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2957 }
2958
2959 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2960
2961 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2962 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2963 }
2964
John Kessenich8985fc92020-03-03 10:25:07 -07002965 if (memoryAccess &
2966 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2967 memoryAccessOperands.push_back(spv::IdImmediate(true,
2968 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002969 }
2970 } else if (arg == 2) {
2971 continue;
2972 }
2973 }
John Kessenichb9197c82019-08-11 07:41:45 -06002974#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002975
John Kessenichbbbd9a22020-03-03 07:21:37 -07002976 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002977 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002978 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2979 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2980 // reduce to a simple access chain. So, we need a temporary vector to
2981 // receive the result, and must later swizzle that into the original
2982 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002983 complexLvalues.push_back(builder.getAccessChain());
2984 temporaryLvalues.push_back(builder.createVariable(spv::StorageClassFunction,
2985 builder.accessChainGetInferredType(), "swizzleTemp"));
2986 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002987 } else {
2988 operands.push_back(builder.accessChainGetLValue());
2989 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002990 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2991 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2992 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002993 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002994 glslang::TOperator glslangOp = node->getOp();
2995 if (arg == 1 &&
2996 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2997 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2998 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2999 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
3001 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
3002 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3003 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3004 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3005 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3006 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3007 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3008 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3009 )) {
3010 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3011 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3012 }
3013 else {
3014 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3015 }
3016
John Kesseniche485c7a2017-05-31 18:50:53 -06003017 }
John Kessenich140f3df2015-06-26 16:58:36 -06003018 }
John Kessenich426394d2015-07-23 10:22:48 -06003019
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003020 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003021#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003022 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3023 std::vector<spv::IdImmediate> idImmOps;
3024
3025 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3026 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3027 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3028 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3029 // get the pointee type
3030 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3031 assert(builder.isCooperativeMatrixType(typeId));
3032 // do the op
3033 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3034 // store the result to the pointer (out param 'm')
3035 builder.createStore(result, operands[0]);
3036 result = 0;
3037 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3038 std::vector<spv::IdImmediate> idImmOps;
3039
3040 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3041 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3042 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3043 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3044 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3045
3046 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3047 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003048 } else
3049#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003050 if (atomic) {
3051 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003052 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3053 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003054 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3055 if (!nonSemanticDebugPrintf) {
3056 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3057 }
3058 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3059 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003060 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003061 // Pass through to generic operations.
3062 switch (glslangOperands.size()) {
3063 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003064 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003065 break;
3066 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003067 {
3068 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003069 TranslateNoContractionDecoration(node->getType().getQualifier()),
3070 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003071 result = createUnaryOperation(
3072 node->getOp(), decorations,
3073 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003074 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003075 }
John Kessenich426394d2015-07-23 10:22:48 -06003076 break;
3077 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003078 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003079 break;
3080 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003081
John Kessenichbbbd9a22020-03-03 07:21:37 -07003082 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003083 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003084
3085 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3086 builder.setAccessChain(complexLvalues[i]);
3087 builder.accessChainStore(builder.createLoad(temporaryLvalues[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003088 }
John Kessenich140f3df2015-06-26 16:58:36 -06003089 }
3090
3091 if (noReturnValue)
3092 return false;
3093
3094 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003095 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003096 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003097 } else {
3098 builder.clearAccessChain();
3099 builder.setAccessChainRValue(result);
3100 return false;
3101 }
3102}
3103
John Kessenich433e9ff2017-01-26 20:31:11 -07003104// This path handles both if-then-else and ?:
3105// The if-then-else has a node type of void, while
3106// ?: has either a void or a non-void node type
3107//
3108// Leaving the result, when not void:
3109// GLSL only has r-values as the result of a :?, but
3110// if we have an l-value, that can be more efficient if it will
3111// become the base of a complex r-value expression, because the
3112// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003113bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3114{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003115 // see if OpSelect can handle it
3116 const auto isOpSelectable = [&]() {
3117 if (node->getBasicType() == glslang::EbtVoid)
3118 return false;
3119 // OpSelect can do all other types starting with SPV 1.4
3120 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3121 // pre-1.4, only scalars and vectors can be handled
3122 if ((!node->getType().isScalar() && !node->getType().isVector()))
3123 return false;
3124 }
3125 return true;
3126 };
3127
John Kessenich4bee5312018-02-20 21:29:05 -07003128 // See if it simple and safe, or required, to execute both sides.
3129 // Crucially, side effects must be either semantically required or avoided,
3130 // and there are performance trade-offs.
3131 // Return true if required or a good idea (and safe) to execute both sides,
3132 // false otherwise.
3133 const auto bothSidesPolicy = [&]() -> bool {
3134 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003135 if (node->getTrueBlock() == nullptr ||
3136 node->getFalseBlock() == nullptr)
3137 return false;
3138
John Kessenich4bee5312018-02-20 21:29:05 -07003139 // required? (unless we write additional code to look for side effects
3140 // and make performance trade-offs if none are present)
3141 if (!node->getShortCircuit())
3142 return true;
3143
3144 // if not required to execute both, decide based on performance/practicality...
3145
John Kessenich0c1e71a2019-01-10 18:23:06 +07003146 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003147 return false;
3148
John Kessenich433e9ff2017-01-26 20:31:11 -07003149 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3150 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3151
3152 // return true if a single operand to ? : is okay for OpSelect
3153 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003154 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003155 };
3156
3157 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3158 operandOkay(node->getFalseBlock()->getAsTyped());
3159 };
3160
John Kessenich4bee5312018-02-20 21:29:05 -07003161 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3162 // emit the condition before doing anything with selection
3163 node->getCondition()->traverse(this);
3164 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3165
3166 // Find a way of executing both sides and selecting the right result.
3167 const auto executeBothSides = [&]() -> void {
3168 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003169 node->getTrueBlock()->traverse(this);
3170 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3171 node->getFalseBlock()->traverse(this);
3172 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3173
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003174 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003175
John Kessenich4bee5312018-02-20 21:29:05 -07003176 // done if void
3177 if (node->getBasicType() == glslang::EbtVoid)
3178 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003179
John Kessenich4bee5312018-02-20 21:29:05 -07003180 // emit code to select between trueValue and falseValue
3181
3182 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003183 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003184 // Emit OpSelect for this selection.
3185
3186 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003187 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3188 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003189 condition = builder.smearScalar(spv::NoPrecision, condition,
3190 builder.makeVectorType(builder.makeBoolType(),
3191 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003192 }
John Kessenich4bee5312018-02-20 21:29:05 -07003193
3194 // OpSelect
3195 result = builder.createTriOp(spv::OpSelect,
3196 convertGlslangToSpvType(node->getType()), condition,
3197 trueValue, falseValue);
3198
3199 builder.clearAccessChain();
3200 builder.setAccessChainRValue(result);
3201 } else {
3202 // We need control flow to select the result.
3203 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3204 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3205
3206 // Selection control:
3207 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3208
3209 // make an "if" based on the value created by the condition
3210 spv::Builder::If ifBuilder(condition, control, builder);
3211
3212 // emit the "then" statement
3213 builder.createStore(trueValue, result);
3214 ifBuilder.makeBeginElse();
3215 // emit the "else" statement
3216 builder.createStore(falseValue, result);
3217
3218 // finish off the control flow
3219 ifBuilder.makeEndIf();
3220
3221 builder.clearAccessChain();
3222 builder.setAccessChainLValue(result);
3223 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003224 };
3225
John Kessenich4bee5312018-02-20 21:29:05 -07003226 // Execute the one side needed, as per the condition
3227 const auto executeOneSide = [&]() {
3228 // Always emit control flow.
3229 if (node->getBasicType() != glslang::EbtVoid)
3230 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003231
John Kessenich4bee5312018-02-20 21:29:05 -07003232 // Selection control:
3233 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3234
3235 // make an "if" based on the value created by the condition
3236 spv::Builder::If ifBuilder(condition, control, builder);
3237
3238 // emit the "then" statement
3239 if (node->getTrueBlock() != nullptr) {
3240 node->getTrueBlock()->traverse(this);
3241 if (result != spv::NoResult)
3242 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3243 }
3244
3245 if (node->getFalseBlock() != nullptr) {
3246 ifBuilder.makeBeginElse();
3247 // emit the "else" statement
3248 node->getFalseBlock()->traverse(this);
3249 if (result != spv::NoResult)
3250 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3251 }
3252
3253 // finish off the control flow
3254 ifBuilder.makeEndIf();
3255
3256 if (result != spv::NoResult) {
3257 builder.clearAccessChain();
3258 builder.setAccessChainLValue(result);
3259 }
3260 };
3261
3262 // Try for OpSelect (or a requirement to execute both sides)
3263 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003264 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3265 if (node->getType().getQualifier().isSpecConstant())
3266 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003267 executeBothSides();
3268 } else
3269 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003270
3271 return false;
3272}
3273
3274bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3275{
3276 // emit and get the condition before doing anything with switch
3277 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003278 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003279
Rex Xu57e65922017-07-04 23:23:40 +08003280 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003281 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003282
John Kessenich140f3df2015-06-26 16:58:36 -06003283 // browse the children to sort out code segments
3284 int defaultSegment = -1;
3285 std::vector<TIntermNode*> codeSegments;
3286 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3287 std::vector<int> caseValues;
3288 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3289 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3290 TIntermNode* child = *c;
3291 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003292 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003293 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003294 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003295 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3296 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003297 } else
3298 codeSegments.push_back(child);
3299 }
3300
qining25262b32016-05-06 17:25:16 -04003301 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003302 // statements between the last case and the end of the switch statement
3303 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3304 (int)codeSegments.size() == defaultSegment)
3305 codeSegments.push_back(nullptr);
3306
3307 // make the switch statement
3308 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003309 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3310 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003311
3312 // emit all the code in the segments
3313 breakForLoop.push(false);
3314 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3315 builder.nextSwitchSegment(segmentBlocks, s);
3316 if (codeSegments[s])
3317 codeSegments[s]->traverse(this);
3318 else
3319 builder.addSwitchBreak();
3320 }
3321 breakForLoop.pop();
3322
3323 builder.endSwitch(segmentBlocks);
3324
3325 return false;
3326}
3327
3328void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3329{
3330 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003331 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003332
3333 builder.clearAccessChain();
3334 builder.setAccessChainRValue(constant);
3335}
3336
3337bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3338{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003339 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003340 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003341
3342 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003343 std::vector<unsigned int> operands;
3344 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003345
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003346 // Spec requires back edges to target header blocks, and every header block
3347 // must dominate its merge block. Make a header block first to ensure these
3348 // conditions are met. By definition, it will contain OpLoopMerge, followed
3349 // by a block-ending branch. But we don't want to put any other body/test
3350 // instructions in it, since the body/test may have arbitrary instructions,
3351 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003352 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003353 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003354 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003355 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003356 spv::Block& test = builder.makeNewBlock();
3357 builder.createBranch(&test);
3358
3359 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003360 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003361 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003362 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3363
3364 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003365 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003366 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003367 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003368 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003369 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003370
3371 builder.setBuildPoint(&blocks.continue_target);
3372 if (node->getTerminal())
3373 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003374 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003375 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003376 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 builder.createBranch(&blocks.body);
3378
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003379 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003380 builder.setBuildPoint(&blocks.body);
3381 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003382 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003383 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003384 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003385
3386 builder.setBuildPoint(&blocks.continue_target);
3387 if (node->getTerminal())
3388 node->getTerminal()->traverse(this);
3389 if (node->getTest()) {
3390 node->getTest()->traverse(this);
3391 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003392 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003393 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003394 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003395 // TODO: unless there was a break/return/discard instruction
3396 // somewhere in the body, this is an infinite loop, so we should
3397 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003398 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003399 }
John Kessenich140f3df2015-06-26 16:58:36 -06003400 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003401 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003402 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003403 return false;
3404}
3405
3406bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3407{
3408 if (node->getExpression())
3409 node->getExpression()->traverse(this);
3410
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003411 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003412
John Kessenich140f3df2015-06-26 16:58:36 -06003413 switch (node->getFlowOp()) {
3414 case glslang::EOpKill:
3415 builder.makeDiscard();
3416 break;
3417 case glslang::EOpBreak:
3418 if (breakForLoop.top())
3419 builder.createLoopExit();
3420 else
3421 builder.addSwitchBreak();
3422 break;
3423 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003424 builder.createLoopContinue();
3425 break;
3426 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003427 if (node->getExpression()) {
3428 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3429 spv::Id returnId = accessChainLoad(glslangReturnType);
3430 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3431 builder.clearAccessChain();
3432 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3433 builder.setAccessChainLValue(copyId);
3434 multiTypeStore(glslangReturnType, returnId);
3435 returnId = builder.createLoad(copyId);
3436 }
3437 builder.makeReturn(false, returnId);
3438 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003439 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003440
3441 builder.clearAccessChain();
3442 break;
3443
John Kessenichb9197c82019-08-11 07:41:45 -06003444#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003445 case glslang::EOpDemote:
3446 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3447 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3448 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3449 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003450#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003451
John Kessenich140f3df2015-06-26 16:58:36 -06003452 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003453 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003454 break;
3455 }
3456
3457 return false;
3458}
3459
John Kessenich9c14f772019-06-17 08:38:35 -06003460spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003461{
qining25262b32016-05-06 17:25:16 -04003462 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003463 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003464 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003465 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003466 spv::Id result = createSpvConstant(*node);
3467 if (result != spv::NoResult)
3468 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003469 }
3470
3471 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003472 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003473 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3474 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003475
John Kessenichb9197c82019-08-11 07:41:45 -06003476 const bool contains16BitType = node->getType().contains16BitFloat() ||
3477 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003478 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003479 switch (storageClass) {
3480 case spv::StorageClassInput:
3481 case spv::StorageClassOutput:
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 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003484 break;
John Kessenich18310872018-05-14 22:08:53 -06003485 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003486 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003487 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3488 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003489 else
3490 builder.addCapability(spv::CapabilityStorageUniform16);
3491 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003492#ifndef GLSLANG_WEB
3493 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003494 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003495 builder.addCapability(spv::CapabilityStoragePushConstant16);
3496 break;
John Kessenich18310872018-05-14 22:08:53 -06003497 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003498 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003499 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003500 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3501 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003502#endif
John Kessenich18310872018-05-14 22:08:53 -06003503 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003504 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003505 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003506 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003507 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003508 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003509 }
3510 }
Rex Xuf89ad982017-04-07 23:22:33 +08003511
John Kessenichb9197c82019-08-11 07:41:45 -06003512 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003513 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003514 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003515 builder.addCapability(spv::CapabilityStoragePushConstant8);
3516 } else if (storageClass == spv::StorageClassUniform) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003517 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003518 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003519 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003520 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003521 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003522 } else {
3523 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003524 }
3525 }
3526
John Kessenich140f3df2015-06-26 16:58:36 -06003527 const char* name = node->getName().c_str();
3528 if (glslang::IsAnonymous(name))
3529 name = "";
3530
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003531 spv::Id initializer = spv::NoResult;
3532
3533 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3534 !node->getConstArray().empty()) {
3535 int nextConst = 0;
3536 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3537 node->getConstArray(),
3538 nextConst,
3539 false /* specConst */);
3540 }
3541
3542 return builder.createVariable(storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003543}
3544
3545// Return type Id of the sampled type.
3546spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3547{
3548 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003549 case glslang::EbtInt: return builder.makeIntType(32);
3550 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003551 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003552#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003553 case glslang::EbtFloat16:
3554 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3555 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3556 return builder.makeFloatType(16);
3557#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003558 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003559 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003560 return builder.makeFloatType(32);
3561 }
3562}
3563
John Kessenich8c8505c2016-07-26 12:50:38 -06003564// If node is a swizzle operation, return the type that should be used if
3565// the swizzle base is first consumed by another operation, before the swizzle
3566// is applied.
3567spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3568{
John Kessenichecba76f2017-01-06 00:34:48 -07003569 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003570 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3571 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3572 else
3573 return spv::NoType;
3574}
3575
3576// When inverting a swizzle with a parent op, this function
3577// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003578spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3579 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003580{
3581 std::vector<unsigned> swizzle;
3582 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3583 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3584}
3585
John Kessenich8c8505c2016-07-26 12:50:38 -06003586// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3587void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3588{
3589 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3590 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3591 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3592}
3593
John Kessenich3ac051e2015-12-20 11:29:16 -07003594// Convert from a glslang type to an SPV type, by calling into a
3595// recursive version of this function. This establishes the inherited
3596// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003597spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003598{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003599 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003600}
3601
3602// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003603// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003604// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003605spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003606 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3607 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003608{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003609 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003610
3611 switch (type.getBasicType()) {
3612 case glslang::EbtVoid:
3613 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003614 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003615 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003616 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003617 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3618 // a 32-bit int where non-0 means true.
3619 if (explicitLayout != glslang::ElpNone)
3620 spvType = builder.makeUintType(32);
3621 else
3622 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003623 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003624 case glslang::EbtInt:
3625 spvType = builder.makeIntType(32);
3626 break;
3627 case glslang::EbtUint:
3628 spvType = builder.makeUintType(32);
3629 break;
3630 case glslang::EbtFloat:
3631 spvType = builder.makeFloatType(32);
3632 break;
3633#ifndef GLSLANG_WEB
3634 case glslang::EbtDouble:
3635 spvType = builder.makeFloatType(64);
3636 break;
3637 case glslang::EbtFloat16:
3638 spvType = builder.makeFloatType(16);
3639 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003640 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003641 spvType = builder.makeIntType(8);
3642 break;
3643 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003644 spvType = builder.makeUintType(8);
3645 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003646 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003647 spvType = builder.makeIntType(16);
3648 break;
3649 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003650 spvType = builder.makeUintType(16);
3651 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003652 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003653 spvType = builder.makeIntType(64);
3654 break;
3655 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003656 spvType = builder.makeUintType(64);
3657 break;
John Kessenich426394d2015-07-23 10:22:48 -06003658 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003659 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003660 spvType = builder.makeUintType(32);
3661 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003662 case glslang::EbtAccStruct:
3663 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003664 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003665 case glslang::EbtRayQuery:
3666 spvType = builder.makeRayQueryType();
3667 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003668 case glslang::EbtReference:
3669 {
3670 // Make the forward pointer, then recurse to convert the structure type, then
3671 // patch up the forward pointer with a real pointer type.
3672 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3673 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3674 forwardPointers[type.getReferentType()] = forwardId;
3675 }
3676 spvType = forwardPointers[type.getReferentType()];
3677 if (!forwardReferenceOnly) {
3678 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3679 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3680 forwardPointers[type.getReferentType()],
3681 referentType);
3682 }
3683 }
3684 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003686 case glslang::EbtSampler:
3687 {
3688 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003689 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003690 spvType = builder.makeSamplerType();
3691 } else {
3692 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003693 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3694 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3695 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3696 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003697 // already has both image and sampler, make the combined type
3698 spvType = builder.makeSampledImageType(spvType);
3699 }
John Kessenich55e7d112015-11-15 21:33:39 -07003700 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003701 }
John Kessenich140f3df2015-06-26 16:58:36 -06003702 break;
3703 case glslang::EbtStruct:
3704 case glslang::EbtBlock:
3705 {
3706 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003707 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003708
3709 // Try to share structs for different layouts, but not yet for other
3710 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003711 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003712 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003713 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003714 break;
3715
3716 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003717 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003718 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003719 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003720 }
3721 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003722 case glslang::EbtString:
3723 // no type used for OpString
3724 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003726 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003727 break;
3728 }
3729
3730 if (type.isMatrix())
3731 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3732 else {
3733 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3734 if (type.getVectorSize() > 1)
3735 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3736 }
3737
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003738 if (type.isCoopMat()) {
3739 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3740 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3741 if (type.getBasicType() == glslang::EbtFloat16)
3742 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003743 if (type.getBasicType() == glslang::EbtUint8 ||
3744 type.getBasicType() == glslang::EbtInt8) {
3745 builder.addCapability(spv::CapabilityInt8);
3746 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003747
3748 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3749 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3750 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3751
3752 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3753 }
3754
John Kessenich140f3df2015-06-26 16:58:36 -06003755 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003756 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3757
John Kessenichc9a80832015-09-12 12:17:44 -06003758 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003759 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003760 // We need to decorate array strides for types needing explicit layout, except blocks.
3761 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003762 // Use a dummy glslang type for querying internal strides of
3763 // arrays of arrays, but using just a one-dimensional array.
3764 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003765 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3766 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003767
3768 // Will compute the higher-order strides here, rather than making a whole
3769 // pile of types and doing repetitive recursion on their contents.
3770 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3771 }
John Kessenichf8842e52016-01-04 19:22:56 -07003772
3773 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003774 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003775 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003776 if (stride > 0)
3777 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003778 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003779 }
3780 } else {
3781 // single-dimensional array, and don't yet have stride
3782
John Kessenichf8842e52016-01-04 19:22:56 -07003783 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003784 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3785 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003786 }
John Kessenich31ed4832015-09-09 17:51:38 -06003787
John Kessenichead86222018-03-28 18:01:20 -06003788 // Do the outer dimension, which might not be known for a runtime-sized array.
3789 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3790 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003791 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003792 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003793#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003794 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003795 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003796 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3797 }
John Kessenichb9197c82019-08-11 07:41:45 -06003798#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003799 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003800 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003801 if (stride > 0)
3802 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003803 }
3804
3805 return spvType;
3806}
3807
John Kessenich0e737842017-03-24 18:38:16 -06003808// TODO: this functionality should exist at a higher level, in creating the AST
3809//
3810// Identify interface members that don't have their required extension turned on.
3811//
3812bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3813{
John Kessenicha28f7a72019-08-06 07:00:58 -06003814#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003815 auto& extensions = glslangIntermediate->getRequestedExtensions();
3816
Rex Xubcf291a2017-03-29 23:01:36 +08003817 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3818 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3819 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003820 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3821 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3822 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003823
3824 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3825 if (member.getFieldName() == "gl_ViewportMask" &&
3826 extensions.find("GL_NV_viewport_array2") == extensions.end())
3827 return true;
3828 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3829 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3830 return true;
3831 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3832 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3833 return true;
3834 }
3835#endif
John Kessenich0e737842017-03-24 18:38:16 -06003836
3837 return false;
3838};
3839
John Kessenich6090df02016-06-30 21:18:02 -06003840// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3841// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3842// Mutually recursive with convertGlslangToSpvType().
3843spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3844 const glslang::TTypeList* glslangMembers,
3845 glslang::TLayoutPacking explicitLayout,
3846 const glslang::TQualifier& qualifier)
3847{
3848 // Create a vector of struct types for SPIR-V to consume
3849 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003850 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3851 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003852 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003853 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3854 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3855 if (glslangMember.hiddenMember()) {
3856 ++memberDelta;
3857 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003858 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003859 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003860 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003861 if (filterMember(glslangMember)) {
3862 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003863 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003864 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003865 }
Roy05a5b532020-01-03 16:21:34 +08003866 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003867 }
John Kessenich6090df02016-06-30 21:18:02 -06003868 // modify just this child's view of the qualifier
3869 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3870 InheritQualifiers(memberQualifier, qualifier);
3871
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003872 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003873 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003874 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003875
3876 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003877 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3878 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003879
3880 // Make forward pointers for any pointer members, and create a list of members to
3881 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003882 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003883 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3884 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3885 }
3886 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003887 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3888 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003889 } else {
3890 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003891 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3892 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003893 }
John Kessenich6090df02016-06-30 21:18:02 -06003894 }
3895 }
3896
3897 // Make the SPIR-V type
3898 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003899 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003900 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3901
3902 // Decorate it
3903 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3904
John Kessenichd72f4882019-01-16 14:55:37 +07003905 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003906 auto it = deferredForwardPointers[i];
3907 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3908 }
3909
John Kessenich6090df02016-06-30 21:18:02 -06003910 return spvType;
3911}
3912
3913void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3914 const glslang::TTypeList* glslangMembers,
3915 glslang::TLayoutPacking explicitLayout,
3916 const glslang::TQualifier& qualifier,
3917 spv::Id spvType)
3918{
3919 // Name and decorate the non-hidden members
3920 int offset = -1;
3921 int locationOffset = 0; // for use within the members of this struct
3922 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3923 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3924 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003925 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003926 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003927 if (filterMember(glslangMember))
3928 continue;
3929 }
John Kessenich6090df02016-06-30 21:18:02 -06003930
3931 // modify just this child's view of the qualifier
3932 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3933 InheritQualifiers(memberQualifier, qualifier);
3934
3935 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003936 if (member < 0)
3937 continue;
3938
3939 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3940 builder.addMemberDecoration(spvType, member,
3941 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3942 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3943 // Add interpolation and auxiliary storage decorations only to
3944 // top-level members of Input and Output storage classes
3945 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3946 type.getQualifier().storage == glslang::EvqVaryingOut) {
3947 if (type.getBasicType() == glslang::EbtBlock ||
3948 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3949 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3950 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003951#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003952 addMeshNVDecoration(spvType, member, memberQualifier);
3953#endif
John Kessenich6090df02016-06-30 21:18:02 -06003954 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003955 }
3956 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003957
John Kessenichb9197c82019-08-11 07:41:45 -06003958#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003959 if (type.getBasicType() == glslang::EbtBlock &&
3960 qualifier.storage == glslang::EvqBuffer) {
3961 // Add memory decorations only to top-level members of shader storage block
3962 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003963 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003964 for (unsigned int i = 0; i < memory.size(); ++i)
3965 builder.addMemberDecoration(spvType, member, memory[i]);
3966 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003967
John Kessenichb9197c82019-08-11 07:41:45 -06003968#endif
John Kessenich6090df02016-06-30 21:18:02 -06003969
John Kessenich5d610ee2018-03-07 18:05:55 -07003970 // Location assignment was already completed correctly by the front end,
3971 // just track whether a member needs to be decorated.
3972 // Ignore member locations if the container is an array, as that's
3973 // ill-specified and decisions have been made to not allow this.
3974 if (! type.isArray() && memberQualifier.hasLocation())
3975 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003976
John Kessenich5d610ee2018-03-07 18:05:55 -07003977 if (qualifier.hasLocation()) // track for upcoming inheritance
3978 locationOffset += glslangIntermediate->computeTypeLocationSize(
3979 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003980
John Kessenich5d610ee2018-03-07 18:05:55 -07003981 // component, XFB, others
3982 if (glslangMember.getQualifier().hasComponent())
3983 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3984 glslangMember.getQualifier().layoutComponent);
3985 if (glslangMember.getQualifier().hasXfbOffset())
3986 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3987 glslangMember.getQualifier().layoutXfbOffset);
3988 else if (explicitLayout != glslang::ElpNone) {
3989 // figure out what to do with offset, which is accumulating
3990 int nextOffset;
3991 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3992 if (offset >= 0)
3993 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3994 offset = nextOffset;
3995 }
John Kessenich6090df02016-06-30 21:18:02 -06003996
John Kessenich5d610ee2018-03-07 18:05:55 -07003997 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3998 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3999 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06004000
John Kessenich5d610ee2018-03-07 18:05:55 -07004001 // built-in variable decorations
4002 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4003 if (builtIn != spv::BuiltInMax)
4004 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004005
John Kessenichb9197c82019-08-11 07:41:45 -06004006#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004007 // nonuniform
4008 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4009
John Kessenichead86222018-03-28 18:01:20 -06004010 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4011 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4012 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4013 memberQualifier.semanticName);
4014 }
4015
John Kessenich5d610ee2018-03-07 18:05:55 -07004016 if (builtIn == spv::BuiltInLayer) {
4017 // SPV_NV_viewport_array2 extension
4018 if (glslangMember.getQualifier().layoutViewportRelative){
4019 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4020 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4021 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004022 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004023 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4024 builder.addMemberDecoration(spvType, member,
4025 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4026 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4027 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4028 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004029 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004030 }
4031 if (glslangMember.getQualifier().layoutPassthrough) {
4032 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4033 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4034 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4035 }
chaoc771d89f2017-01-13 01:10:53 -08004036#endif
John Kessenich6090df02016-06-30 21:18:02 -06004037 }
4038
4039 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004040 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4041 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004042}
4043
John Kessenich6c292d32016-02-15 20:58:50 -07004044// Turn the expression forming the array size into an id.
4045// This is not quite trivial, because of specialization constants.
4046// Sometimes, a raw constant is turned into an Id, and sometimes
4047// a specialization constant expression is.
4048spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4049{
4050 // First, see if this is sized with a node, meaning a specialization constant:
4051 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4052 if (specNode != nullptr) {
4053 builder.clearAccessChain();
4054 specNode->traverse(this);
4055 return accessChainLoad(specNode->getAsTyped()->getType());
4056 }
qining25262b32016-05-06 17:25:16 -04004057
John Kessenich6c292d32016-02-15 20:58:50 -07004058 // Otherwise, need a compile-time (front end) size, get it:
4059 int size = arraySizes.getDimSize(dim);
4060 assert(size > 0);
4061 return builder.makeUintConstant(size);
4062}
4063
John Kessenich103bef92016-02-08 21:38:15 -07004064// Wrap the builder's accessChainLoad to:
4065// - localize handling of RelaxedPrecision
4066// - use the SPIR-V inferred type instead of another conversion of the glslang type
4067// (avoids unnecessary work and possible type punning for structures)
4068// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004069spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4070{
John Kessenich103bef92016-02-08 21:38:15 -07004071 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004072
4073 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4074 coherentFlags |= TranslateCoherent(type);
4075
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004076 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004077 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004078
John Kessenich5611c6d2018-04-05 11:25:02 -06004079 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004080 TranslateNonUniformDecoration(type.getQualifier()),
4081 nominalTypeId,
4082 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4083 TranslateMemoryScope(coherentFlags),
4084 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004085
4086 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004087 if (type.getBasicType() == glslang::EbtBool) {
4088 if (builder.isScalarType(nominalTypeId)) {
4089 // Conversion for bool
4090 spv::Id boolType = builder.makeBoolType();
4091 if (nominalTypeId != boolType)
4092 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4093 } else if (builder.isVectorType(nominalTypeId)) {
4094 // Conversion for bvec
4095 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4096 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4097 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004098 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4099 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004100 }
4101 }
John Kessenich103bef92016-02-08 21:38:15 -07004102
4103 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004104}
4105
Rex Xu27253232016-02-23 17:51:09 +08004106// Wrap the builder's accessChainStore to:
4107// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004108//
4109// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004110void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4111{
4112 // Need to convert to abstract types when necessary
4113 if (type.getBasicType() == glslang::EbtBool) {
4114 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4115
4116 if (builder.isScalarType(nominalTypeId)) {
4117 // Conversion for bool
4118 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004119 if (nominalTypeId != boolType) {
4120 // keep these outside arguments, for determinant order-of-evaluation
4121 spv::Id one = builder.makeUintConstant(1);
4122 spv::Id zero = builder.makeUintConstant(0);
4123 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4124 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004125 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004126 } else if (builder.isVectorType(nominalTypeId)) {
4127 // Conversion for bvec
4128 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4129 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004130 if (nominalTypeId != bvecType) {
4131 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004132 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4133 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4134 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004135 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004136 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4137 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004138 }
4139 }
4140
Jeff Bolz36831c92018-09-05 10:11:41 -05004141 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4142 coherentFlags |= TranslateCoherent(type);
4143
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004144 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004145 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004146
Jeff Bolz36831c92018-09-05 10:11:41 -05004147 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004148 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4149 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004150 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004151}
4152
John Kessenich4bf71552016-09-02 11:20:21 -06004153// For storing when types match at the glslang level, but not might match at the
4154// SPIR-V level.
4155//
4156// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004157// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004158// as in a member-decorated way.
4159//
4160// NOTE: This function can handle any store request; if it's not special it
4161// simplifies to a simple OpStore.
4162//
4163// Implicitly uses the existing builder.accessChain as the storage target.
4164void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4165{
John Kessenichb3e24e42016-09-11 12:33:43 -06004166 // we only do the complex path here if it's an aggregate
4167 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004168 accessChainStore(type, rValue);
4169 return;
4170 }
4171
John Kessenichb3e24e42016-09-11 12:33:43 -06004172 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004173 spv::Id rType = builder.getTypeId(rValue);
4174 spv::Id lValue = builder.accessChainGetLValue();
4175 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4176 if (lType == rType) {
4177 accessChainStore(type, rValue);
4178 return;
4179 }
4180
John Kessenichb3e24e42016-09-11 12:33:43 -06004181 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004182 // where the two types were the same type in GLSL. This requires member
4183 // by member copy, recursively.
4184
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004185 // SPIR-V 1.4 added an instruction to do help do this.
4186 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4187 // However, bool in uniform space is changed to int, so
4188 // OpCopyLogical does not work for that.
4189 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4190 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4191 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4192 if (lBool == rBool) {
4193 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4194 accessChainStore(type, logicalCopy);
4195 return;
4196 }
4197 }
4198
John Kessenichb3e24e42016-09-11 12:33:43 -06004199 // If an array, copy element by element.
4200 if (type.isArray()) {
4201 glslang::TType glslangElementType(type, 0);
4202 spv::Id elementRType = builder.getContainedTypeId(rType);
4203 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4204 // get the source member
4205 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004206
John Kessenichb3e24e42016-09-11 12:33:43 -06004207 // set up the target storage
4208 builder.clearAccessChain();
4209 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004210 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4211 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004212
John Kessenichb3e24e42016-09-11 12:33:43 -06004213 // store the member
4214 multiTypeStore(glslangElementType, elementRValue);
4215 }
4216 } else {
4217 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004218
John Kessenichb3e24e42016-09-11 12:33:43 -06004219 // loop over structure members
4220 const glslang::TTypeList& members = *type.getStruct();
4221 for (int m = 0; m < (int)members.size(); ++m) {
4222 const glslang::TType& glslangMemberType = *members[m].type;
4223
4224 // get the source member
4225 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4226 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4227
4228 // set up the target storage
4229 builder.clearAccessChain();
4230 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004231 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4232 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004233
4234 // store the member
4235 multiTypeStore(glslangMemberType, memberRValue);
4236 }
John Kessenich4bf71552016-09-02 11:20:21 -06004237 }
4238}
4239
John Kessenichf85e8062015-12-19 13:57:10 -07004240// Decide whether or not this type should be
4241// decorated with offsets and strides, and if so
4242// whether std140 or std430 rules should be applied.
4243glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004244{
John Kessenichf85e8062015-12-19 13:57:10 -07004245 // has to be a block
4246 if (type.getBasicType() != glslang::EbtBlock)
4247 return glslang::ElpNone;
4248
Chao Chen3c366992018-09-19 11:41:59 -07004249 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004250 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004251 type.getQualifier().storage != glslang::EvqBuffer &&
4252 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004253 return glslang::ElpNone;
4254
4255 // return the layout to use
4256 switch (type.getQualifier().layoutPacking) {
4257 case glslang::ElpStd140:
4258 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004259 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004260 return type.getQualifier().layoutPacking;
4261 default:
4262 return glslang::ElpNone;
4263 }
John Kessenich31ed4832015-09-09 17:51:38 -06004264}
4265
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004266// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004267int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4268 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004269{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004270 int size;
John Kessenich49987892015-12-29 17:11:44 -07004271 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004272 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4273 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004274
4275 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004276}
4277
John Kessenich49987892015-12-29 17:11:44 -07004278// 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 -07004279// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004280int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4281 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004282{
John Kessenich49987892015-12-29 17:11:44 -07004283 glslang::TType elementType;
4284 elementType.shallowCopy(matrixType);
4285 elementType.clearArraySizes();
4286
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004287 int size;
John Kessenich49987892015-12-29 17:11:44 -07004288 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004289 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4290 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004291
4292 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004293}
4294
John Kessenich5e4b1242015-08-06 22:53:06 -06004295// Given a member type of a struct, realign the current offset for it, and compute
4296// the next (not yet aligned) offset for the next member, which will get aligned
4297// on the next call.
4298// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4299// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4300// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004301void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4302 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004303{
4304 // this will get a positive value when deemed necessary
4305 nextOffset = -1;
4306
John Kessenich5e4b1242015-08-06 22:53:06 -06004307 // override anything in currentOffset with user-set offset
4308 if (memberType.getQualifier().hasOffset())
4309 currentOffset = memberType.getQualifier().layoutOffset;
4310
4311 // It could be that current linker usage in glslang updated all the layoutOffset,
4312 // in which case the following code does not matter. But, that's not quite right
4313 // once cross-compilation unit GLSL validation is done, as the original user
4314 // settings are needed in layoutOffset, and then the following will come into play.
4315
John Kessenichf85e8062015-12-19 13:57:10 -07004316 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004317 if (! memberType.getQualifier().hasOffset())
4318 currentOffset = -1;
4319
4320 return;
4321 }
4322
John Kessenichf85e8062015-12-19 13:57:10 -07004323 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004324 if (currentOffset < 0)
4325 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004326
John Kessenich5e4b1242015-08-06 22:53:06 -06004327 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4328 // but possibly not yet correctly aligned.
4329
4330 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004331 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004332 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4333 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004334
4335 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004336 // TODO: make this consistent in early phases of code:
4337 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4338 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4339 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004340 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004341 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004342 int dummySize;
4343 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4344 if (componentAlignment <= 4)
4345 memberAlignment = componentAlignment;
4346 }
4347
4348 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004349 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004350
4351 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004352 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4353 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004354 glslang::RoundToPow2(currentOffset, 16);
4355
John Kessenich5e4b1242015-08-06 22:53:06 -06004356 nextOffset = currentOffset + memberSize;
4357}
4358
David Netoa901ffe2016-06-08 14:11:40 +01004359void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004360{
David Netoa901ffe2016-06-08 14:11:40 +01004361 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4362 switch (glslangBuiltIn)
4363 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004364 case glslang::EbvPointSize:
4365#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004366 case glslang::EbvClipDistance:
4367 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004368 case glslang::EbvViewportMaskNV:
4369 case glslang::EbvSecondaryPositionNV:
4370 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004371 case glslang::EbvPositionPerViewNV:
4372 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004373 case glslang::EbvTaskCountNV:
4374 case glslang::EbvPrimitiveCountNV:
4375 case glslang::EbvPrimitiveIndicesNV:
4376 case glslang::EbvClipDistancePerViewNV:
4377 case glslang::EbvCullDistancePerViewNV:
4378 case glslang::EbvLayerPerViewNV:
4379 case glslang::EbvMeshViewCountNV:
4380 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004381#endif
David Netoa901ffe2016-06-08 14:11:40 +01004382 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4383 // Alternately, we could just call this for any glslang built-in, since the
4384 // capability already guards against duplicates.
4385 TranslateBuiltInDecoration(glslangBuiltIn, false);
4386 break;
4387 default:
4388 // Capabilities were already generated when the struct was declared.
4389 break;
4390 }
John Kessenichebb50532016-05-16 19:22:05 -06004391}
4392
John Kessenich6fccb3c2016-09-19 16:01:41 -06004393bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004394{
John Kessenicheee9d532016-09-19 18:09:30 -06004395 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004396}
4397
John Kessenichd41993d2017-09-10 15:21:05 -06004398// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004399// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4400// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004401bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004402{
John Kessenich6a14f782017-12-04 02:48:10 -07004403 assert(qualifier == glslang::EvqIn ||
4404 qualifier == glslang::EvqOut ||
4405 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004406 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004407 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004408 return qualifier != glslang::EvqConstReadOnly &&
4409 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004410}
4411
4412// Is parameter pass-by-original?
4413bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4414 bool implicitThisParam)
4415{
4416 if (implicitThisParam) // implicit this
4417 return true;
4418 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004419 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004420 return paramType.containsOpaque() || // sampler, etc.
4421 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4422}
4423
John Kessenich140f3df2015-06-26 16:58:36 -06004424// Make all the functions, skeletally, without actually visiting their bodies.
4425void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4426{
John Kessenich8985fc92020-03-03 10:25:07 -07004427 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4428 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004429 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4430 if (paramPrecision != spv::NoPrecision)
4431 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004432 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004433 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004434 // Original and non-writable params pass the pointer directly and
4435 // use restrict/aliased, others are stored to a pointer in Function
4436 // memory and use RestrictPointer/AliasedPointer.
4437 if (originalParam(type.getQualifier().storage, type, false) ||
4438 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004439 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4440 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004441 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004442 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4443 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004444 }
4445 }
John Kessenichfad62972017-07-18 02:35:46 -06004446 };
4447
John Kessenich140f3df2015-06-26 16:58:36 -06004448 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4449 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004450 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004451 continue;
4452
4453 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004454 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004455 //
qining25262b32016-05-06 17:25:16 -04004456 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004457 // function. What it is an address of varies:
4458 //
John Kessenich4bf71552016-09-02 11:20:21 -06004459 // - "in" parameters not marked as "const" can be written to without modifying the calling
4460 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004461 //
4462 // - "const in" parameters can just be the r-value, as no writes need occur.
4463 //
John Kessenich4bf71552016-09-02 11:20:21 -06004464 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4465 // 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 -06004466
4467 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004468 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004469 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4470
John Kessenich155d3512019-08-08 23:29:20 -06004471#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004472 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4473 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004474#else
4475 bool implicitThis = false;
4476#endif
John Kessenich37789792017-03-21 23:56:40 -06004477
John Kessenichfad62972017-07-18 02:35:46 -06004478 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004479 for (int p = 0; p < (int)parameters.size(); ++p) {
4480 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4481 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004482 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004483 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004484 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004485 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4486 else
John Kessenich4bf71552016-09-02 11:20:21 -06004487 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004488 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004489 paramTypes.push_back(typeId);
4490 }
4491
4492 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004493 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4494 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004495 glslFunction->getName().c_str(), paramTypes,
4496 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004497 if (implicitThis)
4498 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004499
4500 // Track function to emit/call later
4501 functionMap[glslFunction->getName().c_str()] = function;
4502
4503 // Set the parameter id's
4504 for (int p = 0; p < (int)parameters.size(); ++p) {
4505 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4506 // give a name too
4507 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004508
4509 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004510 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004511 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004512 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004513 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004514 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004515 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004516 }
4517 }
4518}
4519
4520// Process all the initializers, while skipping the functions and link objects
4521void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4522{
4523 builder.setBuildPoint(shaderEntry->getLastBlock());
4524 for (int i = 0; i < (int)initializers.size(); ++i) {
4525 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004526 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4527 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004528
4529 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004530 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004531 initializer->traverse(this);
4532 }
4533 }
4534}
4535
4536// Process all the functions, while skipping initializers.
4537void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4538{
4539 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4540 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004541 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004542 node->traverse(this);
4543 }
4544}
4545
4546void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4547{
qining25262b32016-05-06 17:25:16 -04004548 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004549 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004550 currentFunction = functionMap[node->getName().c_str()];
4551 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004552 builder.setBuildPoint(functionBlock);
4553}
4554
John Kessenich8985fc92020-03-03 10:25:07 -07004555void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4556 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004557{
Rex Xufc618912015-09-09 16:42:49 +08004558 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004559
4560 glslang::TSampler sampler = {};
4561 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004562#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004563 bool f16ShadowCompare = false;
4564#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004565 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004566 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4567 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004568#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004569 f16ShadowCompare = sampler.shadow &&
4570 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004571#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004572 }
4573
John Kessenich140f3df2015-06-26 16:58:36 -06004574 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4575 builder.clearAccessChain();
4576 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004577
John Kessenicha28f7a72019-08-06 07:00:58 -06004578#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004579 // Special case l-value operands
4580 bool lvalue = false;
4581 switch (node.getOp()) {
4582 case glslang::EOpImageAtomicAdd:
4583 case glslang::EOpImageAtomicMin:
4584 case glslang::EOpImageAtomicMax:
4585 case glslang::EOpImageAtomicAnd:
4586 case glslang::EOpImageAtomicOr:
4587 case glslang::EOpImageAtomicXor:
4588 case glslang::EOpImageAtomicExchange:
4589 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004590 case glslang::EOpImageAtomicLoad:
4591 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004592 if (i == 0)
4593 lvalue = true;
4594 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004595 case glslang::EOpSparseImageLoad:
4596 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4597 lvalue = true;
4598 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004599 case glslang::EOpSparseTexture:
4600 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4601 lvalue = true;
4602 break;
4603 case glslang::EOpSparseTextureClamp:
4604 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4605 lvalue = true;
4606 break;
4607 case glslang::EOpSparseTextureLod:
4608 case glslang::EOpSparseTextureOffset:
4609 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4610 lvalue = true;
4611 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004612 case glslang::EOpSparseTextureFetch:
4613 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4614 lvalue = true;
4615 break;
4616 case glslang::EOpSparseTextureFetchOffset:
4617 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4618 lvalue = true;
4619 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004620 case glslang::EOpSparseTextureLodOffset:
4621 case glslang::EOpSparseTextureGrad:
4622 case glslang::EOpSparseTextureOffsetClamp:
4623 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4624 lvalue = true;
4625 break;
4626 case glslang::EOpSparseTextureGradOffset:
4627 case glslang::EOpSparseTextureGradClamp:
4628 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4629 lvalue = true;
4630 break;
4631 case glslang::EOpSparseTextureGradOffsetClamp:
4632 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4633 lvalue = true;
4634 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004635 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004636 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4637 lvalue = true;
4638 break;
4639 case glslang::EOpSparseTextureGatherOffset:
4640 case glslang::EOpSparseTextureGatherOffsets:
4641 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4642 lvalue = true;
4643 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004644 case glslang::EOpSparseTextureGatherLod:
4645 if (i == 3)
4646 lvalue = true;
4647 break;
4648 case glslang::EOpSparseTextureGatherLodOffset:
4649 case glslang::EOpSparseTextureGatherLodOffsets:
4650 if (i == 4)
4651 lvalue = true;
4652 break;
Rex Xu129799a2017-07-05 17:23:28 +08004653 case glslang::EOpSparseImageLoadLod:
4654 if (i == 3)
4655 lvalue = true;
4656 break;
Chao Chen3a137962018-09-19 11:41:27 -07004657 case glslang::EOpImageSampleFootprintNV:
4658 if (i == 4)
4659 lvalue = true;
4660 break;
4661 case glslang::EOpImageSampleFootprintClampNV:
4662 case glslang::EOpImageSampleFootprintLodNV:
4663 if (i == 5)
4664 lvalue = true;
4665 break;
4666 case glslang::EOpImageSampleFootprintGradNV:
4667 if (i == 6)
4668 lvalue = true;
4669 break;
4670 case glslang::EOpImageSampleFootprintGradClampNV:
4671 if (i == 7)
4672 lvalue = true;
4673 break;
Rex Xufc618912015-09-09 16:42:49 +08004674 default:
4675 break;
4676 }
4677
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004678 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004679 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004680 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4681 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4682 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004683#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004684 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004685 }
4686}
4687
John Kessenichfc51d282015-08-19 13:34:18 -06004688void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004689{
John Kessenichfc51d282015-08-19 13:34:18 -06004690 builder.clearAccessChain();
4691 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004692 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004693}
John Kessenich140f3df2015-06-26 16:58:36 -06004694
John Kessenichfc51d282015-08-19 13:34:18 -06004695spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4696{
John Kesseniche485c7a2017-05-31 18:50:53 -06004697 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004698 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004699
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004700 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004701
John Kessenichfc51d282015-08-19 13:34:18 -06004702 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004703
John Kessenichf43c7392019-03-31 10:51:57 -06004704 const glslang::TType &imageType = node->getAsAggregate()
4705 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4706 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004707 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004708#ifdef GLSLANG_WEB
4709 const bool f16ShadowCompare = false;
4710#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004711 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004712 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4713 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004714#endif
4715
John Kessenichf43c7392019-03-31 10:51:57 -06004716 const auto signExtensionMask = [&]() {
4717 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4718 if (sampler.type == glslang::EbtUint)
4719 return spv::ImageOperandsZeroExtendMask;
4720 else if (sampler.type == glslang::EbtInt)
4721 return spv::ImageOperandsSignExtendMask;
4722 }
4723 return spv::ImageOperandsMaskNone;
4724 };
4725
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004726 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4727
John Kessenichfc51d282015-08-19 13:34:18 -06004728 std::vector<spv::Id> arguments;
4729 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004730 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004731 else
4732 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004733 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004734
4735 spv::Builder::TextureParameters params = { };
4736 params.sampler = arguments[0];
4737
Rex Xu04db3f52015-09-16 11:44:02 +08004738 glslang::TCrackedTextureOp cracked;
4739 node->crackTexture(sampler, cracked);
4740
amhagan05506bb2017-06-13 16:53:02 -04004741 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004742
John Kessenichfc51d282015-08-19 13:34:18 -06004743 // Check for queries
4744 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004745 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4746 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004747 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004748
John Kessenichfc51d282015-08-19 13:34:18 -06004749 switch (node->getOp()) {
4750 case glslang::EOpImageQuerySize:
4751 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004752 if (arguments.size() > 1) {
4753 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004754 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004755 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004756 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004757#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004758 case glslang::EOpImageQuerySamples:
4759 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004760 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004761 case glslang::EOpTextureQueryLod:
4762 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004763 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004764 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004765 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004766 case glslang::EOpSparseTexelsResident:
4767 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004768#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004769 default:
4770 assert(0);
4771 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004772 }
John Kessenich140f3df2015-06-26 16:58:36 -06004773 }
4774
LoopDawg4425f242018-02-18 11:40:01 -07004775 int components = node->getType().getVectorSize();
4776
4777 if (node->getOp() == glslang::EOpTextureFetch) {
4778 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4779 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4780 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4781 // here around e.g. which ones return scalars or other types.
4782 components = 4;
4783 }
4784
4785 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4786
4787 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4788
Rex Xufc618912015-09-09 16:42:49 +08004789 // Check for image functions other than queries
4790 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004791 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004792 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004793 spv::IdImmediate image = { true, *(opIt++) };
4794 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004795
4796 // Handle subpass operations
4797 // TODO: GLSL should change to have the "MS" only on the type rather than the
4798 // built-in function.
4799 if (cracked.subpass) {
4800 // add on the (0,0) coordinate
4801 spv::Id zero = builder.makeIntConstant(0);
4802 std::vector<spv::Id> comps;
4803 comps.push_back(zero);
4804 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004805 spv::IdImmediate coord = { true,
4806 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4807 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004808 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4809 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004810 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004811 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4812 }
4813 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004814 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004815 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004816 spv::IdImmediate imageOperand = { true, *(opIt++) };
4817 operands.push_back(imageOperand);
4818 }
John Kessenich6c292d32016-02-15 20:58:50 -07004819 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004820 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4821 builder.setPrecision(result, precision);
4822 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004823 }
4824
John Kessenich149afc32018-08-14 13:31:43 -06004825 spv::IdImmediate coord = { true, *(opIt++) };
4826 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004827 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004828 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004829 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004830 mask = mask | spv::ImageOperandsSampleMask;
4831 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004832 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004833 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4834 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004835 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004836 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004837 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4838 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004839 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004840 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004841 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4842 operands.push_back(imageOperands);
4843 }
4844 if (mask & spv::ImageOperandsSampleMask) {
4845 spv::IdImmediate imageOperand = { true, *opIt++ };
4846 operands.push_back(imageOperand);
4847 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004848 if (mask & spv::ImageOperandsLodMask) {
4849 spv::IdImmediate imageOperand = { true, *opIt++ };
4850 operands.push_back(imageOperand);
4851 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004852 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004853 spv::IdImmediate imageOperand = { true,
4854 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004855 operands.push_back(imageOperand);
4856 }
4857
John Kessenich149afc32018-08-14 13:31:43 -06004858 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004859 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004860
John Kessenich149afc32018-08-14 13:31:43 -06004861 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004862 builder.setPrecision(result[0], precision);
4863
4864 // If needed, add a conversion constructor to the proper size.
4865 if (components != node->getType().getVectorSize())
4866 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4867
4868 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004869 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004870
Jeff Bolz36831c92018-09-05 10:11:41 -05004871 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004872 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004873 spv::IdImmediate texel = { true, *(opIt + 1) };
4874 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004875 } else {
4876 spv::IdImmediate texel = { true, *opIt };
4877 operands.push_back(texel);
4878 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004879
4880 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004881 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004882 mask = mask | spv::ImageOperandsSampleMask;
4883 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004884 if (cracked.lod) {
4885 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4886 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4887 mask = mask | spv::ImageOperandsLodMask;
4888 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004889 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4890 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004891 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004892 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004893 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4894 operands.push_back(imageOperands);
4895 }
4896 if (mask & spv::ImageOperandsSampleMask) {
4897 spv::IdImmediate imageOperand = { true, *opIt++ };
4898 operands.push_back(imageOperand);
4899 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004900 if (mask & spv::ImageOperandsLodMask) {
4901 spv::IdImmediate imageOperand = { true, *opIt++ };
4902 operands.push_back(imageOperand);
4903 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004904 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004905 spv::IdImmediate imageOperand = { true,
4906 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004907 operands.push_back(imageOperand);
4908 }
4909
John Kessenich56bab042015-09-16 10:54:31 -06004910 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004911 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004912 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004913 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004914 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4915 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004916 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004917 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004918 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4919
Jeff Bolz36831c92018-09-05 10:11:41 -05004920 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004921 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004922 mask = mask | spv::ImageOperandsSampleMask;
4923 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004924 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004925 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4926 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4927
Jeff Bolz36831c92018-09-05 10:11:41 -05004928 mask = mask | spv::ImageOperandsLodMask;
4929 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004930 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4931 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004932 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004933 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004934 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004935 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004936 }
4937 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004938 spv::IdImmediate imageOperand = { true, *opIt++ };
4939 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004940 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004941 if (mask & spv::ImageOperandsLodMask) {
4942 spv::IdImmediate imageOperand = { true, *opIt++ };
4943 operands.push_back(imageOperand);
4944 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004945 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004946 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4947 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004948 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004949 }
4950
4951 // Create the return type that was a special structure
4952 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004953 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004954 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4955 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4956
4957 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4958
4959 // Decode the return type
4960 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4961 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004962 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004963 // Process image atomic operations
4964
4965 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4966 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004967 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004968 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004969 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004970
Jeff Bolz36831c92018-09-05 10:11:41 -05004971 spv::Id resultTypeId;
4972 // imageAtomicStore has a void return type so base the pointer type on
4973 // the type of the value operand.
4974 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004975 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004976 } else {
4977 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4978 }
John Kessenich56bab042015-09-16 10:54:31 -06004979 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004980 if (imageType.getQualifier().nonUniform) {
4981 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4982 }
Rex Xufc618912015-09-09 16:42:49 +08004983
4984 std::vector<spv::Id> operands;
4985 operands.push_back(pointer);
4986 for (; opIt != arguments.end(); ++opIt)
4987 operands.push_back(*opIt);
4988
John Kessenich8985fc92020-03-03 10:25:07 -07004989 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4990 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004991 }
4992 }
4993
John Kessenicha28f7a72019-08-06 07:00:58 -06004994#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004995 // Check for fragment mask functions other than queries
4996 if (cracked.fragMask) {
4997 assert(sampler.ms);
4998
4999 auto opIt = arguments.begin();
5000 std::vector<spv::Id> operands;
5001
5002 // Extract the image if necessary
5003 if (builder.isSampledImage(params.sampler))
5004 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5005
5006 operands.push_back(params.sampler);
5007 ++opIt;
5008
5009 if (sampler.isSubpass()) {
5010 // add on the (0,0) coordinate
5011 spv::Id zero = builder.makeIntConstant(0);
5012 std::vector<spv::Id> comps;
5013 comps.push_back(zero);
5014 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005015 operands.push_back(builder.makeCompositeConstant(
5016 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005017 }
5018
5019 for (; opIt != arguments.end(); ++opIt)
5020 operands.push_back(*opIt);
5021
5022 spv::Op fragMaskOp = spv::OpNop;
5023 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5024 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5025 else if (node->getOp() == glslang::EOpFragmentFetch)
5026 fragMaskOp = spv::OpFragmentFetchAMD;
5027
5028 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5029 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5030 return builder.createOp(fragMaskOp, resultType(), operands);
5031 }
5032#endif
5033
Rex Xufc618912015-09-09 16:42:49 +08005034 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005035 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005036 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005037 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005038
John Kessenichfc51d282015-08-19 13:34:18 -06005039 // check for bias argument
5040 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005041 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005042 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005043 if (cracked.gather)
5044 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005045
5046 if (f16ShadowCompare)
5047 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005048 if (cracked.offset)
5049 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005050 else if (cracked.offsets)
5051 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005052 if (cracked.grad)
5053 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005054 if (cracked.lodClamp)
5055 ++nonBiasArgCount;
5056 if (sparse)
5057 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005058 if (imageFootprint)
5059 //Following three extra arguments
5060 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5061 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005062 if ((int)arguments.size() > nonBiasArgCount)
5063 bias = true;
5064 }
5065
John Kessenicha5c33d62016-06-02 23:45:21 -06005066 // See if the sampler param should really be just the SPV image part
5067 if (cracked.fetch) {
5068 // a fetch needs to have the image extracted first
5069 if (builder.isSampledImage(params.sampler))
5070 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5071 }
5072
John Kessenicha28f7a72019-08-06 07:00:58 -06005073#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005074 if (cracked.gather) {
5075 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5076 if (bias || cracked.lod ||
5077 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5078 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005079 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005080 }
5081 }
5082#endif
5083
John Kessenichfc51d282015-08-19 13:34:18 -06005084 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005085
John Kessenichfc51d282015-08-19 13:34:18 -06005086 params.coords = arguments[1];
5087 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005088 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005089
5090 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005091 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005092 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005093 ++extraArgs;
5094 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005095 params.Dref = arguments[2];
5096 ++extraArgs;
5097 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005098 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005099 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005100 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005101 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005102 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005103 dRefComp = builder.getNumComponents(params.coords) - 1;
5104 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005105 params.Dref = builder.createCompositeExtract(params.coords,
5106 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005107 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005108
5109 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005110 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005111 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005112 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005113 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5114 !(glslangIntermediate->getStage() == EShLangCompute &&
5115 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005116 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5117 noImplicitLod = true;
5118 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005119
5120 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005121 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005122 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005123 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005124 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005125
5126 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005127 if (cracked.grad) {
5128 params.gradX = arguments[2 + extraArgs];
5129 params.gradY = arguments[3 + extraArgs];
5130 extraArgs += 2;
5131 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005132
5133 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005134 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005135 params.offset = arguments[2 + extraArgs];
5136 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005137 } else if (cracked.offsets) {
5138 params.offsets = arguments[2 + extraArgs];
5139 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005140 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005141
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005142#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005143 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005144 if (cracked.lodClamp) {
5145 params.lodClamp = arguments[2 + extraArgs];
5146 ++extraArgs;
5147 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005148 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005149 if (sparse) {
5150 params.texelOut = arguments[2 + extraArgs];
5151 ++extraArgs;
5152 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005153 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005154 if (cracked.gather && ! sampler.shadow) {
5155 // default component is 0, if missing, otherwise an argument
5156 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005157 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005158 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005159 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005160 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005161 }
Chao Chen3a137962018-09-19 11:41:27 -07005162 spv::Id resultStruct = spv::NoResult;
5163 if (imageFootprint) {
5164 //Following three extra arguments
5165 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5166 params.granularity = arguments[2 + extraArgs];
5167 params.coarse = arguments[3 + extraArgs];
5168 resultStruct = arguments[4 + extraArgs];
5169 extraArgs += 3;
5170 }
5171#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005172 // bias
5173 if (bias) {
5174 params.bias = arguments[2 + extraArgs];
5175 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005176 }
John Kessenichfc51d282015-08-19 13:34:18 -06005177
John Kessenicha28f7a72019-08-06 07:00:58 -06005178#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005179 if (imageFootprint) {
5180 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5181 builder.addCapability(spv::CapabilityImageFootprintNV);
5182
5183
5184 //resultStructType(OpenGL type) contains 5 elements:
5185 //struct gl_TextureFootprint2DNV {
5186 // uvec2 anchor;
5187 // uvec2 offset;
5188 // uvec2 mask;
5189 // uint lod;
5190 // uint granularity;
5191 //};
5192 //or
5193 //struct gl_TextureFootprint3DNV {
5194 // uvec3 anchor;
5195 // uvec3 offset;
5196 // uvec2 mask;
5197 // uint lod;
5198 // uint granularity;
5199 //};
5200 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5201 assert(builder.isStructType(resultStructType));
5202
5203 //resType (SPIR-V type) contains 6 elements:
5204 //Member 0 must be a Boolean type scalar(LOD),
5205 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5206 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5207 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5208 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5209 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5210 std::vector<spv::Id> members;
5211 members.push_back(resultType());
5212 for (int i = 0; i < 5; i++) {
5213 members.push_back(builder.getContainedTypeId(resultStructType, i));
5214 }
5215 spv::Id resType = builder.makeStructType(members, "ResType");
5216
5217 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005218 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5219 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005220
5221 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5222 for (int i = 0; i < 5; i++) {
5223 builder.clearAccessChain();
5224 builder.setAccessChainLValue(resultStruct);
5225
5226 //Accessing to a struct we created, no coherent flag is set
5227 spv::Builder::AccessChain::CoherentFlags flags;
5228 flags.clear();
5229
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005230 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005231 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5232 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005233 }
5234 return builder.createCompositeExtract(res, resultType(), 0);
5235 }
5236#endif
5237
John Kessenich65336482016-06-16 14:06:26 -06005238 // projective component (might not to move)
5239 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5240 // are divided by the last component of P."
5241 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5242 // unused components will appear after all used components."
5243 if (cracked.proj) {
5244 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5245 int projTargetComp;
5246 switch (sampler.dim) {
5247 case glslang::Esd1D: projTargetComp = 1; break;
5248 case glslang::Esd2D: projTargetComp = 2; break;
5249 case glslang::EsdRect: projTargetComp = 2; break;
5250 default: projTargetComp = projSourceComp; break;
5251 }
5252 // copy the projective coordinate if we have to
5253 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005254 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005255 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005256 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005257 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005258 }
5259 }
5260
John Kessenichf8d1d742019-10-21 06:55:11 -06005261#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005262 // nonprivate
5263 if (imageType.getQualifier().nonprivate) {
5264 params.nonprivate = true;
5265 }
5266
5267 // volatile
5268 if (imageType.getQualifier().volatil) {
5269 params.volatil = true;
5270 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005271#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005272
St0fFa1184dd2018-04-09 21:08:14 +02005273 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005274 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5275 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005276 );
LoopDawg4425f242018-02-18 11:40:01 -07005277
5278 if (components != node->getType().getVectorSize())
5279 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5280
5281 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005282}
5283
5284spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5285{
5286 // Grab the function's pointer from the previously created function
5287 spv::Function* function = functionMap[node->getName().c_str()];
5288 if (! function)
5289 return 0;
5290
5291 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5292 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5293
5294 // See comments in makeFunctions() for details about the semantics for parameter passing.
5295 //
5296 // These imply we need a four step process:
5297 // 1. Evaluate the arguments
5298 // 2. Allocate and make copies of in, out, and inout arguments
5299 // 3. Make the call
5300 // 4. Copy back the results
5301
John Kessenichd3ed90b2018-05-04 11:43:03 -06005302 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005303 std::vector<spv::Builder::AccessChain> lValues;
5304 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005305 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005306 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005307 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005308 // build l-value
5309 builder.clearAccessChain();
5310 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005311 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005312 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005313 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005314 // save l-value
5315 lValues.push_back(builder.getAccessChain());
5316 } else {
5317 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005318 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005319 }
5320 }
5321
5322 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5323 // copy the original into that space.
5324 //
5325 // Also, build up the list of actual arguments to pass in for the call
5326 int lValueCount = 0;
5327 int rValueCount = 0;
5328 std::vector<spv::Id> spvArgs;
5329 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5330 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005331 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005332 builder.setAccessChain(lValues[lValueCount]);
5333 arg = builder.accessChainGetLValue();
5334 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005335 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005336 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005337 arg = builder.createVariable(spv::StorageClassFunction,
5338 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005339 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5340 // need to copy the input into output space
5341 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005342 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005343 builder.clearAccessChain();
5344 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005345 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005346 }
5347 ++lValueCount;
5348 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005349 // process r-value, which involves a copy for a type mismatch
5350 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5351 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5352 builder.clearAccessChain();
5353 builder.setAccessChainLValue(argCopy);
5354 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5355 arg = builder.createLoad(argCopy);
5356 } else
5357 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005358 ++rValueCount;
5359 }
5360 spvArgs.push_back(arg);
5361 }
5362
5363 // 3. Make the call.
5364 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005365 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005366
5367 // 4. Copy back out an "out" arguments.
5368 lValueCount = 0;
5369 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005370 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005371 ++lValueCount;
5372 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005373 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5374 spv::Id copy = builder.createLoad(spvArgs[a]);
5375 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005376 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005377 }
5378 ++lValueCount;
5379 }
5380 }
5381
5382 return result;
5383}
5384
5385// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005386spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005387 spv::Id typeId, spv::Id left, spv::Id right,
5388 glslang::TBasicType typeProxy, bool reduceComparison)
5389{
John Kessenich66011cb2018-03-06 16:12:04 -07005390 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5391 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005392 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005393
5394 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005395 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005396 bool comparison = false;
5397
5398 switch (op) {
5399 case glslang::EOpAdd:
5400 case glslang::EOpAddAssign:
5401 if (isFloat)
5402 binOp = spv::OpFAdd;
5403 else
5404 binOp = spv::OpIAdd;
5405 break;
5406 case glslang::EOpSub:
5407 case glslang::EOpSubAssign:
5408 if (isFloat)
5409 binOp = spv::OpFSub;
5410 else
5411 binOp = spv::OpISub;
5412 break;
5413 case glslang::EOpMul:
5414 case glslang::EOpMulAssign:
5415 if (isFloat)
5416 binOp = spv::OpFMul;
5417 else
5418 binOp = spv::OpIMul;
5419 break;
5420 case glslang::EOpVectorTimesScalar:
5421 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005422 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005423 if (builder.isVector(right))
5424 std::swap(left, right);
5425 assert(builder.isScalar(right));
5426 needMatchingVectors = false;
5427 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005428 } else if (isFloat)
5429 binOp = spv::OpFMul;
5430 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005431 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005432 break;
5433 case glslang::EOpVectorTimesMatrix:
5434 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005435 binOp = spv::OpVectorTimesMatrix;
5436 break;
5437 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005438 binOp = spv::OpMatrixTimesVector;
5439 break;
5440 case glslang::EOpMatrixTimesScalar:
5441 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005442 binOp = spv::OpMatrixTimesScalar;
5443 break;
5444 case glslang::EOpMatrixTimesMatrix:
5445 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005446 binOp = spv::OpMatrixTimesMatrix;
5447 break;
5448 case glslang::EOpOuterProduct:
5449 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005450 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005451 break;
5452
5453 case glslang::EOpDiv:
5454 case glslang::EOpDivAssign:
5455 if (isFloat)
5456 binOp = spv::OpFDiv;
5457 else if (isUnsigned)
5458 binOp = spv::OpUDiv;
5459 else
5460 binOp = spv::OpSDiv;
5461 break;
5462 case glslang::EOpMod:
5463 case glslang::EOpModAssign:
5464 if (isFloat)
5465 binOp = spv::OpFMod;
5466 else if (isUnsigned)
5467 binOp = spv::OpUMod;
5468 else
5469 binOp = spv::OpSMod;
5470 break;
5471 case glslang::EOpRightShift:
5472 case glslang::EOpRightShiftAssign:
5473 if (isUnsigned)
5474 binOp = spv::OpShiftRightLogical;
5475 else
5476 binOp = spv::OpShiftRightArithmetic;
5477 break;
5478 case glslang::EOpLeftShift:
5479 case glslang::EOpLeftShiftAssign:
5480 binOp = spv::OpShiftLeftLogical;
5481 break;
5482 case glslang::EOpAnd:
5483 case glslang::EOpAndAssign:
5484 binOp = spv::OpBitwiseAnd;
5485 break;
5486 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005487 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005488 binOp = spv::OpLogicalAnd;
5489 break;
5490 case glslang::EOpInclusiveOr:
5491 case glslang::EOpInclusiveOrAssign:
5492 binOp = spv::OpBitwiseOr;
5493 break;
5494 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005495 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 binOp = spv::OpLogicalOr;
5497 break;
5498 case glslang::EOpExclusiveOr:
5499 case glslang::EOpExclusiveOrAssign:
5500 binOp = spv::OpBitwiseXor;
5501 break;
5502 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005503 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005504 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005505 break;
5506
Ian Romanickb3bd4022019-01-21 08:57:25 -08005507 case glslang::EOpAbsDifference:
5508 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5509 break;
5510
5511 case glslang::EOpAddSaturate:
5512 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5513 break;
5514
5515 case glslang::EOpSubSaturate:
5516 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5517 break;
5518
5519 case glslang::EOpAverage:
5520 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5521 break;
5522
5523 case glslang::EOpAverageRounded:
5524 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5525 break;
5526
5527 case glslang::EOpMul32x16:
5528 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5529 break;
5530
John Kessenich140f3df2015-06-26 16:58:36 -06005531 case glslang::EOpLessThan:
5532 case glslang::EOpGreaterThan:
5533 case glslang::EOpLessThanEqual:
5534 case glslang::EOpGreaterThanEqual:
5535 case glslang::EOpEqual:
5536 case glslang::EOpNotEqual:
5537 case glslang::EOpVectorEqual:
5538 case glslang::EOpVectorNotEqual:
5539 comparison = true;
5540 break;
5541 default:
5542 break;
5543 }
5544
John Kessenich7c1aa102015-10-15 13:29:11 -06005545 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005546 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005547 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005548 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5549 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005550 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005551
5552 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005553 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005554 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005555
qining25262b32016-05-06 17:25:16 -04005556 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005557 decorations.addNoContraction(builder, result);
5558 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005559 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005560 }
5561
5562 if (! comparison)
5563 return 0;
5564
John Kessenich7c1aa102015-10-15 13:29:11 -06005565 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005566
John Kessenich4583b612016-08-07 19:14:22 -06005567 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005568 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5569 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005570 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005571 return result;
5572 }
John Kessenich140f3df2015-06-26 16:58:36 -06005573
5574 switch (op) {
5575 case glslang::EOpLessThan:
5576 if (isFloat)
5577 binOp = spv::OpFOrdLessThan;
5578 else if (isUnsigned)
5579 binOp = spv::OpULessThan;
5580 else
5581 binOp = spv::OpSLessThan;
5582 break;
5583 case glslang::EOpGreaterThan:
5584 if (isFloat)
5585 binOp = spv::OpFOrdGreaterThan;
5586 else if (isUnsigned)
5587 binOp = spv::OpUGreaterThan;
5588 else
5589 binOp = spv::OpSGreaterThan;
5590 break;
5591 case glslang::EOpLessThanEqual:
5592 if (isFloat)
5593 binOp = spv::OpFOrdLessThanEqual;
5594 else if (isUnsigned)
5595 binOp = spv::OpULessThanEqual;
5596 else
5597 binOp = spv::OpSLessThanEqual;
5598 break;
5599 case glslang::EOpGreaterThanEqual:
5600 if (isFloat)
5601 binOp = spv::OpFOrdGreaterThanEqual;
5602 else if (isUnsigned)
5603 binOp = spv::OpUGreaterThanEqual;
5604 else
5605 binOp = spv::OpSGreaterThanEqual;
5606 break;
5607 case glslang::EOpEqual:
5608 case glslang::EOpVectorEqual:
5609 if (isFloat)
5610 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005611 else if (isBool)
5612 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005613 else
5614 binOp = spv::OpIEqual;
5615 break;
5616 case glslang::EOpNotEqual:
5617 case glslang::EOpVectorNotEqual:
5618 if (isFloat)
5619 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005620 else if (isBool)
5621 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005622 else
5623 binOp = spv::OpINotEqual;
5624 break;
5625 default:
5626 break;
5627 }
5628
qining25262b32016-05-06 17:25:16 -04005629 if (binOp != spv::OpNop) {
5630 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005631 decorations.addNoContraction(builder, result);
5632 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005633 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005634 }
John Kessenich140f3df2015-06-26 16:58:36 -06005635
5636 return 0;
5637}
5638
John Kessenich04bb8a02015-12-12 12:28:14 -07005639//
5640// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5641// These can be any of:
5642//
5643// matrix * scalar
5644// scalar * matrix
5645// matrix * matrix linear algebraic
5646// matrix * vector
5647// vector * matrix
5648// matrix * matrix componentwise
5649// matrix op matrix op in {+, -, /}
5650// matrix op scalar op in {+, -, /}
5651// scalar op matrix op in {+, -, /}
5652//
John Kessenichead86222018-03-28 18:01:20 -06005653spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5654 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005655{
5656 bool firstClass = true;
5657
5658 // First, handle first-class matrix operations (* and matrix/scalar)
5659 switch (op) {
5660 case spv::OpFDiv:
5661 if (builder.isMatrix(left) && builder.isScalar(right)) {
5662 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005663 spv::Id resultType = builder.getTypeId(right);
5664 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005665 op = spv::OpMatrixTimesScalar;
5666 } else
5667 firstClass = false;
5668 break;
5669 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005670 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005671 std::swap(left, right);
5672 assert(builder.isScalar(right));
5673 break;
5674 case spv::OpVectorTimesMatrix:
5675 assert(builder.isVector(left));
5676 assert(builder.isMatrix(right));
5677 break;
5678 case spv::OpMatrixTimesVector:
5679 assert(builder.isMatrix(left));
5680 assert(builder.isVector(right));
5681 break;
5682 case spv::OpMatrixTimesMatrix:
5683 assert(builder.isMatrix(left));
5684 assert(builder.isMatrix(right));
5685 break;
5686 default:
5687 firstClass = false;
5688 break;
5689 }
5690
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005691 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5692 firstClass = true;
5693
qining25262b32016-05-06 17:25:16 -04005694 if (firstClass) {
5695 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005696 decorations.addNoContraction(builder, result);
5697 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005698 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005699 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005700
LoopDawg592860c2016-06-09 08:57:35 -06005701 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005702 // The result type of all of them is the same type as the (a) matrix operand.
5703 // The algorithm is to:
5704 // - break the matrix(es) into vectors
5705 // - smear any scalar to a vector
5706 // - do vector operations
5707 // - make a matrix out the vector results
5708 switch (op) {
5709 case spv::OpFAdd:
5710 case spv::OpFSub:
5711 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005712 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005713 case spv::OpFMul:
5714 {
5715 // one time set up...
5716 bool leftMat = builder.isMatrix(left);
5717 bool rightMat = builder.isMatrix(right);
5718 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5719 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5720 spv::Id scalarType = builder.getScalarTypeId(typeId);
5721 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5722 std::vector<spv::Id> results;
5723 spv::Id smearVec = spv::NoResult;
5724 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005725 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005726 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005727 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005728
5729 // do each vector op
5730 for (unsigned int c = 0; c < numCols; ++c) {
5731 std::vector<unsigned int> indexes;
5732 indexes.push_back(c);
5733 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5734 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005735 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005736 decorations.addNoContraction(builder, result);
5737 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005738 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005739 }
5740
5741 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005742 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005743 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005744 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005745 }
5746 default:
5747 assert(0);
5748 return spv::NoResult;
5749 }
5750}
5751
John Kessenichead86222018-03-28 18:01:20 -06005752spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005753 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005754{
5755 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005756 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005757 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005758 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5759 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005760
5761 switch (op) {
5762 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005763 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005764 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005765 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005766 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005767 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005768 unaryOp = spv::OpSNegate;
5769 break;
5770
5771 case glslang::EOpLogicalNot:
5772 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005773 unaryOp = spv::OpLogicalNot;
5774 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005775 case glslang::EOpBitwiseNot:
5776 unaryOp = spv::OpNot;
5777 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005778
John Kessenich140f3df2015-06-26 16:58:36 -06005779 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005780 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005781 break;
5782 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005783 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005784 break;
5785 case glslang::EOpTranspose:
5786 unaryOp = spv::OpTranspose;
5787 break;
5788
5789 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005790 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005791 break;
5792 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005793 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005794 break;
5795 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005796 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005797 break;
5798 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005799 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005800 break;
5801 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005802 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005803 break;
5804 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005805 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005806 break;
5807 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005808 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 break;
5810 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005811 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005812 break;
5813
5814 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005815 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005822 break;
5823 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005824 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005830 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005831 break;
5832
5833 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005834 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005835 break;
5836 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005837 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005838 break;
5839
5840 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005850 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005851 break;
5852 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005853 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005854 break;
5855 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005856 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005857 break;
5858
5859 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005860 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005861 break;
5862 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005863 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
5865 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005866 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005867 break;
5868 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005869 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005870 break;
5871 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005872 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005873 break;
5874 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005875 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005876 break;
5877
5878 case glslang::EOpIsNan:
5879 unaryOp = spv::OpIsNan;
5880 break;
5881 case glslang::EOpIsInf:
5882 unaryOp = spv::OpIsInf;
5883 break;
LoopDawg592860c2016-06-09 08:57:35 -06005884 case glslang::EOpIsFinite:
5885 unaryOp = spv::OpIsFinite;
5886 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005887
Rex Xucbc426e2015-12-15 16:03:10 +08005888 case glslang::EOpFloatBitsToInt:
5889 case glslang::EOpFloatBitsToUint:
5890 case glslang::EOpIntBitsToFloat:
5891 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005892 case glslang::EOpDoubleBitsToInt64:
5893 case glslang::EOpDoubleBitsToUint64:
5894 case glslang::EOpInt64BitsToDouble:
5895 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005896 case glslang::EOpFloat16BitsToInt16:
5897 case glslang::EOpFloat16BitsToUint16:
5898 case glslang::EOpInt16BitsToFloat16:
5899 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005900 unaryOp = spv::OpBitcast;
5901 break;
5902
John Kessenich140f3df2015-06-26 16:58:36 -06005903 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005904 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005905 break;
5906 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005907 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005908 break;
5909 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005910 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005911 break;
5912 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005913 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005914 break;
5915 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005916 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005917 break;
5918 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005919 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005920 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005921#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005922 case glslang::EOpPackSnorm4x8:
5923 libCall = spv::GLSLstd450PackSnorm4x8;
5924 break;
5925 case glslang::EOpUnpackSnorm4x8:
5926 libCall = spv::GLSLstd450UnpackSnorm4x8;
5927 break;
5928 case glslang::EOpPackUnorm4x8:
5929 libCall = spv::GLSLstd450PackUnorm4x8;
5930 break;
5931 case glslang::EOpUnpackUnorm4x8:
5932 libCall = spv::GLSLstd450UnpackUnorm4x8;
5933 break;
5934 case glslang::EOpPackDouble2x32:
5935 libCall = spv::GLSLstd450PackDouble2x32;
5936 break;
5937 case glslang::EOpUnpackDouble2x32:
5938 libCall = spv::GLSLstd450UnpackDouble2x32;
5939 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005940#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005941
Rex Xu8ff43de2016-04-22 16:51:45 +08005942 case glslang::EOpPackInt2x32:
5943 case glslang::EOpUnpackInt2x32:
5944 case glslang::EOpPackUint2x32:
5945 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005946 case glslang::EOpPack16:
5947 case glslang::EOpPack32:
5948 case glslang::EOpPack64:
5949 case glslang::EOpUnpack32:
5950 case glslang::EOpUnpack16:
5951 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005952 case glslang::EOpPackInt2x16:
5953 case glslang::EOpUnpackInt2x16:
5954 case glslang::EOpPackUint2x16:
5955 case glslang::EOpUnpackUint2x16:
5956 case glslang::EOpPackInt4x16:
5957 case glslang::EOpUnpackInt4x16:
5958 case glslang::EOpPackUint4x16:
5959 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005960 case glslang::EOpPackFloat2x16:
5961 case glslang::EOpUnpackFloat2x16:
5962 unaryOp = spv::OpBitcast;
5963 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005964
John Kessenich140f3df2015-06-26 16:58:36 -06005965 case glslang::EOpDPdx:
5966 unaryOp = spv::OpDPdx;
5967 break;
5968 case glslang::EOpDPdy:
5969 unaryOp = spv::OpDPdy;
5970 break;
5971 case glslang::EOpFwidth:
5972 unaryOp = spv::OpFwidth;
5973 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005974
John Kessenich140f3df2015-06-26 16:58:36 -06005975 case glslang::EOpAny:
5976 unaryOp = spv::OpAny;
5977 break;
5978 case glslang::EOpAll:
5979 unaryOp = spv::OpAll;
5980 break;
5981
5982 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005983 if (isFloat)
5984 libCall = spv::GLSLstd450FAbs;
5985 else
5986 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005987 break;
5988 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005989 if (isFloat)
5990 libCall = spv::GLSLstd450FSign;
5991 else
5992 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005993 break;
5994
John Kessenicha28f7a72019-08-06 07:00:58 -06005995#ifndef GLSLANG_WEB
5996 case glslang::EOpDPdxFine:
5997 unaryOp = spv::OpDPdxFine;
5998 break;
5999 case glslang::EOpDPdyFine:
6000 unaryOp = spv::OpDPdyFine;
6001 break;
6002 case glslang::EOpFwidthFine:
6003 unaryOp = spv::OpFwidthFine;
6004 break;
6005 case glslang::EOpDPdxCoarse:
6006 unaryOp = spv::OpDPdxCoarse;
6007 break;
6008 case glslang::EOpDPdyCoarse:
6009 unaryOp = spv::OpDPdyCoarse;
6010 break;
6011 case glslang::EOpFwidthCoarse:
6012 unaryOp = spv::OpFwidthCoarse;
6013 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006014 case glslang::EOpRayQueryProceed:
6015 unaryOp = spv::OpRayQueryProceedKHR;
6016 break;
6017 case glslang::EOpRayQueryGetRayTMin:
6018 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6019 break;
6020 case glslang::EOpRayQueryGetRayFlags:
6021 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6022 break;
6023 case glslang::EOpRayQueryGetWorldRayOrigin:
6024 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6025 break;
6026 case glslang::EOpRayQueryGetWorldRayDirection:
6027 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6028 break;
6029 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6030 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6031 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006032 case glslang::EOpInterpolateAtCentroid:
6033 if (typeProxy == glslang::EbtFloat16)
6034 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6035 libCall = spv::GLSLstd450InterpolateAtCentroid;
6036 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006037 case glslang::EOpAtomicCounterIncrement:
6038 case glslang::EOpAtomicCounterDecrement:
6039 case glslang::EOpAtomicCounter:
6040 {
6041 // Handle all of the atomics in one place, in createAtomicOperation()
6042 std::vector<spv::Id> operands;
6043 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006044 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006045 }
6046
John Kessenichfc51d282015-08-19 13:34:18 -06006047 case glslang::EOpBitFieldReverse:
6048 unaryOp = spv::OpBitReverse;
6049 break;
6050 case glslang::EOpBitCount:
6051 unaryOp = spv::OpBitCount;
6052 break;
6053 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006054 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006055 break;
6056 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006057 if (isUnsigned)
6058 libCall = spv::GLSLstd450FindUMsb;
6059 else
6060 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006061 break;
6062
Ian Romanickb3bd4022019-01-21 08:57:25 -08006063 case glslang::EOpCountLeadingZeros:
6064 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6065 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6066 unaryOp = spv::OpUCountLeadingZerosINTEL;
6067 break;
6068
6069 case glslang::EOpCountTrailingZeros:
6070 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6071 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6072 unaryOp = spv::OpUCountTrailingZerosINTEL;
6073 break;
6074
Rex Xu574ab042016-04-14 16:53:07 +08006075 case glslang::EOpBallot:
6076 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006077 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006078 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006079 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006080 case glslang::EOpMinInvocations:
6081 case glslang::EOpMaxInvocations:
6082 case glslang::EOpAddInvocations:
6083 case glslang::EOpMinInvocationsNonUniform:
6084 case glslang::EOpMaxInvocationsNonUniform:
6085 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006086 case glslang::EOpMinInvocationsInclusiveScan:
6087 case glslang::EOpMaxInvocationsInclusiveScan:
6088 case glslang::EOpAddInvocationsInclusiveScan:
6089 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6090 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6091 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6092 case glslang::EOpMinInvocationsExclusiveScan:
6093 case glslang::EOpMaxInvocationsExclusiveScan:
6094 case glslang::EOpAddInvocationsExclusiveScan:
6095 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6096 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6097 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006098 {
6099 std::vector<spv::Id> operands;
6100 operands.push_back(operand);
6101 return createInvocationsOperation(op, typeId, operands, typeProxy);
6102 }
John Kessenich66011cb2018-03-06 16:12:04 -07006103 case glslang::EOpSubgroupAll:
6104 case glslang::EOpSubgroupAny:
6105 case glslang::EOpSubgroupAllEqual:
6106 case glslang::EOpSubgroupBroadcastFirst:
6107 case glslang::EOpSubgroupBallot:
6108 case glslang::EOpSubgroupInverseBallot:
6109 case glslang::EOpSubgroupBallotBitCount:
6110 case glslang::EOpSubgroupBallotInclusiveBitCount:
6111 case glslang::EOpSubgroupBallotExclusiveBitCount:
6112 case glslang::EOpSubgroupBallotFindLSB:
6113 case glslang::EOpSubgroupBallotFindMSB:
6114 case glslang::EOpSubgroupAdd:
6115 case glslang::EOpSubgroupMul:
6116 case glslang::EOpSubgroupMin:
6117 case glslang::EOpSubgroupMax:
6118 case glslang::EOpSubgroupAnd:
6119 case glslang::EOpSubgroupOr:
6120 case glslang::EOpSubgroupXor:
6121 case glslang::EOpSubgroupInclusiveAdd:
6122 case glslang::EOpSubgroupInclusiveMul:
6123 case glslang::EOpSubgroupInclusiveMin:
6124 case glslang::EOpSubgroupInclusiveMax:
6125 case glslang::EOpSubgroupInclusiveAnd:
6126 case glslang::EOpSubgroupInclusiveOr:
6127 case glslang::EOpSubgroupInclusiveXor:
6128 case glslang::EOpSubgroupExclusiveAdd:
6129 case glslang::EOpSubgroupExclusiveMul:
6130 case glslang::EOpSubgroupExclusiveMin:
6131 case glslang::EOpSubgroupExclusiveMax:
6132 case glslang::EOpSubgroupExclusiveAnd:
6133 case glslang::EOpSubgroupExclusiveOr:
6134 case glslang::EOpSubgroupExclusiveXor:
6135 case glslang::EOpSubgroupQuadSwapHorizontal:
6136 case glslang::EOpSubgroupQuadSwapVertical:
6137 case glslang::EOpSubgroupQuadSwapDiagonal: {
6138 std::vector<spv::Id> operands;
6139 operands.push_back(operand);
6140 return createSubgroupOperation(op, typeId, operands, typeProxy);
6141 }
Rex Xu9d93a232016-05-05 12:30:44 +08006142 case glslang::EOpMbcnt:
6143 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6144 libCall = spv::MbcntAMD;
6145 break;
6146
6147 case glslang::EOpCubeFaceIndex:
6148 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6149 libCall = spv::CubeFaceIndexAMD;
6150 break;
6151
6152 case glslang::EOpCubeFaceCoord:
6153 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6154 libCall = spv::CubeFaceCoordAMD;
6155 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006156 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006157 unaryOp = spv::OpGroupNonUniformPartitionNV;
6158 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006159 case glslang::EOpConstructReference:
6160 unaryOp = spv::OpBitcast;
6161 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006162#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006163
6164 case glslang::EOpCopyObject:
6165 unaryOp = spv::OpCopyObject;
6166 break;
6167
John Kessenich140f3df2015-06-26 16:58:36 -06006168 default:
6169 return 0;
6170 }
6171
6172 spv::Id id;
6173 if (libCall >= 0) {
6174 std::vector<spv::Id> args;
6175 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006176 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006177 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006178 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006179 }
John Kessenich140f3df2015-06-26 16:58:36 -06006180
John Kessenichb9197c82019-08-11 07:41:45 -06006181 decorations.addNoContraction(builder, id);
6182 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006183 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006184}
6185
John Kessenich7a53f762016-01-20 11:19:27 -07006186// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006187spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6188 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006189{
6190 // Handle unary operations vector by vector.
6191 // The result type is the same type as the original type.
6192 // The algorithm is to:
6193 // - break the matrix into vectors
6194 // - apply the operation to each vector
6195 // - make a matrix out the vector results
6196
6197 // get the types sorted out
6198 int numCols = builder.getNumColumns(operand);
6199 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006200 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6201 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006202 std::vector<spv::Id> results;
6203
6204 // do each vector op
6205 for (int c = 0; c < numCols; ++c) {
6206 std::vector<unsigned int> indexes;
6207 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006208 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6209 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006210 decorations.addNoContraction(builder, destVec);
6211 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006212 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006213 }
6214
6215 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006216 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006217 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006218 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006219}
6220
John Kessenichad7645f2018-06-04 19:11:25 -06006221// For converting integers where both the bitwidth and the signedness could
6222// change, but only do the width change here. The caller is still responsible
6223// for the signedness conversion.
6224spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006225{
John Kessenichad7645f2018-06-04 19:11:25 -06006226 // Get the result type width, based on the type to convert to.
6227 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006228 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006229 case glslang::EOpConvInt16ToUint8:
6230 case glslang::EOpConvIntToUint8:
6231 case glslang::EOpConvInt64ToUint8:
6232 case glslang::EOpConvUint16ToInt8:
6233 case glslang::EOpConvUintToInt8:
6234 case glslang::EOpConvUint64ToInt8:
6235 width = 8;
6236 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006237 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006238 case glslang::EOpConvIntToUint16:
6239 case glslang::EOpConvInt64ToUint16:
6240 case glslang::EOpConvUint8ToInt16:
6241 case glslang::EOpConvUintToInt16:
6242 case glslang::EOpConvUint64ToInt16:
6243 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006244 break;
6245 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006246 case glslang::EOpConvInt16ToUint:
6247 case glslang::EOpConvInt64ToUint:
6248 case glslang::EOpConvUint8ToInt:
6249 case glslang::EOpConvUint16ToInt:
6250 case glslang::EOpConvUint64ToInt:
6251 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006252 break;
6253 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006254 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006255 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006256 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006257 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006258 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006259 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006260 break;
6261
6262 default:
6263 assert(false && "Default missing");
6264 break;
6265 }
6266
John Kessenichad7645f2018-06-04 19:11:25 -06006267 // Get the conversion operation and result type,
6268 // based on the target width, but the source type.
6269 spv::Id type = spv::NoType;
6270 spv::Op convOp = spv::OpNop;
6271 switch(op) {
6272 case glslang::EOpConvInt8ToUint16:
6273 case glslang::EOpConvInt8ToUint:
6274 case glslang::EOpConvInt8ToUint64:
6275 case glslang::EOpConvInt16ToUint8:
6276 case glslang::EOpConvInt16ToUint:
6277 case glslang::EOpConvInt16ToUint64:
6278 case glslang::EOpConvIntToUint8:
6279 case glslang::EOpConvIntToUint16:
6280 case glslang::EOpConvIntToUint64:
6281 case glslang::EOpConvInt64ToUint8:
6282 case glslang::EOpConvInt64ToUint16:
6283 case glslang::EOpConvInt64ToUint:
6284 convOp = spv::OpSConvert;
6285 type = builder.makeIntType(width);
6286 break;
6287 default:
6288 convOp = spv::OpUConvert;
6289 type = builder.makeUintType(width);
6290 break;
6291 }
6292
John Kessenich66011cb2018-03-06 16:12:04 -07006293 if (vectorSize > 0)
6294 type = builder.makeVectorType(type, vectorSize);
6295
John Kessenichad7645f2018-06-04 19:11:25 -06006296 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006297}
6298
John Kessenichead86222018-03-28 18:01:20 -06006299spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6300 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006301{
6302 spv::Op convOp = spv::OpNop;
6303 spv::Id zero = 0;
6304 spv::Id one = 0;
6305
6306 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6307
6308 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006309 case glslang::EOpConvIntToBool:
6310 case glslang::EOpConvUintToBool:
6311 zero = builder.makeUintConstant(0);
6312 zero = makeSmearedConstant(zero, vectorSize);
6313 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006314 case glslang::EOpConvFloatToBool:
6315 zero = builder.makeFloatConstant(0.0F);
6316 zero = makeSmearedConstant(zero, vectorSize);
6317 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006318 case glslang::EOpConvBoolToFloat:
6319 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006320 zero = builder.makeFloatConstant(0.0F);
6321 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006322 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006323
John Kessenich140f3df2015-06-26 16:58:36 -06006324 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006325 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006326#ifndef GLSLANG_WEB
6327 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006328 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006329 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006330 } else
6331#endif
6332 {
6333 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006334 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006335 }
Rex Xucabbb782017-03-24 13:41:14 +08006336
John Kessenich140f3df2015-06-26 16:58:36 -06006337 convOp = spv::OpSelect;
6338 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006339
John Kessenich140f3df2015-06-26 16:58:36 -06006340 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006341 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006342#ifndef GLSLANG_WEB
6343 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006344 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006345 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006346 } else
6347#endif
6348 {
6349 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006350 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006351 }
Rex Xucabbb782017-03-24 13:41:14 +08006352
John Kessenich140f3df2015-06-26 16:58:36 -06006353 convOp = spv::OpSelect;
6354 break;
6355
John Kessenich66011cb2018-03-06 16:12:04 -07006356 case glslang::EOpConvInt8ToFloat16:
6357 case glslang::EOpConvInt8ToFloat:
6358 case glslang::EOpConvInt8ToDouble:
6359 case glslang::EOpConvInt16ToFloat16:
6360 case glslang::EOpConvInt16ToFloat:
6361 case glslang::EOpConvInt16ToDouble:
6362 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006363 case glslang::EOpConvIntToFloat:
6364 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006365 case glslang::EOpConvInt64ToFloat:
6366 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006367 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006368 convOp = spv::OpConvertSToF;
6369 break;
6370
John Kessenich66011cb2018-03-06 16:12:04 -07006371 case glslang::EOpConvUint8ToFloat16:
6372 case glslang::EOpConvUint8ToFloat:
6373 case glslang::EOpConvUint8ToDouble:
6374 case glslang::EOpConvUint16ToFloat16:
6375 case glslang::EOpConvUint16ToFloat:
6376 case glslang::EOpConvUint16ToDouble:
6377 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006378 case glslang::EOpConvUintToFloat:
6379 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006380 case glslang::EOpConvUint64ToFloat:
6381 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006382 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006383 convOp = spv::OpConvertUToF;
6384 break;
6385
John Kessenich66011cb2018-03-06 16:12:04 -07006386 case glslang::EOpConvFloat16ToInt8:
6387 case glslang::EOpConvFloatToInt8:
6388 case glslang::EOpConvDoubleToInt8:
6389 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006390 case glslang::EOpConvFloatToInt16:
6391 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006392 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006393 case glslang::EOpConvFloatToInt:
6394 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006395 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006396 case glslang::EOpConvFloatToInt64:
6397 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006398 convOp = spv::OpConvertFToS;
6399 break;
6400
John Kessenich66011cb2018-03-06 16:12:04 -07006401 case glslang::EOpConvUint8ToInt8:
6402 case glslang::EOpConvInt8ToUint8:
6403 case glslang::EOpConvUint16ToInt16:
6404 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006405 case glslang::EOpConvUintToInt:
6406 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006407 case glslang::EOpConvUint64ToInt64:
6408 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006409 if (builder.isInSpecConstCodeGenMode()) {
6410 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006411#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006412 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6413 zero = builder.makeUint8Constant(0);
6414 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006415 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006416 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6417 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006418 } else
6419#endif
6420 {
Rex Xucabbb782017-03-24 13:41:14 +08006421 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006422 }
qining189b2032016-04-12 23:16:20 -04006423 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006424 // Use OpIAdd, instead of OpBitcast to do the conversion when
6425 // generating for OpSpecConstantOp instruction.
6426 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6427 }
6428 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006429 convOp = spv::OpBitcast;
6430 break;
6431
John Kessenich66011cb2018-03-06 16:12:04 -07006432 case glslang::EOpConvFloat16ToUint8:
6433 case glslang::EOpConvFloatToUint8:
6434 case glslang::EOpConvDoubleToUint8:
6435 case glslang::EOpConvFloat16ToUint16:
6436 case glslang::EOpConvFloatToUint16:
6437 case glslang::EOpConvDoubleToUint16:
6438 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006439 case glslang::EOpConvFloatToUint:
6440 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006441 case glslang::EOpConvFloatToUint64:
6442 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006443 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006444 convOp = spv::OpConvertFToU;
6445 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006446
John Kessenich39697cd2019-08-08 10:35:51 -06006447#ifndef GLSLANG_WEB
6448 case glslang::EOpConvInt8ToBool:
6449 case glslang::EOpConvUint8ToBool:
6450 zero = builder.makeUint8Constant(0);
6451 zero = makeSmearedConstant(zero, vectorSize);
6452 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6453 case glslang::EOpConvInt16ToBool:
6454 case glslang::EOpConvUint16ToBool:
6455 zero = builder.makeUint16Constant(0);
6456 zero = makeSmearedConstant(zero, vectorSize);
6457 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6458 case glslang::EOpConvInt64ToBool:
6459 case glslang::EOpConvUint64ToBool:
6460 zero = builder.makeUint64Constant(0);
6461 zero = makeSmearedConstant(zero, vectorSize);
6462 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6463 case glslang::EOpConvDoubleToBool:
6464 zero = builder.makeDoubleConstant(0.0);
6465 zero = makeSmearedConstant(zero, vectorSize);
6466 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6467 case glslang::EOpConvFloat16ToBool:
6468 zero = builder.makeFloat16Constant(0.0F);
6469 zero = makeSmearedConstant(zero, vectorSize);
6470 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6471 case glslang::EOpConvBoolToDouble:
6472 convOp = spv::OpSelect;
6473 zero = builder.makeDoubleConstant(0.0);
6474 one = builder.makeDoubleConstant(1.0);
6475 break;
6476 case glslang::EOpConvBoolToFloat16:
6477 convOp = spv::OpSelect;
6478 zero = builder.makeFloat16Constant(0.0F);
6479 one = builder.makeFloat16Constant(1.0F);
6480 break;
6481 case glslang::EOpConvBoolToInt8:
6482 zero = builder.makeInt8Constant(0);
6483 one = builder.makeInt8Constant(1);
6484 convOp = spv::OpSelect;
6485 break;
6486 case glslang::EOpConvBoolToUint8:
6487 zero = builder.makeUint8Constant(0);
6488 one = builder.makeUint8Constant(1);
6489 convOp = spv::OpSelect;
6490 break;
6491 case glslang::EOpConvBoolToInt16:
6492 zero = builder.makeInt16Constant(0);
6493 one = builder.makeInt16Constant(1);
6494 convOp = spv::OpSelect;
6495 break;
6496 case glslang::EOpConvBoolToUint16:
6497 zero = builder.makeUint16Constant(0);
6498 one = builder.makeUint16Constant(1);
6499 convOp = spv::OpSelect;
6500 break;
6501 case glslang::EOpConvDoubleToFloat:
6502 case glslang::EOpConvFloatToDouble:
6503 case glslang::EOpConvDoubleToFloat16:
6504 case glslang::EOpConvFloat16ToDouble:
6505 case glslang::EOpConvFloatToFloat16:
6506 case glslang::EOpConvFloat16ToFloat:
6507 convOp = spv::OpFConvert;
6508 if (builder.isMatrixType(destType))
6509 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6510 break;
6511
John Kessenich66011cb2018-03-06 16:12:04 -07006512 case glslang::EOpConvInt8ToInt16:
6513 case glslang::EOpConvInt8ToInt:
6514 case glslang::EOpConvInt8ToInt64:
6515 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006516 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006517 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006518 case glslang::EOpConvIntToInt8:
6519 case glslang::EOpConvIntToInt16:
6520 case glslang::EOpConvIntToInt64:
6521 case glslang::EOpConvInt64ToInt8:
6522 case glslang::EOpConvInt64ToInt16:
6523 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006524 convOp = spv::OpSConvert;
6525 break;
6526
John Kessenich66011cb2018-03-06 16:12:04 -07006527 case glslang::EOpConvUint8ToUint16:
6528 case glslang::EOpConvUint8ToUint:
6529 case glslang::EOpConvUint8ToUint64:
6530 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006531 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006532 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006533 case glslang::EOpConvUintToUint8:
6534 case glslang::EOpConvUintToUint16:
6535 case glslang::EOpConvUintToUint64:
6536 case glslang::EOpConvUint64ToUint8:
6537 case glslang::EOpConvUint64ToUint16:
6538 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006539 convOp = spv::OpUConvert;
6540 break;
6541
John Kessenich66011cb2018-03-06 16:12:04 -07006542 case glslang::EOpConvInt8ToUint16:
6543 case glslang::EOpConvInt8ToUint:
6544 case glslang::EOpConvInt8ToUint64:
6545 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006546 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006547 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006548 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006549 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006550 case glslang::EOpConvIntToUint64:
6551 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006552 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006553 case glslang::EOpConvInt64ToUint:
6554 case glslang::EOpConvUint8ToInt16:
6555 case glslang::EOpConvUint8ToInt:
6556 case glslang::EOpConvUint8ToInt64:
6557 case glslang::EOpConvUint16ToInt8:
6558 case glslang::EOpConvUint16ToInt:
6559 case glslang::EOpConvUint16ToInt64:
6560 case glslang::EOpConvUintToInt8:
6561 case glslang::EOpConvUintToInt16:
6562 case glslang::EOpConvUintToInt64:
6563 case glslang::EOpConvUint64ToInt8:
6564 case glslang::EOpConvUint64ToInt16:
6565 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006566 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006567 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006568
6569 if (builder.isInSpecConstCodeGenMode()) {
6570 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006571 switch(op) {
6572 case glslang::EOpConvInt16ToUint8:
6573 case glslang::EOpConvIntToUint8:
6574 case glslang::EOpConvInt64ToUint8:
6575 case glslang::EOpConvUint16ToInt8:
6576 case glslang::EOpConvUintToInt8:
6577 case glslang::EOpConvUint64ToInt8:
6578 zero = builder.makeUint8Constant(0);
6579 break;
6580 case glslang::EOpConvInt8ToUint16:
6581 case glslang::EOpConvIntToUint16:
6582 case glslang::EOpConvInt64ToUint16:
6583 case glslang::EOpConvUint8ToInt16:
6584 case glslang::EOpConvUintToInt16:
6585 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006586 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006587 break;
6588 case glslang::EOpConvInt8ToUint:
6589 case glslang::EOpConvInt16ToUint:
6590 case glslang::EOpConvInt64ToUint:
6591 case glslang::EOpConvUint8ToInt:
6592 case glslang::EOpConvUint16ToInt:
6593 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006594 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006595 break;
6596 case glslang::EOpConvInt8ToUint64:
6597 case glslang::EOpConvInt16ToUint64:
6598 case glslang::EOpConvIntToUint64:
6599 case glslang::EOpConvUint8ToInt64:
6600 case glslang::EOpConvUint16ToInt64:
6601 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006602 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006603 break;
6604 default:
6605 assert(false && "Default missing");
6606 break;
6607 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006608 zero = makeSmearedConstant(zero, vectorSize);
6609 // Use OpIAdd, instead of OpBitcast to do the conversion when
6610 // generating for OpSpecConstantOp instruction.
6611 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6612 }
6613 // For normal run-time conversion instruction, use OpBitcast.
6614 convOp = spv::OpBitcast;
6615 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006616 case glslang::EOpConvUint64ToPtr:
6617 convOp = spv::OpConvertUToPtr;
6618 break;
6619 case glslang::EOpConvPtrToUint64:
6620 convOp = spv::OpConvertPtrToU;
6621 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006622 case glslang::EOpConvPtrToUvec2:
6623 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006624 if (builder.isVector(operand))
6625 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6626 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006627 convOp = spv::OpBitcast;
6628 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006629#endif
6630
John Kessenich140f3df2015-06-26 16:58:36 -06006631 default:
6632 break;
6633 }
6634
6635 spv::Id result = 0;
6636 if (convOp == spv::OpNop)
6637 return result;
6638
6639 if (convOp == spv::OpSelect) {
6640 zero = makeSmearedConstant(zero, vectorSize);
6641 one = makeSmearedConstant(one, vectorSize);
6642 result = builder.createTriOp(convOp, destType, operand, one, zero);
6643 } else
6644 result = builder.createUnaryOp(convOp, destType, operand);
6645
John Kessenichead86222018-03-28 18:01:20 -06006646 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006647 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006648 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006649}
6650
6651spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6652{
6653 if (vectorSize == 0)
6654 return constant;
6655
6656 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6657 std::vector<spv::Id> components;
6658 for (int c = 0; c < vectorSize; ++c)
6659 components.push_back(constant);
6660 return builder.makeCompositeConstant(vectorTypeId, components);
6661}
6662
John Kessenich426394d2015-07-23 10:22:48 -06006663// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006664spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6665 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6666 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006667{
6668 spv::Op opCode = spv::OpNop;
6669
6670 switch (op) {
6671 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006672 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006673 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006674 opCode = spv::OpAtomicIAdd;
6675 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006676 case glslang::EOpAtomicCounterSubtract:
6677 opCode = spv::OpAtomicISub;
6678 break;
John Kessenich426394d2015-07-23 10:22:48 -06006679 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006680 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006681 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006682 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6683 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006684 break;
6685 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006686 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006687 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006688 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6689 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006690 break;
6691 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006692 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006693 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006694 opCode = spv::OpAtomicAnd;
6695 break;
6696 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006697 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006698 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006699 opCode = spv::OpAtomicOr;
6700 break;
6701 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006702 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006703 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006704 opCode = spv::OpAtomicXor;
6705 break;
6706 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006707 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006708 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006709 opCode = spv::OpAtomicExchange;
6710 break;
6711 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006712 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006713 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006714 opCode = spv::OpAtomicCompareExchange;
6715 break;
6716 case glslang::EOpAtomicCounterIncrement:
6717 opCode = spv::OpAtomicIIncrement;
6718 break;
6719 case glslang::EOpAtomicCounterDecrement:
6720 opCode = spv::OpAtomicIDecrement;
6721 break;
6722 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006723 case glslang::EOpImageAtomicLoad:
6724 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006725 opCode = spv::OpAtomicLoad;
6726 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006727 case glslang::EOpAtomicStore:
6728 case glslang::EOpImageAtomicStore:
6729 opCode = spv::OpAtomicStore;
6730 break;
John Kessenich426394d2015-07-23 10:22:48 -06006731 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006732 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006733 break;
6734 }
6735
Rex Xue8fe8b02017-09-26 15:42:56 +08006736 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6737 builder.addCapability(spv::CapabilityInt64Atomics);
6738
John Kessenich426394d2015-07-23 10:22:48 -06006739 // Sort out the operands
6740 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006741 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006742 // - compare-exchange swaps the value and comparator
6743 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006744 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006745 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6746 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6747 spv::Id scopeId;
6748 if (glslangIntermediate->usingVulkanMemoryModel()) {
6749 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6750 } else {
6751 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6752 }
6753 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006754 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6755 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006756 spv::MemorySemanticsVolatileMask :
6757 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006758 spv::Id semanticsId2 = semanticsId;
6759
6760 pointerId = operands[0];
6761 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6762 // no additional operands
6763 } else if (opCode == spv::OpAtomicCompareExchange) {
6764 compareId = operands[1];
6765 valueId = operands[2];
6766 if (operands.size() > 3) {
6767 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006768 semanticsId = builder.makeUintConstant(
6769 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6770 semanticsId2 = builder.makeUintConstant(
6771 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006772 }
6773 } else if (opCode == spv::OpAtomicLoad) {
6774 if (operands.size() > 1) {
6775 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006776 semanticsId = builder.makeUintConstant(
6777 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006778 }
6779 } else {
6780 // atomic store or RMW
6781 valueId = operands[1];
6782 if (operands.size() > 2) {
6783 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006784 semanticsId = builder.makeUintConstant
6785 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006786 }
Rex Xu04db3f52015-09-16 11:44:02 +08006787 }
John Kessenich426394d2015-07-23 10:22:48 -06006788
Jeff Bolz36831c92018-09-05 10:11:41 -05006789 // Check for capabilities
6790 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006791 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6792 spv::MemorySemanticsMakeVisibleKHRMask |
6793 spv::MemorySemanticsOutputMemoryKHRMask |
6794 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006795 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6796 }
John Kessenich426394d2015-07-23 10:22:48 -06006797
Jeff Bolz36831c92018-09-05 10:11:41 -05006798 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6799 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6800 }
John Kessenich48d6e792017-10-06 21:21:48 -06006801
Jeff Bolz36831c92018-09-05 10:11:41 -05006802 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6803 spvAtomicOperands.push_back(pointerId);
6804 spvAtomicOperands.push_back(scopeId);
6805 spvAtomicOperands.push_back(semanticsId);
6806 if (opCode == spv::OpAtomicCompareExchange) {
6807 spvAtomicOperands.push_back(semanticsId2);
6808 spvAtomicOperands.push_back(valueId);
6809 spvAtomicOperands.push_back(compareId);
6810 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6811 spvAtomicOperands.push_back(valueId);
6812 }
John Kessenich48d6e792017-10-06 21:21:48 -06006813
Jeff Bolz36831c92018-09-05 10:11:41 -05006814 if (opCode == spv::OpAtomicStore) {
6815 builder.createNoResultOp(opCode, spvAtomicOperands);
6816 return 0;
6817 } else {
6818 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6819
6820 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6821 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6822 if (op == glslang::EOpAtomicCounterDecrement)
6823 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6824
6825 return resultId;
6826 }
John Kessenich426394d2015-07-23 10:22:48 -06006827}
6828
John Kessenich91cef522016-05-05 16:45:40 -06006829// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006830spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6831 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006832{
John Kessenich66011cb2018-03-06 16:12:04 -07006833 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6834 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006835
Rex Xu51596642016-09-21 18:56:12 +08006836 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006837 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006838 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6839
chaocf200da82016-12-20 12:44:35 -08006840 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6841 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006842 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6843 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006844 } else if (op == glslang::EOpAnyInvocation ||
6845 op == glslang::EOpAllInvocations ||
6846 op == glslang::EOpAllInvocationsEqual) {
6847 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6848 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006849 } else {
6850 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006851 if (op == glslang::EOpMinInvocationsNonUniform ||
6852 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006853 op == glslang::EOpAddInvocationsNonUniform ||
6854 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6855 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6856 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6857 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6858 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6859 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006860 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006861
Rex Xu430ef402016-10-14 17:22:23 +08006862 switch (op) {
6863 case glslang::EOpMinInvocations:
6864 case glslang::EOpMaxInvocations:
6865 case glslang::EOpAddInvocations:
6866 case glslang::EOpMinInvocationsNonUniform:
6867 case glslang::EOpMaxInvocationsNonUniform:
6868 case glslang::EOpAddInvocationsNonUniform:
6869 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006870 break;
6871 case glslang::EOpMinInvocationsInclusiveScan:
6872 case glslang::EOpMaxInvocationsInclusiveScan:
6873 case glslang::EOpAddInvocationsInclusiveScan:
6874 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6875 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6876 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6877 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006878 break;
6879 case glslang::EOpMinInvocationsExclusiveScan:
6880 case glslang::EOpMaxInvocationsExclusiveScan:
6881 case glslang::EOpAddInvocationsExclusiveScan:
6882 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6883 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6884 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6885 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006886 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006887 default:
6888 break;
Rex Xu430ef402016-10-14 17:22:23 +08006889 }
John Kessenich149afc32018-08-14 13:31:43 -06006890 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6891 spvGroupOperands.push_back(scope);
6892 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006893 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006894 spvGroupOperands.push_back(groupOp);
6895 }
Rex Xu51596642016-09-21 18:56:12 +08006896 }
6897
John Kessenich149afc32018-08-14 13:31:43 -06006898 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6899 spv::IdImmediate op = { true, *opIt };
6900 spvGroupOperands.push_back(op);
6901 }
John Kessenich91cef522016-05-05 16:45:40 -06006902
6903 switch (op) {
6904 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006905 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006906 break;
John Kessenich91cef522016-05-05 16:45:40 -06006907 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006908 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006909 break;
John Kessenich91cef522016-05-05 16:45:40 -06006910 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006911 opCode = spv::OpSubgroupAllEqualKHR;
6912 break;
Rex Xu51596642016-09-21 18:56:12 +08006913 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006914 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006915 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006916 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006917 break;
6918 case glslang::EOpReadFirstInvocation:
6919 opCode = spv::OpSubgroupFirstInvocationKHR;
6920 break;
6921 case glslang::EOpBallot:
6922 {
6923 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6924 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6925 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6926 //
6927 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6928 //
6929 spv::Id uintType = builder.makeUintType(32);
6930 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6931 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6932
6933 std::vector<spv::Id> components;
6934 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6935 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6936
6937 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6938 return builder.createUnaryOp(spv::OpBitcast, typeId,
6939 builder.createCompositeConstruct(uvec2Type, components));
6940 }
6941
Rex Xu9d93a232016-05-05 12:30:44 +08006942 case glslang::EOpMinInvocations:
6943 case glslang::EOpMaxInvocations:
6944 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006945 case glslang::EOpMinInvocationsInclusiveScan:
6946 case glslang::EOpMaxInvocationsInclusiveScan:
6947 case glslang::EOpAddInvocationsInclusiveScan:
6948 case glslang::EOpMinInvocationsExclusiveScan:
6949 case glslang::EOpMaxInvocationsExclusiveScan:
6950 case glslang::EOpAddInvocationsExclusiveScan:
6951 if (op == glslang::EOpMinInvocations ||
6952 op == glslang::EOpMinInvocationsInclusiveScan ||
6953 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006954 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006955 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006956 else {
6957 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006958 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006959 else
Rex Xu51596642016-09-21 18:56:12 +08006960 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006961 }
Rex Xu430ef402016-10-14 17:22:23 +08006962 } else if (op == glslang::EOpMaxInvocations ||
6963 op == glslang::EOpMaxInvocationsInclusiveScan ||
6964 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006965 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006966 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006967 else {
6968 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006969 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006970 else
Rex Xu51596642016-09-21 18:56:12 +08006971 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006972 }
6973 } else {
6974 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006975 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006976 else
Rex Xu51596642016-09-21 18:56:12 +08006977 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006978 }
6979
Rex Xu2bbbe062016-08-23 15:41:05 +08006980 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006981 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006982
6983 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006984 case glslang::EOpMinInvocationsNonUniform:
6985 case glslang::EOpMaxInvocationsNonUniform:
6986 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006987 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6988 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6989 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6990 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6991 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6992 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6993 if (op == glslang::EOpMinInvocationsNonUniform ||
6994 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6995 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006996 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006997 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006998 else {
6999 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007000 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007001 else
Rex Xu51596642016-09-21 18:56:12 +08007002 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007003 }
7004 }
Rex Xu430ef402016-10-14 17:22:23 +08007005 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7006 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7007 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007008 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007009 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007010 else {
7011 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007012 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007013 else
Rex Xu51596642016-09-21 18:56:12 +08007014 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007015 }
7016 }
7017 else {
7018 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007019 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007020 else
Rex Xu51596642016-09-21 18:56:12 +08007021 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007022 }
7023
Rex Xu2bbbe062016-08-23 15:41:05 +08007024 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007025 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007026
7027 break;
John Kessenich91cef522016-05-05 16:45:40 -06007028 default:
7029 logger->missingFunctionality("invocation operation");
7030 return spv::NoResult;
7031 }
Rex Xu51596642016-09-21 18:56:12 +08007032
7033 assert(opCode != spv::OpNop);
7034 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007035}
7036
Rex Xu2bbbe062016-08-23 15:41:05 +08007037// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007038spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7039 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007040{
7041 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7042 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007043 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007044 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007045 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7046 op == spv::OpGroupSMinNonUniformAMD ||
7047 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7048 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007049 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7050
7051 // Handle group invocation operations scalar by scalar.
7052 // The result type is the same type as the original type.
7053 // The algorithm is to:
7054 // - break the vector into scalars
7055 // - apply the operation to each scalar
7056 // - make a vector out the scalar results
7057
7058 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007059 int numComponents = builder.getNumComponents(operands[0]);
7060 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007061 std::vector<spv::Id> results;
7062
7063 // do each scalar op
7064 for (int comp = 0; comp < numComponents; ++comp) {
7065 std::vector<unsigned int> indexes;
7066 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007067 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7068 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007069 if (op == spv::OpSubgroupReadInvocationKHR) {
7070 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007071 spv::IdImmediate operand = { true, operands[1] };
7072 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007073 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007074 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7075 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007076 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007077 spv::IdImmediate operand = { true, operands[1] };
7078 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007079 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007080 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7081 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007082 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007083 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007084 spvGroupOperands.push_back(scalar);
7085 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007086
Rex Xub7072052016-09-26 15:53:40 +08007087 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007088 }
7089
7090 // put the pieces together
7091 return builder.createCompositeConstruct(typeId, results);
7092}
Rex Xu2bbbe062016-08-23 15:41:05 +08007093
John Kessenich66011cb2018-03-06 16:12:04 -07007094// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007095spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7096 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007097{
7098 // Add the required capabilities.
7099 switch (op) {
7100 case glslang::EOpSubgroupElect:
7101 builder.addCapability(spv::CapabilityGroupNonUniform);
7102 break;
7103 case glslang::EOpSubgroupAll:
7104 case glslang::EOpSubgroupAny:
7105 case glslang::EOpSubgroupAllEqual:
7106 builder.addCapability(spv::CapabilityGroupNonUniform);
7107 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7108 break;
7109 case glslang::EOpSubgroupBroadcast:
7110 case glslang::EOpSubgroupBroadcastFirst:
7111 case glslang::EOpSubgroupBallot:
7112 case glslang::EOpSubgroupInverseBallot:
7113 case glslang::EOpSubgroupBallotBitExtract:
7114 case glslang::EOpSubgroupBallotBitCount:
7115 case glslang::EOpSubgroupBallotInclusiveBitCount:
7116 case glslang::EOpSubgroupBallotExclusiveBitCount:
7117 case glslang::EOpSubgroupBallotFindLSB:
7118 case glslang::EOpSubgroupBallotFindMSB:
7119 builder.addCapability(spv::CapabilityGroupNonUniform);
7120 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7121 break;
7122 case glslang::EOpSubgroupShuffle:
7123 case glslang::EOpSubgroupShuffleXor:
7124 builder.addCapability(spv::CapabilityGroupNonUniform);
7125 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7126 break;
7127 case glslang::EOpSubgroupShuffleUp:
7128 case glslang::EOpSubgroupShuffleDown:
7129 builder.addCapability(spv::CapabilityGroupNonUniform);
7130 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7131 break;
7132 case glslang::EOpSubgroupAdd:
7133 case glslang::EOpSubgroupMul:
7134 case glslang::EOpSubgroupMin:
7135 case glslang::EOpSubgroupMax:
7136 case glslang::EOpSubgroupAnd:
7137 case glslang::EOpSubgroupOr:
7138 case glslang::EOpSubgroupXor:
7139 case glslang::EOpSubgroupInclusiveAdd:
7140 case glslang::EOpSubgroupInclusiveMul:
7141 case glslang::EOpSubgroupInclusiveMin:
7142 case glslang::EOpSubgroupInclusiveMax:
7143 case glslang::EOpSubgroupInclusiveAnd:
7144 case glslang::EOpSubgroupInclusiveOr:
7145 case glslang::EOpSubgroupInclusiveXor:
7146 case glslang::EOpSubgroupExclusiveAdd:
7147 case glslang::EOpSubgroupExclusiveMul:
7148 case glslang::EOpSubgroupExclusiveMin:
7149 case glslang::EOpSubgroupExclusiveMax:
7150 case glslang::EOpSubgroupExclusiveAnd:
7151 case glslang::EOpSubgroupExclusiveOr:
7152 case glslang::EOpSubgroupExclusiveXor:
7153 builder.addCapability(spv::CapabilityGroupNonUniform);
7154 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7155 break;
7156 case glslang::EOpSubgroupClusteredAdd:
7157 case glslang::EOpSubgroupClusteredMul:
7158 case glslang::EOpSubgroupClusteredMin:
7159 case glslang::EOpSubgroupClusteredMax:
7160 case glslang::EOpSubgroupClusteredAnd:
7161 case glslang::EOpSubgroupClusteredOr:
7162 case glslang::EOpSubgroupClusteredXor:
7163 builder.addCapability(spv::CapabilityGroupNonUniform);
7164 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7165 break;
7166 case glslang::EOpSubgroupQuadBroadcast:
7167 case glslang::EOpSubgroupQuadSwapHorizontal:
7168 case glslang::EOpSubgroupQuadSwapVertical:
7169 case glslang::EOpSubgroupQuadSwapDiagonal:
7170 builder.addCapability(spv::CapabilityGroupNonUniform);
7171 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7172 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007173 case glslang::EOpSubgroupPartitionedAdd:
7174 case glslang::EOpSubgroupPartitionedMul:
7175 case glslang::EOpSubgroupPartitionedMin:
7176 case glslang::EOpSubgroupPartitionedMax:
7177 case glslang::EOpSubgroupPartitionedAnd:
7178 case glslang::EOpSubgroupPartitionedOr:
7179 case glslang::EOpSubgroupPartitionedXor:
7180 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7181 case glslang::EOpSubgroupPartitionedInclusiveMul:
7182 case glslang::EOpSubgroupPartitionedInclusiveMin:
7183 case glslang::EOpSubgroupPartitionedInclusiveMax:
7184 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7185 case glslang::EOpSubgroupPartitionedInclusiveOr:
7186 case glslang::EOpSubgroupPartitionedInclusiveXor:
7187 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7188 case glslang::EOpSubgroupPartitionedExclusiveMul:
7189 case glslang::EOpSubgroupPartitionedExclusiveMin:
7190 case glslang::EOpSubgroupPartitionedExclusiveMax:
7191 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7192 case glslang::EOpSubgroupPartitionedExclusiveOr:
7193 case glslang::EOpSubgroupPartitionedExclusiveXor:
7194 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7195 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7196 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007197 default: assert(0 && "Unhandled subgroup operation!");
7198 }
7199
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007200
7201 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7202 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007203 const bool isBool = typeProxy == glslang::EbtBool;
7204
7205 spv::Op opCode = spv::OpNop;
7206
7207 // Figure out which opcode to use.
7208 switch (op) {
7209 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7210 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7211 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7212 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7213 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7214 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7215 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7216 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7217 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7218 case glslang::EOpSubgroupBallotBitCount:
7219 case glslang::EOpSubgroupBallotInclusiveBitCount:
7220 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7221 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7222 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7223 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7224 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7225 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7226 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7227 case glslang::EOpSubgroupAdd:
7228 case glslang::EOpSubgroupInclusiveAdd:
7229 case glslang::EOpSubgroupExclusiveAdd:
7230 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007231 case glslang::EOpSubgroupPartitionedAdd:
7232 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7233 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007234 if (isFloat) {
7235 opCode = spv::OpGroupNonUniformFAdd;
7236 } else {
7237 opCode = spv::OpGroupNonUniformIAdd;
7238 }
7239 break;
7240 case glslang::EOpSubgroupMul:
7241 case glslang::EOpSubgroupInclusiveMul:
7242 case glslang::EOpSubgroupExclusiveMul:
7243 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007244 case glslang::EOpSubgroupPartitionedMul:
7245 case glslang::EOpSubgroupPartitionedInclusiveMul:
7246 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007247 if (isFloat) {
7248 opCode = spv::OpGroupNonUniformFMul;
7249 } else {
7250 opCode = spv::OpGroupNonUniformIMul;
7251 }
7252 break;
7253 case glslang::EOpSubgroupMin:
7254 case glslang::EOpSubgroupInclusiveMin:
7255 case glslang::EOpSubgroupExclusiveMin:
7256 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007257 case glslang::EOpSubgroupPartitionedMin:
7258 case glslang::EOpSubgroupPartitionedInclusiveMin:
7259 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007260 if (isFloat) {
7261 opCode = spv::OpGroupNonUniformFMin;
7262 } else if (isUnsigned) {
7263 opCode = spv::OpGroupNonUniformUMin;
7264 } else {
7265 opCode = spv::OpGroupNonUniformSMin;
7266 }
7267 break;
7268 case glslang::EOpSubgroupMax:
7269 case glslang::EOpSubgroupInclusiveMax:
7270 case glslang::EOpSubgroupExclusiveMax:
7271 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007272 case glslang::EOpSubgroupPartitionedMax:
7273 case glslang::EOpSubgroupPartitionedInclusiveMax:
7274 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007275 if (isFloat) {
7276 opCode = spv::OpGroupNonUniformFMax;
7277 } else if (isUnsigned) {
7278 opCode = spv::OpGroupNonUniformUMax;
7279 } else {
7280 opCode = spv::OpGroupNonUniformSMax;
7281 }
7282 break;
7283 case glslang::EOpSubgroupAnd:
7284 case glslang::EOpSubgroupInclusiveAnd:
7285 case glslang::EOpSubgroupExclusiveAnd:
7286 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007287 case glslang::EOpSubgroupPartitionedAnd:
7288 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7289 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007290 if (isBool) {
7291 opCode = spv::OpGroupNonUniformLogicalAnd;
7292 } else {
7293 opCode = spv::OpGroupNonUniformBitwiseAnd;
7294 }
7295 break;
7296 case glslang::EOpSubgroupOr:
7297 case glslang::EOpSubgroupInclusiveOr:
7298 case glslang::EOpSubgroupExclusiveOr:
7299 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007300 case glslang::EOpSubgroupPartitionedOr:
7301 case glslang::EOpSubgroupPartitionedInclusiveOr:
7302 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007303 if (isBool) {
7304 opCode = spv::OpGroupNonUniformLogicalOr;
7305 } else {
7306 opCode = spv::OpGroupNonUniformBitwiseOr;
7307 }
7308 break;
7309 case glslang::EOpSubgroupXor:
7310 case glslang::EOpSubgroupInclusiveXor:
7311 case glslang::EOpSubgroupExclusiveXor:
7312 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007313 case glslang::EOpSubgroupPartitionedXor:
7314 case glslang::EOpSubgroupPartitionedInclusiveXor:
7315 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007316 if (isBool) {
7317 opCode = spv::OpGroupNonUniformLogicalXor;
7318 } else {
7319 opCode = spv::OpGroupNonUniformBitwiseXor;
7320 }
7321 break;
7322 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7323 case glslang::EOpSubgroupQuadSwapHorizontal:
7324 case glslang::EOpSubgroupQuadSwapVertical:
7325 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7326 default: assert(0 && "Unhandled subgroup operation!");
7327 }
7328
John Kessenich149afc32018-08-14 13:31:43 -06007329 // get the right Group Operation
7330 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007331 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007332 default:
7333 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007334 case glslang::EOpSubgroupBallotBitCount:
7335 case glslang::EOpSubgroupAdd:
7336 case glslang::EOpSubgroupMul:
7337 case glslang::EOpSubgroupMin:
7338 case glslang::EOpSubgroupMax:
7339 case glslang::EOpSubgroupAnd:
7340 case glslang::EOpSubgroupOr:
7341 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007342 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007343 break;
7344 case glslang::EOpSubgroupBallotInclusiveBitCount:
7345 case glslang::EOpSubgroupInclusiveAdd:
7346 case glslang::EOpSubgroupInclusiveMul:
7347 case glslang::EOpSubgroupInclusiveMin:
7348 case glslang::EOpSubgroupInclusiveMax:
7349 case glslang::EOpSubgroupInclusiveAnd:
7350 case glslang::EOpSubgroupInclusiveOr:
7351 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007352 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007353 break;
7354 case glslang::EOpSubgroupBallotExclusiveBitCount:
7355 case glslang::EOpSubgroupExclusiveAdd:
7356 case glslang::EOpSubgroupExclusiveMul:
7357 case glslang::EOpSubgroupExclusiveMin:
7358 case glslang::EOpSubgroupExclusiveMax:
7359 case glslang::EOpSubgroupExclusiveAnd:
7360 case glslang::EOpSubgroupExclusiveOr:
7361 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007362 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007363 break;
7364 case glslang::EOpSubgroupClusteredAdd:
7365 case glslang::EOpSubgroupClusteredMul:
7366 case glslang::EOpSubgroupClusteredMin:
7367 case glslang::EOpSubgroupClusteredMax:
7368 case glslang::EOpSubgroupClusteredAnd:
7369 case glslang::EOpSubgroupClusteredOr:
7370 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007371 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007372 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007373 case glslang::EOpSubgroupPartitionedAdd:
7374 case glslang::EOpSubgroupPartitionedMul:
7375 case glslang::EOpSubgroupPartitionedMin:
7376 case glslang::EOpSubgroupPartitionedMax:
7377 case glslang::EOpSubgroupPartitionedAnd:
7378 case glslang::EOpSubgroupPartitionedOr:
7379 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007380 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007381 break;
7382 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7383 case glslang::EOpSubgroupPartitionedInclusiveMul:
7384 case glslang::EOpSubgroupPartitionedInclusiveMin:
7385 case glslang::EOpSubgroupPartitionedInclusiveMax:
7386 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7387 case glslang::EOpSubgroupPartitionedInclusiveOr:
7388 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007389 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007390 break;
7391 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7392 case glslang::EOpSubgroupPartitionedExclusiveMul:
7393 case glslang::EOpSubgroupPartitionedExclusiveMin:
7394 case glslang::EOpSubgroupPartitionedExclusiveMax:
7395 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7396 case glslang::EOpSubgroupPartitionedExclusiveOr:
7397 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007398 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007399 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007400 }
7401
John Kessenich149afc32018-08-14 13:31:43 -06007402 // build the instruction
7403 std::vector<spv::IdImmediate> spvGroupOperands;
7404
7405 // Every operation begins with the Execution Scope operand.
7406 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7407 spvGroupOperands.push_back(executionScope);
7408
7409 // Next, for all operations that use a Group Operation, push that as an operand.
7410 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007411 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007412 spvGroupOperands.push_back(groupOperand);
7413 }
7414
John Kessenich66011cb2018-03-06 16:12:04 -07007415 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007416 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7417 spv::IdImmediate operand = { true, *opIt };
7418 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007419 }
7420
7421 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007422 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007423 switch (op) {
7424 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007425 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7426 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7427 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7428 }
7429 if (directionId != spv::NoResult) {
7430 spv::IdImmediate direction = { true, directionId };
7431 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007432 }
7433
7434 return builder.createOp(opCode, typeId, spvGroupOperands);
7435}
7436
John Kessenich8985fc92020-03-03 10:25:07 -07007437spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7438 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007439{
John Kessenich66011cb2018-03-06 16:12:04 -07007440 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7441 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007442
John Kessenich140f3df2015-06-26 16:58:36 -06007443 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007444 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007445 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007446 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007447 spv::Id typeId0 = 0;
7448 if (consumedOperands > 0)
7449 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007450 spv::Id typeId1 = 0;
7451 if (consumedOperands > 1)
7452 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007453 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007454
7455 switch (op) {
7456 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007457 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007458 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007459 else if (isUnsigned)
7460 libCall = spv::GLSLstd450UMin;
7461 else
7462 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007463 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007464 break;
7465 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007466 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007467 break;
7468 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007469 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007470 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007471 else if (isUnsigned)
7472 libCall = spv::GLSLstd450UMax;
7473 else
7474 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007475 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007476 break;
7477 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007478 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007479 break;
7480 case glslang::EOpDot:
7481 opCode = spv::OpDot;
7482 break;
7483 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007484 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007485 break;
7486
7487 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007488 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007489 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007490 else if (isUnsigned)
7491 libCall = spv::GLSLstd450UClamp;
7492 else
7493 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007494 builder.promoteScalar(precision, operands.front(), operands[1]);
7495 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007496 break;
7497 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007498 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7499 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007500 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007501 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007502 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007503 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007504 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007505 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007506 break;
7507 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007508 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007509 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007510 break;
7511 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007512 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007513 builder.promoteScalar(precision, operands[0], operands[2]);
7514 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007515 break;
7516
7517 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007518 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007519 break;
7520 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007521 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007522 break;
7523 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007524 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007525 break;
7526 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007527 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007528 break;
7529 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007530 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007531 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007532 case glslang::EOpBarrier:
7533 {
7534 // This is for the extended controlBarrier function, with four operands.
7535 // The unextended barrier() goes through createNoArgOperation.
7536 assert(operands.size() == 4);
7537 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7538 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7539 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007540 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7541 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007542 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7543 spv::MemorySemanticsMakeVisibleKHRMask |
7544 spv::MemorySemanticsOutputMemoryKHRMask |
7545 spv::MemorySemanticsVolatileMask)) {
7546 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7547 }
John Kessenich8985fc92020-03-03 10:25:07 -07007548 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7549 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007550 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7551 }
7552 return 0;
7553 }
7554 break;
7555 case glslang::EOpMemoryBarrier:
7556 {
7557 // This is for the extended memoryBarrier function, with three operands.
7558 // The unextended memoryBarrier() goes through createNoArgOperation.
7559 assert(operands.size() == 3);
7560 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7561 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7562 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7563 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7564 spv::MemorySemanticsMakeVisibleKHRMask |
7565 spv::MemorySemanticsOutputMemoryKHRMask |
7566 spv::MemorySemanticsVolatileMask)) {
7567 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7568 }
7569 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7570 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7571 }
7572 return 0;
7573 }
7574 break;
7575
John Kessenicha28f7a72019-08-06 07:00:58 -06007576#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007577 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007578 if (typeProxy == glslang::EbtFloat16)
7579 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007580 libCall = spv::GLSLstd450InterpolateAtSample;
7581 break;
7582 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007583 if (typeProxy == glslang::EbtFloat16)
7584 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007585 libCall = spv::GLSLstd450InterpolateAtOffset;
7586 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007587 case glslang::EOpAddCarry:
7588 opCode = spv::OpIAddCarry;
7589 typeId = builder.makeStructResultType(typeId0, typeId0);
7590 consumedOperands = 2;
7591 break;
7592 case glslang::EOpSubBorrow:
7593 opCode = spv::OpISubBorrow;
7594 typeId = builder.makeStructResultType(typeId0, typeId0);
7595 consumedOperands = 2;
7596 break;
7597 case glslang::EOpUMulExtended:
7598 opCode = spv::OpUMulExtended;
7599 typeId = builder.makeStructResultType(typeId0, typeId0);
7600 consumedOperands = 2;
7601 break;
7602 case glslang::EOpIMulExtended:
7603 opCode = spv::OpSMulExtended;
7604 typeId = builder.makeStructResultType(typeId0, typeId0);
7605 consumedOperands = 2;
7606 break;
7607 case glslang::EOpBitfieldExtract:
7608 if (isUnsigned)
7609 opCode = spv::OpBitFieldUExtract;
7610 else
7611 opCode = spv::OpBitFieldSExtract;
7612 break;
7613 case glslang::EOpBitfieldInsert:
7614 opCode = spv::OpBitFieldInsert;
7615 break;
7616
7617 case glslang::EOpFma:
7618 libCall = spv::GLSLstd450Fma;
7619 break;
7620 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007621 {
7622 libCall = spv::GLSLstd450FrexpStruct;
7623 assert(builder.isPointerType(typeId1));
7624 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007625 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007626 if (width == 16)
7627 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7628 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007629 if (builder.getNumComponents(operands[0]) == 1)
7630 frexpIntType = builder.makeIntegerType(width, true);
7631 else
John Kessenich8985fc92020-03-03 10:25:07 -07007632 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7633 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007634 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7635 consumedOperands = 1;
7636 }
John Kessenich55e7d112015-11-15 21:33:39 -07007637 break;
7638 case glslang::EOpLdexp:
7639 libCall = spv::GLSLstd450Ldexp;
7640 break;
7641
Rex Xu574ab042016-04-14 16:53:07 +08007642 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007643 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007644
John Kessenich66011cb2018-03-06 16:12:04 -07007645 case glslang::EOpSubgroupBroadcast:
7646 case glslang::EOpSubgroupBallotBitExtract:
7647 case glslang::EOpSubgroupShuffle:
7648 case glslang::EOpSubgroupShuffleXor:
7649 case glslang::EOpSubgroupShuffleUp:
7650 case glslang::EOpSubgroupShuffleDown:
7651 case glslang::EOpSubgroupClusteredAdd:
7652 case glslang::EOpSubgroupClusteredMul:
7653 case glslang::EOpSubgroupClusteredMin:
7654 case glslang::EOpSubgroupClusteredMax:
7655 case glslang::EOpSubgroupClusteredAnd:
7656 case glslang::EOpSubgroupClusteredOr:
7657 case glslang::EOpSubgroupClusteredXor:
7658 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007659 case glslang::EOpSubgroupPartitionedAdd:
7660 case glslang::EOpSubgroupPartitionedMul:
7661 case glslang::EOpSubgroupPartitionedMin:
7662 case glslang::EOpSubgroupPartitionedMax:
7663 case glslang::EOpSubgroupPartitionedAnd:
7664 case glslang::EOpSubgroupPartitionedOr:
7665 case glslang::EOpSubgroupPartitionedXor:
7666 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7667 case glslang::EOpSubgroupPartitionedInclusiveMul:
7668 case glslang::EOpSubgroupPartitionedInclusiveMin:
7669 case glslang::EOpSubgroupPartitionedInclusiveMax:
7670 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7671 case glslang::EOpSubgroupPartitionedInclusiveOr:
7672 case glslang::EOpSubgroupPartitionedInclusiveXor:
7673 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7674 case glslang::EOpSubgroupPartitionedExclusiveMul:
7675 case glslang::EOpSubgroupPartitionedExclusiveMin:
7676 case glslang::EOpSubgroupPartitionedExclusiveMax:
7677 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7678 case glslang::EOpSubgroupPartitionedExclusiveOr:
7679 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007680 return createSubgroupOperation(op, typeId, operands, typeProxy);
7681
Rex Xu9d93a232016-05-05 12:30:44 +08007682 case glslang::EOpSwizzleInvocations:
7683 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7684 libCall = spv::SwizzleInvocationsAMD;
7685 break;
7686 case glslang::EOpSwizzleInvocationsMasked:
7687 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7688 libCall = spv::SwizzleInvocationsMaskedAMD;
7689 break;
7690 case glslang::EOpWriteInvocation:
7691 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7692 libCall = spv::WriteInvocationAMD;
7693 break;
7694
7695 case glslang::EOpMin3:
7696 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7697 if (isFloat)
7698 libCall = spv::FMin3AMD;
7699 else {
7700 if (isUnsigned)
7701 libCall = spv::UMin3AMD;
7702 else
7703 libCall = spv::SMin3AMD;
7704 }
7705 break;
7706 case glslang::EOpMax3:
7707 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7708 if (isFloat)
7709 libCall = spv::FMax3AMD;
7710 else {
7711 if (isUnsigned)
7712 libCall = spv::UMax3AMD;
7713 else
7714 libCall = spv::SMax3AMD;
7715 }
7716 break;
7717 case glslang::EOpMid3:
7718 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7719 if (isFloat)
7720 libCall = spv::FMid3AMD;
7721 else {
7722 if (isUnsigned)
7723 libCall = spv::UMid3AMD;
7724 else
7725 libCall = spv::SMid3AMD;
7726 }
7727 break;
7728
7729 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007730 if (typeProxy == glslang::EbtFloat16)
7731 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007732 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7733 libCall = spv::InterpolateAtVertexAMD;
7734 break;
Chao Chen3c366992018-09-19 11:41:59 -07007735
Daniel Kochdb32b242020-03-17 20:42:47 -04007736 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007737 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007738 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007739 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007740 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007741 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007742 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007743 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007744 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007745 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007746
7747 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007748 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7749 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007750 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007751 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7752 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007753 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007754 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7755 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007756 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007757 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7758 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007759 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007760 typeId = builder.makeBoolType();
7761 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007762 break;
7763 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007764 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007765 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007766 break;
7767 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007768 typeId = builder.makeFloatType(32);
7769 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007770 break;
7771 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007772 typeId = builder.makeIntType(32);
7773 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007774 break;
7775 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007776 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007777 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007778 break;
7779 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007780 typeId = builder.makeIntType(32);
7781 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007782 break;
7783 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007784 typeId = builder.makeIntType(32);
7785 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007786 break;
7787 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007788 typeId = builder.makeIntType(32);
7789 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007790 break;
7791 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007792 typeId = builder.makeIntType(32);
7793 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007794 break;
7795 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007796 typeId = builder.makeIntType(32);
7797 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007798 break;
7799 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007800 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7801 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007802 break;
7803 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007804 typeId = builder.makeBoolType();
7805 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007806 break;
7807 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007808 typeId = builder.makeBoolType();
7809 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007810 break;
7811 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007812 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7813 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007814 break;
7815 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007816 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7817 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007818 break;
7819 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007820 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7821 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007822 break;
7823 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007824 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7825 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007826 break;
7827 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007828 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007829 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007830 break;
7831 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007832 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007833 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007834 break;
Chao Chen3c366992018-09-19 11:41:59 -07007835 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7836 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7837 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007838 case glslang::EOpCooperativeMatrixMulAdd:
7839 opCode = spv::OpCooperativeMatrixMulAddNV;
7840 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007841#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007842 default:
7843 return 0;
7844 }
7845
7846 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007847 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007848 // Use an extended instruction from the standard library.
7849 // Construct the call arguments, without modifying the original operands vector.
7850 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7851 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007852 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007853 } else if (opCode == spv::OpDot && !isFloat) {
7854 // int dot(int, int)
7855 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7856 const int componentCount = builder.getNumComponents(operands[0]);
7857 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7858 builder.setPrecision(mulOp, precision);
7859 id = builder.createCompositeExtract(mulOp, typeId, 0);
7860 for (int i = 1; i < componentCount; ++i) {
7861 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007862 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007863 }
John Kessenich2359bd02015-12-06 19:29:11 -07007864 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007865 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007866 case 0:
7867 // should all be handled by visitAggregate and createNoArgOperation
7868 assert(0);
7869 return 0;
7870 case 1:
7871 // should all be handled by createUnaryOperation
7872 assert(0);
7873 return 0;
7874 case 2:
7875 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7876 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007877 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007878 // anything 3 or over doesn't have l-value operands, so all should be consumed
7879 assert(consumedOperands == operands.size());
7880 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007881 break;
7882 }
7883 }
7884
John Kessenichb9197c82019-08-11 07:41:45 -06007885#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007886 // Decode the return types that were structures
7887 switch (op) {
7888 case glslang::EOpAddCarry:
7889 case glslang::EOpSubBorrow:
7890 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7891 id = builder.createCompositeExtract(id, typeId0, 0);
7892 break;
7893 case glslang::EOpUMulExtended:
7894 case glslang::EOpIMulExtended:
7895 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7896 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7897 break;
7898 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007899 {
7900 assert(operands.size() == 2);
7901 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7902 // "exp" is floating-point type (from HLSL intrinsic)
7903 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7904 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7905 builder.createStore(member1, operands[1]);
7906 } else
7907 // "exp" is integer type (from GLSL built-in function)
7908 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7909 id = builder.createCompositeExtract(id, typeId0, 0);
7910 }
John Kessenich55e7d112015-11-15 21:33:39 -07007911 break;
7912 default:
7913 break;
7914 }
John Kessenichb9197c82019-08-11 07:41:45 -06007915#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007916
John Kessenich32cfd492016-02-02 12:37:46 -07007917 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007918}
7919
Rex Xu9d93a232016-05-05 12:30:44 +08007920// Intrinsics with no arguments (or no return value, and no precision).
7921spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007922{
Jeff Bolz36831c92018-09-05 10:11:41 -05007923 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007924 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7925 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007926
7927 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007928 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007929 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007930 if (glslangIntermediate->usingVulkanMemoryModel()) {
7931 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7932 spv::MemorySemanticsOutputMemoryKHRMask |
7933 spv::MemorySemanticsAcquireReleaseMask);
7934 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7935 } else {
7936 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7937 }
John Kessenich82979362017-12-11 04:02:24 -07007938 } else {
7939 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7940 spv::MemorySemanticsWorkgroupMemoryMask |
7941 spv::MemorySemanticsAcquireReleaseMask);
7942 }
John Kessenich140f3df2015-06-26 16:58:36 -06007943 return 0;
7944 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007945 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7946 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007947 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007948 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007949 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7950 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007951 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007952 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007953 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7954 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007955 return 0;
7956 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007957 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7958 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007959 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007960#ifndef GLSLANG_WEB
7961 case glslang::EOpMemoryBarrierAtomicCounter:
7962 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7963 spv::MemorySemanticsAcquireReleaseMask);
7964 return 0;
7965 case glslang::EOpMemoryBarrierImage:
7966 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7967 spv::MemorySemanticsAcquireReleaseMask);
7968 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007969 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007970 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007971 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007972 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007973 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007974 case glslang::EOpDeviceMemoryBarrier:
7975 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7976 spv::MemorySemanticsImageMemoryMask |
7977 spv::MemorySemanticsAcquireReleaseMask);
7978 return 0;
7979 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7980 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7981 spv::MemorySemanticsImageMemoryMask |
7982 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007983 return 0;
7984 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007985 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7986 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007987 return 0;
7988 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007989 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7990 spv::MemorySemanticsWorkgroupMemoryMask |
7991 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007992 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007993 case glslang::EOpSubgroupBarrier:
7994 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7995 spv::MemorySemanticsAcquireReleaseMask);
7996 return spv::NoResult;
7997 case glslang::EOpSubgroupMemoryBarrier:
7998 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7999 spv::MemorySemanticsAcquireReleaseMask);
8000 return spv::NoResult;
8001 case glslang::EOpSubgroupMemoryBarrierBuffer:
8002 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8003 spv::MemorySemanticsAcquireReleaseMask);
8004 return spv::NoResult;
8005 case glslang::EOpSubgroupMemoryBarrierImage:
8006 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8007 spv::MemorySemanticsAcquireReleaseMask);
8008 return spv::NoResult;
8009 case glslang::EOpSubgroupMemoryBarrierShared:
8010 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8011 spv::MemorySemanticsAcquireReleaseMask);
8012 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008013
8014 case glslang::EOpEmitVertex:
8015 builder.createNoResultOp(spv::OpEmitVertex);
8016 return 0;
8017 case glslang::EOpEndPrimitive:
8018 builder.createNoResultOp(spv::OpEndPrimitive);
8019 return 0;
8020
John Kessenich66011cb2018-03-06 16:12:04 -07008021 case glslang::EOpSubgroupElect: {
8022 std::vector<spv::Id> operands;
8023 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8024 }
Rex Xu9d93a232016-05-05 12:30:44 +08008025 case glslang::EOpTime:
8026 {
8027 std::vector<spv::Id> args; // Dummy arguments
8028 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8029 return builder.setPrecision(id, precision);
8030 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008031 case glslang::EOpIgnoreIntersection:
8032 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008033 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008034 case glslang::EOpTerminateRay:
8035 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008036 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008037 case glslang::EOpRayQueryInitialize:
8038 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8039 return 0;
8040 case glslang::EOpRayQueryTerminate:
8041 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8042 return 0;
8043 case glslang::EOpRayQueryGenerateIntersection:
8044 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8045 return 0;
8046 case glslang::EOpRayQueryConfirmIntersection:
8047 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8048 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008049 case glslang::EOpBeginInvocationInterlock:
8050 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8051 return 0;
8052 case glslang::EOpEndInvocationInterlock:
8053 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8054 return 0;
8055
Jeff Bolzba6170b2019-07-01 09:23:23 -05008056 case glslang::EOpIsHelperInvocation:
8057 {
8058 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008059 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8060 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8061 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008062 }
8063
amhagan91fb0092019-07-10 21:14:38 -04008064 case glslang::EOpReadClockSubgroupKHR: {
8065 std::vector<spv::Id> args;
8066 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8067 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8068 builder.addCapability(spv::CapabilityShaderClockKHR);
8069 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8070 }
8071
8072 case glslang::EOpReadClockDeviceKHR: {
8073 std::vector<spv::Id> args;
8074 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8075 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8076 builder.addCapability(spv::CapabilityShaderClockKHR);
8077 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8078 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008079#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008080 default:
John Kessenich155d3512019-08-08 23:29:20 -06008081 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008082 }
John Kessenich155d3512019-08-08 23:29:20 -06008083
8084 logger->missingFunctionality("unknown operation with no arguments");
8085
8086 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008087}
8088
8089spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8090{
John Kessenich2f273362015-07-18 22:34:27 -06008091 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008092 spv::Id id;
8093 if (symbolValues.end() != iter) {
8094 id = iter->second;
8095 return id;
8096 }
8097
8098 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008099 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008100 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008101 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008102 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008103 if (forcedType.second != spv::NoType)
8104 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008105
Rex Xuc884b4a2016-06-29 15:03:44 +08008106 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008107 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8108 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8109 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008110#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008111 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008112 if (symbol->getQualifier().hasComponent())
8113 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8114 if (symbol->getQualifier().hasIndex())
8115 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008116#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008117 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008118 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008119 // atomic counters use this:
8120 if (symbol->getQualifier().hasOffset())
8121 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008122 }
8123
scygan2c864272016-05-18 18:09:17 +02008124 if (symbol->getQualifier().hasLocation())
8125 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008126 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008127 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008128 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008129 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008130 }
John Kessenich140f3df2015-06-26 16:58:36 -06008131 if (symbol->getQualifier().hasSet())
8132 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008133 else if (IsDescriptorResource(symbol->getType())) {
8134 // default to 0
8135 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8136 }
John Kessenich140f3df2015-06-26 16:58:36 -06008137 if (symbol->getQualifier().hasBinding())
8138 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008139 else if (IsDescriptorResource(symbol->getType())) {
8140 // default to 0
8141 builder.addDecoration(id, spv::DecorationBinding, 0);
8142 }
John Kessenich6c292d32016-02-15 20:58:50 -07008143 if (symbol->getQualifier().hasAttachment())
8144 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008145 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008146 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008147 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008148 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008149 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8150 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8151 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8152 }
8153 if (symbol->getQualifier().hasXfbOffset())
8154 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008155 }
8156
John Kessenichb9197c82019-08-11 07:41:45 -06008157 // add built-in variable decoration
8158 if (builtIn != spv::BuiltInMax) {
8159 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8160 }
8161
8162#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008163 if (symbol->getType().isImage()) {
8164 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008165 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8166 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008167 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008168 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008169 }
8170
John Kessenich5611c6d2018-04-05 11:25:02 -06008171 // nonuniform
8172 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8173
chaoc0ad6a4e2016-12-19 16:29:34 -08008174 if (builtIn == spv::BuiltInSampleMask) {
8175 spv::Decoration decoration;
8176 // GL_NV_sample_mask_override_coverage extension
8177 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008178 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008179 else
8180 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008181 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008182 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008183 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008184 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8185 }
8186 }
chaoc771d89f2017-01-13 01:10:53 -08008187 else if (builtIn == spv::BuiltInLayer) {
8188 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008189 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008190 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008191 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8192 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8193 }
John Kessenichb41bff62017-08-11 13:07:17 -06008194 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008195 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8196 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008197 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8198 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8199 }
8200 }
8201
chaoc6e5acae2016-12-20 13:28:52 -08008202 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008203 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008204 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008205 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8206 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008207 if (symbol->getQualifier().pervertexNV) {
8208 builder.addDecoration(id, spv::DecorationPerVertexNV);
8209 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8210 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8211 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008212
John Kessenich5d610ee2018-03-07 18:05:55 -07008213 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8214 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8215 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8216 symbol->getType().getQualifier().semanticName);
8217 }
8218
John Kessenich7015bd62019-08-01 03:28:08 -06008219 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008220 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8221 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008222 }
John Kessenichb9197c82019-08-11 07:41:45 -06008223#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008224
John Kessenich140f3df2015-06-26 16:58:36 -06008225 return id;
8226}
8227
John Kessenicha28f7a72019-08-06 07:00:58 -06008228#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008229// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8230void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8231{
8232 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008233 if (qualifier.perPrimitiveNV) {
8234 // Need to add capability/extension for fragment shader.
8235 // Mesh shader already adds this by default.
8236 if (glslangIntermediate->getStage() == EShLangFragment) {
8237 builder.addCapability(spv::CapabilityMeshShadingNV);
8238 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8239 }
Chao Chen3c366992018-09-19 11:41:59 -07008240 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008241 }
Chao Chen3c366992018-09-19 11:41:59 -07008242 if (qualifier.perViewNV)
8243 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8244 if (qualifier.perTaskNV)
8245 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8246 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008247 if (qualifier.perPrimitiveNV) {
8248 // Need to add capability/extension for fragment shader.
8249 // Mesh shader already adds this by default.
8250 if (glslangIntermediate->getStage() == EShLangFragment) {
8251 builder.addCapability(spv::CapabilityMeshShadingNV);
8252 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8253 }
Chao Chen3c366992018-09-19 11:41:59 -07008254 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008255 }
Chao Chen3c366992018-09-19 11:41:59 -07008256 if (qualifier.perViewNV)
8257 builder.addDecoration(id, spv::DecorationPerViewNV);
8258 if (qualifier.perTaskNV)
8259 builder.addDecoration(id, spv::DecorationPerTaskNV);
8260 }
8261}
8262#endif
8263
John Kessenich55e7d112015-11-15 21:33:39 -07008264// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008265// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008266//
8267// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8268//
8269// Recursively walk the nodes. The nodes form a tree whose leaves are
8270// regular constants, which themselves are trees that createSpvConstant()
8271// recursively walks. So, this function walks the "top" of the tree:
8272// - emit specialization constant-building instructions for specConstant
8273// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008274spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008275{
John Kessenich7cc0e282016-03-20 00:46:02 -06008276 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008277
qining4f4bb812016-04-03 23:55:17 -04008278 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008279 if (! node.getQualifier().specConstant) {
8280 // hand off to the non-spec-constant path
8281 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8282 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008283 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8284 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8285 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008286 }
8287
8288 // We now know we have a specialization constant to build
8289
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008290 // Extra capabilities may be needed.
8291 if (node.getType().contains8BitInt())
8292 builder.addCapability(spv::CapabilityInt8);
8293 if (node.getType().contains16BitFloat())
8294 builder.addCapability(spv::CapabilityFloat16);
8295 if (node.getType().contains16BitInt())
8296 builder.addCapability(spv::CapabilityInt16);
8297 if (node.getType().contains64BitInt())
8298 builder.addCapability(spv::CapabilityInt64);
8299 if (node.getType().containsDouble())
8300 builder.addCapability(spv::CapabilityFloat64);
8301
John Kessenichd94c0032016-05-30 19:29:40 -06008302 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008303 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8304 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8305 std::vector<spv::Id> dimConstId;
8306 for (int dim = 0; dim < 3; ++dim) {
8307 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8308 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008309 if (specConst) {
8310 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8311 glslangIntermediate->getLocalSizeSpecId(dim));
8312 }
qining4f4bb812016-04-03 23:55:17 -04008313 }
8314 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8315 }
8316
8317 // An AST node labelled as specialization constant should be a symbol node.
8318 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8319 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008320 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008321 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008322 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8323 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8324 // will set the builder into spec constant op instruction generating mode.
8325 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008326 result = accessChainLoad(sub_tree->getType());
8327 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008328 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008329 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008330 } else {
8331 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008332 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008333 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008334 builder.addName(result, sn->getName().c_str());
8335 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008336 }
qining4f4bb812016-04-03 23:55:17 -04008337
8338 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8339 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008340 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008341 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008342}
8343
John Kessenich140f3df2015-06-26 16:58:36 -06008344// Use 'consts' as the flattened glslang source of scalar constants to recursively
8345// build the aggregate SPIR-V constant.
8346//
8347// If there are not enough elements present in 'consts', 0 will be substituted;
8348// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8349//
John Kessenich8985fc92020-03-03 10:25:07 -07008350spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8351 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008352{
8353 // vector of constants for SPIR-V
8354 std::vector<spv::Id> spvConsts;
8355
8356 // Type is used for struct and array constants
8357 spv::Id typeId = convertGlslangToSpvType(glslangType);
8358
8359 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008360 glslang::TType elementType(glslangType, 0);
8361 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008362 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008363 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008364 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008365 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008366 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008367 } else if (glslangType.isCoopMat()) {
8368 glslang::TType componentType(glslangType.getBasicType());
8369 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008370 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008371 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8372 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008373 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008374 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008375 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8376 bool zero = nextConst >= consts.size();
8377 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008378 case glslang::EbtInt:
8379 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8380 break;
8381 case glslang::EbtUint:
8382 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8383 break;
8384 case glslang::EbtFloat:
8385 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8386 break;
8387 case glslang::EbtBool:
8388 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8389 break;
8390#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008391 case glslang::EbtInt8:
8392 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8393 break;
8394 case glslang::EbtUint8:
8395 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8396 break;
8397 case glslang::EbtInt16:
8398 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8399 break;
8400 case glslang::EbtUint16:
8401 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8402 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008403 case glslang::EbtInt64:
8404 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8405 break;
8406 case glslang::EbtUint64:
8407 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8408 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008409 case glslang::EbtDouble:
8410 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8411 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008412 case glslang::EbtFloat16:
8413 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8414 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008415#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008416 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008417 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008418 break;
8419 }
8420 ++nextConst;
8421 }
8422 } else {
8423 // we have a non-aggregate (scalar) constant
8424 bool zero = nextConst >= consts.size();
8425 spv::Id scalar = 0;
8426 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008427 case glslang::EbtInt:
8428 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8429 break;
8430 case glslang::EbtUint:
8431 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8432 break;
8433 case glslang::EbtFloat:
8434 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8435 break;
8436 case glslang::EbtBool:
8437 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8438 break;
8439#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008440 case glslang::EbtInt8:
8441 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8442 break;
8443 case glslang::EbtUint8:
8444 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8445 break;
8446 case glslang::EbtInt16:
8447 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8448 break;
8449 case glslang::EbtUint16:
8450 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8451 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008452 case glslang::EbtInt64:
8453 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8454 break;
8455 case glslang::EbtUint64:
8456 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8457 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008458 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008459 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008460 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008461 case glslang::EbtFloat16:
8462 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8463 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008464 case glslang::EbtReference:
8465 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8466 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8467 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008468#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008469 case glslang::EbtString:
8470 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8471 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008472 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008473 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008474 break;
8475 }
8476 ++nextConst;
8477 return scalar;
8478 }
8479
8480 return builder.makeCompositeConstant(typeId, spvConsts);
8481}
8482
John Kessenich7c1aa102015-10-15 13:29:11 -06008483// Return true if the node is a constant or symbol whose reading has no
8484// non-trivial observable cost or effect.
8485bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8486{
8487 // don't know what this is
8488 if (node == nullptr)
8489 return false;
8490
8491 // a constant is safe
8492 if (node->getAsConstantUnion() != nullptr)
8493 return true;
8494
8495 // not a symbol means non-trivial
8496 if (node->getAsSymbolNode() == nullptr)
8497 return false;
8498
8499 // a symbol, depends on what's being read
8500 switch (node->getType().getQualifier().storage) {
8501 case glslang::EvqTemporary:
8502 case glslang::EvqGlobal:
8503 case glslang::EvqIn:
8504 case glslang::EvqInOut:
8505 case glslang::EvqConst:
8506 case glslang::EvqConstReadOnly:
8507 case glslang::EvqUniform:
8508 return true;
8509 default:
8510 return false;
8511 }
qining25262b32016-05-06 17:25:16 -04008512}
John Kessenich7c1aa102015-10-15 13:29:11 -06008513
8514// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008515// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008516// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008517// Return true if trivial.
8518bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8519{
8520 if (node == nullptr)
8521 return false;
8522
John Kessenich84cc15f2017-05-24 16:44:47 -06008523 // count non scalars as trivial, as well as anything coming from HLSL
8524 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008525 return true;
8526
John Kessenich7c1aa102015-10-15 13:29:11 -06008527 // symbols and constants are trivial
8528 if (isTrivialLeaf(node))
8529 return true;
8530
8531 // otherwise, it needs to be a simple operation or one or two leaf nodes
8532
8533 // not a simple operation
8534 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8535 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8536 if (binaryNode == nullptr && unaryNode == nullptr)
8537 return false;
8538
8539 // not on leaf nodes
8540 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8541 return false;
8542
8543 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8544 return false;
8545 }
8546
8547 switch (node->getAsOperator()->getOp()) {
8548 case glslang::EOpLogicalNot:
8549 case glslang::EOpConvIntToBool:
8550 case glslang::EOpConvUintToBool:
8551 case glslang::EOpConvFloatToBool:
8552 case glslang::EOpConvDoubleToBool:
8553 case glslang::EOpEqual:
8554 case glslang::EOpNotEqual:
8555 case glslang::EOpLessThan:
8556 case glslang::EOpGreaterThan:
8557 case glslang::EOpLessThanEqual:
8558 case glslang::EOpGreaterThanEqual:
8559 case glslang::EOpIndexDirect:
8560 case glslang::EOpIndexDirectStruct:
8561 case glslang::EOpLogicalXor:
8562 case glslang::EOpAny:
8563 case glslang::EOpAll:
8564 return true;
8565 default:
8566 return false;
8567 }
8568}
8569
8570// Emit short-circuiting code, where 'right' is never evaluated unless
8571// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008572spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8573 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008574{
8575 spv::Id boolTypeId = builder.makeBoolType();
8576
8577 // emit left operand
8578 builder.clearAccessChain();
8579 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008580 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008581
8582 // Operands to accumulate OpPhi operands
8583 std::vector<spv::Id> phiOperands;
8584 // accumulate left operand's phi information
8585 phiOperands.push_back(leftId);
8586 phiOperands.push_back(builder.getBuildPoint()->getId());
8587
8588 // Make the two kinds of operation symmetric with a "!"
8589 // || => emit "if (! left) result = right"
8590 // && => emit "if ( left) result = right"
8591 //
8592 // TODO: this runtime "not" for || could be avoided by adding functionality
8593 // to 'builder' to have an "else" without an "then"
8594 if (op == glslang::EOpLogicalOr)
8595 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8596
8597 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008598 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008599
8600 // emit right operand as the "then" part of the "if"
8601 builder.clearAccessChain();
8602 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008603 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008604
8605 // accumulate left operand's phi information
8606 phiOperands.push_back(rightId);
8607 phiOperands.push_back(builder.getBuildPoint()->getId());
8608
8609 // finish the "if"
8610 ifBuilder.makeEndIf();
8611
8612 // phi together the two results
8613 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8614}
8615
John Kessenicha28f7a72019-08-06 07:00:58 -06008616#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008617// Return type Id of the imported set of extended instructions corresponds to the name.
8618// Import this set if it has not been imported yet.
8619spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8620{
8621 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8622 return extBuiltinMap[name];
8623 else {
Rex Xu51596642016-09-21 18:56:12 +08008624 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008625 spv::Id extBuiltins = builder.import(name);
8626 extBuiltinMap[name] = extBuiltins;
8627 return extBuiltins;
8628 }
8629}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008630#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008631
John Kessenich140f3df2015-06-26 16:58:36 -06008632}; // end anonymous namespace
8633
8634namespace glslang {
8635
John Kessenich68d78fd2015-07-12 19:28:10 -06008636void GetSpirvVersion(std::string& version)
8637{
John Kessenich9e55f632015-07-15 10:03:39 -06008638 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008639 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008640 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008641 version = buf;
8642}
8643
John Kessenicha372a3e2017-11-02 22:32:14 -06008644// For low-order part of the generator's magic number. Bump up
8645// when there is a change in the style (e.g., if SSA form changes,
8646// or a different instruction sequence to do something gets used).
8647int GetSpirvGeneratorVersion()
8648{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008649 // return 1; // start
8650 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008651 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008652 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008653 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008654 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8655 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008656 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenich3641ff72020-06-10 07:38:31 -06008657 // return 8; // switch to new dead block eliminator; use OpUnreachable
8658 return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
John Kessenicha372a3e2017-11-02 22:32:14 -06008659}
8660
John Kessenich140f3df2015-06-26 16:58:36 -06008661// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008662void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008663{
8664 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008665 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008666 if (out.fail())
8667 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008668 for (int i = 0; i < (int)spirv.size(); ++i) {
8669 unsigned int word = spirv[i];
8670 out.write((const char*)&word, 4);
8671 }
8672 out.close();
8673}
8674
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008675// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008676void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008677{
John Kessenich155d3512019-08-08 23:29:20 -06008678#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008679 std::ofstream out;
8680 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008681 if (out.fail())
8682 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008683 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008684 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008685 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008686 if (varName != nullptr) {
8687 out << "\t #pragma once" << std::endl;
8688 out << "const uint32_t " << varName << "[] = {" << std::endl;
8689 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008690 const int WORDS_PER_LINE = 8;
8691 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8692 out << "\t";
8693 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8694 const unsigned int word = spirv[i + j];
8695 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8696 if (i + j + 1 < (int)spirv.size()) {
8697 out << ",";
8698 }
8699 }
8700 out << std::endl;
8701 }
Flavio15017db2017-02-15 14:29:33 -08008702 if (varName != nullptr) {
8703 out << "};";
8704 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008705 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008706#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008707}
8708
John Kessenich140f3df2015-06-26 16:58:36 -06008709//
8710// Set up the glslang traversal
8711//
John Kessenich4e11b612018-08-30 16:56:59 -06008712void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008713{
Lei Zhang17535f72016-05-04 15:55:59 -04008714 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008715 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008716}
8717
John Kessenich4e11b612018-08-30 16:56:59 -06008718void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008719 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008720{
John Kessenich140f3df2015-06-26 16:58:36 -06008721 TIntermNode* root = intermediate.getTreeRoot();
8722
8723 if (root == 0)
8724 return;
8725
John Kessenich4e11b612018-08-30 16:56:59 -06008726 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008727 if (options == nullptr)
8728 options = &defaultOptions;
8729
John Kessenich4e11b612018-08-30 16:56:59 -06008730 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008731
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008732 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008733 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008734 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008735 it.dumpSpv(spirv);
8736
GregFfb03a552018-03-29 11:49:14 -06008737#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008738 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8739 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008740 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8741 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008742 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008743 prelegalization = false;
8744 }
John Kessenich717c80a2018-08-23 15:17:10 -06008745
John Kessenich4e11b612018-08-30 16:56:59 -06008746 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008747 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008748
John Kessenich717c80a2018-08-23 15:17:10 -06008749 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008750 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008751
GregFcd1f1692017-09-21 18:40:22 -06008752#endif
8753
John Kessenich4e11b612018-08-30 16:56:59 -06008754 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008755}
8756
8757}; // end namespace glslang