blob: 3e420aa263bb37474d9f05bf274abdec1dcc49bf [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 Kessenich9c14f772019-06-17 08:38:35 -06001714 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001715 // Consider adding to the OpEntryPoint interface list.
1716 // Only looking at structures if they have at least one member.
1717 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1718 spv::StorageClass sc = builder.getStorageClass(id);
1719 // Before SPIR-V 1.4, we only want to include Input and Output.
1720 // Starting with SPIR-V 1.4, we want all globals.
1721 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1722 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001723 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001724 }
John Kessenich5f77d862017-09-19 11:09:59 -06001725 }
John Kessenich9c14f772019-06-17 08:38:35 -06001726
Daniel Kochdb32b242020-03-17 20:42:47 -04001727 // If the SPIR-V type is required to be different than the AST type
1728 // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
John Kessenich9c14f772019-06-17 08:38:35 -06001729 // translate now from the SPIR-V type to the AST type, for the consuming
1730 // operation.
1731 // Note this turns it from an l-value to an r-value.
1732 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1733 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1734 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001735 }
1736
1737 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001738 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001739 // Prepare to generate code for the access
1740
1741 // L-value chains will be computed left to right. We're on the symbol now,
1742 // which is the left-most part of the access chain, so now is "clear" time,
1743 // followed by setting the base.
1744 builder.clearAccessChain();
1745
1746 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001747 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001748 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001749 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001750 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001751 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001752 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001753 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001754 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1755 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001756 builder.setAccessChainRValue(id);
1757 else
1758 builder.setAccessChainLValue(id);
1759 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001760
John Kessenichb9197c82019-08-11 07:41:45 -06001761#ifdef ENABLE_HLSL
John Kessenich5d610ee2018-03-07 18:05:55 -07001762 // Process linkage-only nodes for any special additional interface work.
1763 if (linkageOnly) {
1764 if (glslangIntermediate->getHlslFunctionality1()) {
1765 // Map implicit counter buffers to their originating buffers, which should have been
1766 // seen by now, given earlier pruning of unused counters, and preservation of order
1767 // of declaration.
1768 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1769 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1770 // Save possible originating buffers for counter buffers, keyed by
1771 // making the potential counter-buffer name.
1772 std::string keyName = symbol->getName().c_str();
1773 keyName = glslangIntermediate->addCounterBufferName(keyName);
1774 counterOriginator[keyName] = symbol;
1775 } else {
1776 // Handle a counter buffer, by finding the saved originating buffer.
1777 std::string keyName = symbol->getName().c_str();
1778 auto it = counterOriginator.find(keyName);
1779 if (it != counterOriginator.end()) {
1780 id = getSymbolId(it->second);
1781 if (id != spv::NoResult) {
1782 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001783 if (counterId != spv::NoResult) {
1784 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001785 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001786 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001787 }
1788 }
1789 }
1790 }
1791 }
1792 }
John Kessenich155d3512019-08-08 23:29:20 -06001793#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001794}
1795
1796bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1797{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001798 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Roy05a5b532020-01-03 16:21:34 +08001799 if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
1800 glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
1801 }
1802 if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
1803 glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
1804 }
John Kesseniche485c7a2017-05-31 18:50:53 -06001805
qining40887662016-04-03 22:20:42 -04001806 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1807 if (node->getType().getQualifier().isSpecConstant())
1808 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1809
John Kessenich140f3df2015-06-26 16:58:36 -06001810 // First, handle special cases
1811 switch (node->getOp()) {
1812 case glslang::EOpAssign:
1813 case glslang::EOpAddAssign:
1814 case glslang::EOpSubAssign:
1815 case glslang::EOpMulAssign:
1816 case glslang::EOpVectorTimesMatrixAssign:
1817 case glslang::EOpVectorTimesScalarAssign:
1818 case glslang::EOpMatrixTimesScalarAssign:
1819 case glslang::EOpMatrixTimesMatrixAssign:
1820 case glslang::EOpDivAssign:
1821 case glslang::EOpModAssign:
1822 case glslang::EOpAndAssign:
1823 case glslang::EOpInclusiveOrAssign:
1824 case glslang::EOpExclusiveOrAssign:
1825 case glslang::EOpLeftShiftAssign:
1826 case glslang::EOpRightShiftAssign:
1827 // A bin-op assign "a += b" means the same thing as "a = a + b"
1828 // where a is evaluated before b. For a simple assignment, GLSL
1829 // says to evaluate the left before the right. So, always, left
1830 // node then right node.
1831 {
1832 // get the left l-value, save it away
1833 builder.clearAccessChain();
1834 node->getLeft()->traverse(this);
1835 spv::Builder::AccessChain lValue = builder.getAccessChain();
1836
1837 // evaluate the right
1838 builder.clearAccessChain();
1839 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001840 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001841
1842 if (node->getOp() != glslang::EOpAssign) {
1843 // the left is also an r-value
1844 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001845 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001846
1847 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001848 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001849 TranslateNoContractionDecoration(node->getType().getQualifier()),
1850 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001851 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001852 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1853 node->getType().getBasicType());
1854
1855 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001856 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001857 }
1858
1859 // store the result
1860 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001861 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001862
1863 // assignments are expressions having an rValue after they are evaluated...
1864 builder.clearAccessChain();
1865 builder.setAccessChainRValue(rValue);
1866 }
1867 return false;
1868 case glslang::EOpIndexDirect:
1869 case glslang::EOpIndexDirectStruct:
1870 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001871 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001872 // Get the left part of the access chain.
1873 node->getLeft()->traverse(this);
1874
1875 // Add the next element in the chain
1876
David Netoa901ffe2016-06-08 14:11:40 +01001877 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001878 if (! node->getLeft()->getType().isArray() &&
1879 node->getLeft()->getType().isVector() &&
1880 node->getOp() == glslang::EOpIndexDirect) {
1881 // This is essentially a hard-coded vector swizzle of size 1,
1882 // so short circuit the access-chain stuff with a swizzle.
1883 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001884 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001885 int dummySize;
1886 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1887 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001888 glslangIntermediate->getBaseAlignmentScalar(
1889 node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001890 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001891
1892 // Load through a block reference is performed with a dot operator that
1893 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1894 // do a load and reset the access chain.
John Kessenich7015bd62019-08-01 03:28:08 -06001895 if (node->getLeft()->isReference() &&
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001896 !node->getLeft()->getType().isArray() &&
1897 node->getOp() == glslang::EOpIndexDirectStruct)
1898 {
1899 spv::Id left = accessChainLoad(node->getLeft()->getType());
1900 builder.clearAccessChain();
1901 builder.setAccessChainLValue(left);
1902 }
1903
David Netoa901ffe2016-06-08 14:11:40 +01001904 int spvIndex = glslangIndex;
1905 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1906 node->getOp() == glslang::EOpIndexDirectStruct)
1907 {
1908 // This may be, e.g., an anonymous block-member selection, which generally need
1909 // index remapping due to hidden members in anonymous blocks.
Roy05a5b532020-01-03 16:21:34 +08001910 int glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
1911 if (memberRemapper.find(glslangId) != memberRemapper.end()) {
1912 std::vector<int>& remapper = memberRemapper[glslangId];
1913 assert(remapper.size() > 0);
1914 spvIndex = remapper[glslangIndex];
1915 }
David Netoa901ffe2016-06-08 14:11:40 +01001916 }
John Kessenichebb50532016-05-16 19:22:05 -06001917
David Netoa901ffe2016-06-08 14:11:40 +01001918 // normal case for indexing array or structure or block
John Kessenich8985fc92020-03-03 10:25:07 -07001919 builder.accessChainPush(builder.makeIntConstant(spvIndex),
1920 TranslateCoherent(node->getLeft()->getType()),
1921 node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001922
1923 // Add capabilities here for accessing PointSize and clip/cull distance.
1924 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001925 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001926 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001927 }
1928 }
1929 return false;
1930 case glslang::EOpIndexIndirect:
1931 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001932 // Array, matrix, or vector indirection with variable index.
1933 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001934 // matrices are arrays of vectors, so will also work for a matrix.
1935 // Will use the access chain's 'component' for variable index into a vector.
1936
1937 // This adapter is building access chains left to right.
1938 // Set up the access chain to the left.
1939 node->getLeft()->traverse(this);
1940
1941 // save it so that computing the right side doesn't trash it
1942 spv::Builder::AccessChain partial = builder.getAccessChain();
1943
1944 // compute the next index in the chain
1945 builder.clearAccessChain();
1946 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001947 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001948
John Kessenich5611c6d2018-04-05 11:25:02 -06001949 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1950
John Kessenich140f3df2015-06-26 16:58:36 -06001951 // restore the saved access chain
1952 builder.setAccessChain(partial);
1953
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001954 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1955 int dummySize;
1956 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1957 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001958 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1959 dummySize));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001960 } else
John Kessenich8985fc92020-03-03 10:25:07 -07001961 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()),
1962 node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001963 }
1964 return false;
1965 case glslang::EOpVectorSwizzle:
1966 {
1967 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001968 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001969 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001970 int dummySize;
1971 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1972 TranslateCoherent(node->getLeft()->getType()),
John Kessenich8985fc92020-03-03 10:25:07 -07001973 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
1974 dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001975 }
1976 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001977 case glslang::EOpMatrixSwizzle:
1978 logger->missingFunctionality("matrix swizzle");
1979 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001980 case glslang::EOpLogicalOr:
1981 case glslang::EOpLogicalAnd:
1982 {
1983
1984 // These may require short circuiting, but can sometimes be done as straight
1985 // binary operations. The right operand must be short circuited if it has
1986 // side effects, and should probably be if it is complex.
1987 if (isTrivial(node->getRight()->getAsTyped()))
1988 break; // handle below as a normal binary operation
1989 // otherwise, we need to do dynamic short circuiting on the right operand
John Kessenich8985fc92020-03-03 10:25:07 -07001990 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
1991 *node->getRight()->getAsTyped());
John Kessenich7c1aa102015-10-15 13:29:11 -06001992 builder.clearAccessChain();
1993 builder.setAccessChainRValue(result);
1994 }
1995 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001996 default:
1997 break;
1998 }
1999
2000 // Assume generic binary op...
2001
John Kessenich32cfd492016-02-02 12:37:46 -07002002 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06002003 builder.clearAccessChain();
2004 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002005 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002006
John Kessenich32cfd492016-02-02 12:37:46 -07002007 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06002008 builder.clearAccessChain();
2009 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002010 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002011
John Kessenich32cfd492016-02-02 12:37:46 -07002012 // get result
John Kessenichead86222018-03-28 18:01:20 -06002013 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002014 TranslateNoContractionDecoration(node->getType().getQualifier()),
2015 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002016 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07002017 convertGlslangToSpvType(node->getType()), left, right,
2018 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002019
John Kessenich50e57562015-12-21 21:21:11 -07002020 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06002021 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002022 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07002023 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06002024 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06002025 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06002026 return false;
2027 }
John Kessenich140f3df2015-06-26 16:58:36 -06002028}
2029
John Kessenich9c14f772019-06-17 08:38:35 -06002030// Figure out what, if any, type changes are needed when accessing a specific built-in.
2031// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
2032// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
Daniel Kochdb32b242020-03-17 20:42:47 -04002033std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
John Kessenich9c14f772019-06-17 08:38:35 -06002034 const glslang::TType& glslangType)
2035{
Daniel Kochdb32b242020-03-17 20:42:47 -04002036 switch(glslangBuiltIn)
John Kessenich9c14f772019-06-17 08:38:35 -06002037 {
Daniel Kochdb32b242020-03-17 20:42:47 -04002038 case glslang::EbvSubGroupEqMask:
2039 case glslang::EbvSubGroupGeMask:
2040 case glslang::EbvSubGroupGtMask:
2041 case glslang::EbvSubGroupLeMask:
2042 case glslang::EbvSubGroupLtMask: {
John Kessenich9c14f772019-06-17 08:38:35 -06002043 // these require changing a 64-bit scaler -> a vector of 32-bit components
2044 if (glslangType.isVector())
2045 break;
2046 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
2047 builder.makeUintType(64));
2048 return ret;
2049 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002050 // There are no SPIR-V builtins defined for these and map onto original non-transposed
2051 // builtins. During visitBinary we insert a transpose
2052 case glslang::EbvWorldToObject3x4:
2053 case glslang::EbvObjectToWorld3x4: {
2054 std::pair<spv::Id, spv::Id> ret(builder.makeMatrixType(builder.makeFloatType(32), 4, 3),
2055 builder.makeMatrixType(builder.makeFloatType(32), 3, 4)
2056 );
2057 return ret;
2058 }
John Kessenich9c14f772019-06-17 08:38:35 -06002059 default:
2060 break;
2061 }
2062
2063 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
2064 return ret;
2065}
2066
2067// For an object previously identified (see getForcedType() and forceType)
2068// as needing type translations, do the translation needed for a load, turning
2069// an L-value into in R-value.
2070spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
2071{
2072 const auto forceIt = forceType.find(object);
2073 if (forceIt == forceType.end())
2074 return object;
2075
2076 spv::Id desiredTypeId = forceIt->second;
2077 spv::Id objectTypeId = builder.getTypeId(object);
2078 assert(builder.isPointerType(objectTypeId));
2079 objectTypeId = builder.getContainedTypeId(objectTypeId);
2080 if (builder.isVectorType(objectTypeId) &&
2081 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
2082 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
2083 // handle 32-bit v.xy* -> 64-bit
2084 builder.clearAccessChain();
2085 builder.setAccessChainLValue(object);
2086 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2087 std::vector<spv::Id> components;
2088 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
2089 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
2090
2091 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
2092 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
2093 builder.createCompositeConstruct(vecType, components));
2094 } else {
2095 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
2096 }
Daniel Kochdb32b242020-03-17 20:42:47 -04002097 } else if (builder.isMatrixType(objectTypeId)) {
2098 // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
2099 // and we insert a transpose after loading the original non-transposed builtins
2100 builder.clearAccessChain();
2101 builder.setAccessChainLValue(object);
2102 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
2103 return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
2104
2105 } else {
John Kessenich9c14f772019-06-17 08:38:35 -06002106 logger->missingFunctionality("forcing non 32-bit vector type");
2107 }
2108
2109 return object;
2110}
2111
John Kessenich140f3df2015-06-26 16:58:36 -06002112bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
2113{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002114 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002115
qining40887662016-04-03 22:20:42 -04002116 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2117 if (node->getType().getQualifier().isSpecConstant())
2118 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2119
John Kessenichfc51d282015-08-19 13:34:18 -06002120 spv::Id result = spv::NoResult;
2121
2122 // try texturing first
2123 result = createImageTextureFunctionCall(node);
2124 if (result != spv::NoResult) {
2125 builder.clearAccessChain();
2126 builder.setAccessChainRValue(result);
2127
2128 return false; // done with this node
2129 }
2130
2131 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002132
2133 if (node->getOp() == glslang::EOpArrayLength) {
2134 // Quite special; won't want to evaluate the operand.
2135
John Kessenich5611c6d2018-04-05 11:25:02 -06002136 // Currently, the front-end does not allow .length() on an array until it is sized,
2137 // except for the last block membeor of an SSBO.
2138 // TODO: If this changes, link-time sized arrays might show up here, and need their
2139 // size extracted.
2140
John Kessenichc9a80832015-09-12 12:17:44 -06002141 // Normal .length() would have been constant folded by the front-end.
2142 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002143 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002144
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002145 spv::Id length;
2146 if (node->getOperand()->getType().isCoopMat()) {
2147 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2148
2149 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2150 assert(builder.isCooperativeMatrixType(typeId));
2151
2152 length = builder.createCooperativeMatrixLength(typeId);
2153 } else {
2154 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2155 block->traverse(this);
John Kessenich8985fc92020-03-03 10:25:07 -07002156 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
2157 ->getConstArray()[0].getUConst();
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002158 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2159 }
John Kessenichc9a80832015-09-12 12:17:44 -06002160
John Kessenich8c869672018-11-28 07:01:37 -07002161 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2162 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2163 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002164 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2165 if (builder.isInSpecConstCodeGenMode()) {
2166 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2167 } else {
2168 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2169 }
2170 }
John Kessenich8c869672018-11-28 07:01:37 -07002171
John Kessenichc9a80832015-09-12 12:17:44 -06002172 builder.clearAccessChain();
2173 builder.setAccessChainRValue(length);
2174
2175 return false;
2176 }
2177
John Kessenichfc51d282015-08-19 13:34:18 -06002178 // Start by evaluating the operand
2179
John Kessenich8c8505c2016-07-26 12:50:38 -06002180 // Does it need a swizzle inversion? If so, evaluation is inverted;
2181 // operate first on the swizzle base, then apply the swizzle.
2182 spv::Id invertedType = spv::NoType;
John Kessenich8985fc92020-03-03 10:25:07 -07002183 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2184 invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenich8c8505c2016-07-26 12:50:38 -06002185 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2186 invertedType = getInvertedSwizzleType(*node->getOperand());
2187
John Kessenich140f3df2015-06-26 16:58:36 -06002188 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002189 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002190 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002191 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002192 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002193 operandNode = node->getOperand();
2194
2195 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002196
Rex Xufc618912015-09-09 16:42:49 +08002197 spv::Id operand = spv::NoResult;
2198
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002199 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2200
John Kessenichfb4f2332019-08-09 03:49:15 -06002201#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08002202 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2203 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002204 node->getOp() == glslang::EOpAtomicCounter ||
Neslisah Torosdagli7d37a682020-03-26 10:52:33 -04002205 node->getOp() == glslang::EOpInterpolateAtCentroid ||
2206 node->getOp() == glslang::EOpRayQueryProceed ||
2207 node->getOp() == glslang::EOpRayQueryGetRayTMin ||
2208 node->getOp() == glslang::EOpRayQueryGetRayFlags ||
2209 node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
2210 node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
2211 node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
2212 node->getOp() == glslang::EOpRayQueryTerminate ||
2213 node->getOp() == glslang::EOpRayQueryConfirmIntersection) {
Rex Xufc618912015-09-09 16:42:49 +08002214 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002215 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2216 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2217 } else
John Kessenichfb4f2332019-08-09 03:49:15 -06002218#endif
2219 {
John Kessenich32cfd492016-02-02 12:37:46 -07002220 operand = accessChainLoad(node->getOperand()->getType());
John Kessenichfb4f2332019-08-09 03:49:15 -06002221 }
John Kessenich140f3df2015-06-26 16:58:36 -06002222
John Kessenichead86222018-03-28 18:01:20 -06002223 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002224 TranslateNoContractionDecoration(node->getType().getQualifier()),
2225 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002226
2227 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002228 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002229 result = createConversion(node->getOp(), decorations, resultType(), operand,
2230 node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002231
2232 // if not, then possibly an operation
2233 if (! result)
John Kessenich8985fc92020-03-03 10:25:07 -07002234 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
2235 node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002236
2237 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002238 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002239 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenichb9197c82019-08-11 07:41:45 -06002240 decorations.addNonUniform(builder, result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002241 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002242
John Kessenich140f3df2015-06-26 16:58:36 -06002243 builder.clearAccessChain();
2244 builder.setAccessChainRValue(result);
2245
2246 return false; // done with this node
2247 }
2248
2249 // it must be a special case, check...
2250 switch (node->getOp()) {
2251 case glslang::EOpPostIncrement:
2252 case glslang::EOpPostDecrement:
2253 case glslang::EOpPreIncrement:
2254 case glslang::EOpPreDecrement:
2255 {
2256 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002257 spv::Id one = 0;
2258 if (node->getBasicType() == glslang::EbtFloat)
2259 one = builder.makeFloatConstant(1.0F);
John Kessenich39697cd2019-08-08 10:35:51 -06002260#ifndef GLSLANG_WEB
Rex Xuce31aea2016-07-29 16:13:04 +08002261 else if (node->getBasicType() == glslang::EbtDouble)
2262 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002263 else if (node->getBasicType() == glslang::EbtFloat16)
2264 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002265 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2266 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002267 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2268 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002269 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2270 one = builder.makeInt64Constant(1);
John Kessenich39697cd2019-08-08 10:35:51 -06002271#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08002272 else
2273 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002274 glslang::TOperator op;
2275 if (node->getOp() == glslang::EOpPreIncrement ||
2276 node->getOp() == glslang::EOpPostIncrement)
2277 op = glslang::EOpAdd;
2278 else
2279 op = glslang::EOpSub;
2280
John Kessenichead86222018-03-28 18:01:20 -06002281 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002282 convertGlslangToSpvType(node->getType()), operand, one,
2283 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002284 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002285
2286 // The result of operation is always stored, but conditionally the
2287 // consumed result. The consumed result is always an r-value.
2288 builder.accessChainStore(result);
2289 builder.clearAccessChain();
2290 if (node->getOp() == glslang::EOpPreIncrement ||
2291 node->getOp() == glslang::EOpPreDecrement)
2292 builder.setAccessChainRValue(result);
2293 else
2294 builder.setAccessChainRValue(operand);
2295 }
2296
2297 return false;
2298
John Kessenich155d3512019-08-08 23:29:20 -06002299#ifndef GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06002300 case glslang::EOpEmitStreamVertex:
2301 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2302 return false;
2303 case glslang::EOpEndStreamPrimitive:
2304 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2305 return false;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002306 case glslang::EOpRayQueryTerminate:
2307 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
2308 return false;
2309 case glslang::EOpRayQueryConfirmIntersection:
2310 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
2311 return false;
John Kessenich155d3512019-08-08 23:29:20 -06002312#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002313
2314 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002315 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002316 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002317 }
John Kessenich140f3df2015-06-26 16:58:36 -06002318}
2319
Jeff Bolz53134492019-06-25 13:31:10 -05002320// Construct a composite object, recursively copying members if their types don't match
2321spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
2322{
2323 for (int c = 0; c < (int)constituents.size(); ++c) {
2324 spv::Id& constituent = constituents[c];
2325 spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
2326 spv::Id rType = builder.getTypeId(constituent);
2327 if (lType != rType) {
2328 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
2329 constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
2330 } else if (builder.isStructType(rType)) {
2331 std::vector<spv::Id> rTypeConstituents;
2332 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2333 for (int i = 0; i < numrTypeConstituents; ++i) {
John Kessenich8985fc92020-03-03 10:25:07 -07002334 rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
2335 builder.getContainedTypeId(rType, i), i));
Jeff Bolz53134492019-06-25 13:31:10 -05002336 }
2337 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2338 } else {
2339 assert(builder.isArrayType(rType));
2340 std::vector<spv::Id> rTypeConstituents;
2341 int numrTypeConstituents = builder.getNumTypeConstituents(rType);
2342
2343 spv::Id elementRType = builder.getContainedTypeId(rType);
2344 for (int i = 0; i < numrTypeConstituents; ++i) {
2345 rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
2346 }
2347 constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
2348 }
2349 }
2350 }
2351 return builder.createCompositeConstruct(resultTypeId, constituents);
2352}
2353
John Kessenich140f3df2015-06-26 16:58:36 -06002354bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2355{
qining27e04a02016-04-14 16:40:20 -04002356 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2357 if (node->getType().getQualifier().isSpecConstant())
2358 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2359
John Kessenichfc51d282015-08-19 13:34:18 -06002360 spv::Id result = spv::NoResult;
Cody Northrop4d2298b2020-04-13 21:59:49 -06002361 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2362 std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
2363 // SPIR-V, for an out parameter
2364 std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
John Kessenichbbbd9a22020-03-03 07:21:37 -07002365
John Kessenich8985fc92020-03-03 10:25:07 -07002366 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
2367 invertedType :
2368 convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002369
2370 // try texturing
2371 result = createImageTextureFunctionCall(node);
2372 if (result != spv::NoResult) {
2373 builder.clearAccessChain();
2374 builder.setAccessChainRValue(result);
2375
2376 return false;
John Kessenicha28f7a72019-08-06 07:00:58 -06002377 }
2378#ifndef GLSLANG_WEB
2379 else if (node->getOp() == glslang::EOpImageStore ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002380 node->getOp() == glslang::EOpImageStoreLod ||
Jeff Bolz36831c92018-09-05 10:11:41 -05002381 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002382 // "imageStore" is a special case, which has no result
2383 return false;
2384 }
John Kessenicha28f7a72019-08-06 07:00:58 -06002385#endif
John Kessenichfc51d282015-08-19 13:34:18 -06002386
John Kessenich140f3df2015-06-26 16:58:36 -06002387 glslang::TOperator binOp = glslang::EOpNull;
2388 bool reduceComparison = true;
2389 bool isMatrix = false;
2390 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002391 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002392
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002393 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2394
John Kessenich140f3df2015-06-26 16:58:36 -06002395 assert(node->getOp());
2396
John Kessenichf6640762016-08-01 19:44:00 -06002397 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002398
2399 switch (node->getOp()) {
2400 case glslang::EOpSequence:
2401 {
2402 if (preVisit)
2403 ++sequenceDepth;
2404 else
2405 --sequenceDepth;
2406
2407 if (sequenceDepth == 1) {
2408 // If this is the parent node of all the functions, we want to see them
2409 // early, so all call points have actual SPIR-V functions to reference.
2410 // In all cases, still let the traverser visit the children for us.
2411 makeFunctions(node->getAsAggregate()->getSequence());
2412
John Kessenich6fccb3c2016-09-19 16:01:41 -06002413 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002414 // anything else gets there, so visit out of order, doing them all now.
2415 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2416
John Kessenich6a60c2f2016-12-08 21:01:59 -07002417 // 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 -06002418 // so do them manually.
2419 visitFunctions(node->getAsAggregate()->getSequence());
2420
2421 return false;
2422 }
2423
2424 return true;
2425 }
2426 case glslang::EOpLinkerObjects:
2427 {
2428 if (visit == glslang::EvPreVisit)
2429 linkageOnly = true;
2430 else
2431 linkageOnly = false;
2432
2433 return true;
2434 }
2435 case glslang::EOpComma:
2436 {
2437 // processing from left to right naturally leaves the right-most
2438 // lying around in the access chain
2439 glslang::TIntermSequence& glslangOperands = node->getSequence();
2440 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2441 glslangOperands[i]->traverse(this);
2442
2443 return false;
2444 }
2445 case glslang::EOpFunction:
2446 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002447 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002448 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002449 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002450 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002451 } else {
2452 handleFunctionEntry(node);
2453 }
2454 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002455 if (inEntryPoint)
2456 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002457 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002458 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002459 }
2460
2461 return true;
2462 case glslang::EOpParameters:
2463 // Parameters will have been consumed by EOpFunction processing, but not
2464 // the body, so we still visited the function node's children, making this
2465 // child redundant.
2466 return false;
2467 case glslang::EOpFunctionCall:
2468 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002469 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002470 if (node->isUserDefined())
2471 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07002472 if (result) {
2473 builder.clearAccessChain();
2474 builder.setAccessChainRValue(result);
2475 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002476 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002477
2478 return false;
2479 }
2480 case glslang::EOpConstructMat2x2:
2481 case glslang::EOpConstructMat2x3:
2482 case glslang::EOpConstructMat2x4:
2483 case glslang::EOpConstructMat3x2:
2484 case glslang::EOpConstructMat3x3:
2485 case glslang::EOpConstructMat3x4:
2486 case glslang::EOpConstructMat4x2:
2487 case glslang::EOpConstructMat4x3:
2488 case glslang::EOpConstructMat4x4:
2489 case glslang::EOpConstructDMat2x2:
2490 case glslang::EOpConstructDMat2x3:
2491 case glslang::EOpConstructDMat2x4:
2492 case glslang::EOpConstructDMat3x2:
2493 case glslang::EOpConstructDMat3x3:
2494 case glslang::EOpConstructDMat3x4:
2495 case glslang::EOpConstructDMat4x2:
2496 case glslang::EOpConstructDMat4x3:
2497 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002498 case glslang::EOpConstructIMat2x2:
2499 case glslang::EOpConstructIMat2x3:
2500 case glslang::EOpConstructIMat2x4:
2501 case glslang::EOpConstructIMat3x2:
2502 case glslang::EOpConstructIMat3x3:
2503 case glslang::EOpConstructIMat3x4:
2504 case glslang::EOpConstructIMat4x2:
2505 case glslang::EOpConstructIMat4x3:
2506 case glslang::EOpConstructIMat4x4:
2507 case glslang::EOpConstructUMat2x2:
2508 case glslang::EOpConstructUMat2x3:
2509 case glslang::EOpConstructUMat2x4:
2510 case glslang::EOpConstructUMat3x2:
2511 case glslang::EOpConstructUMat3x3:
2512 case glslang::EOpConstructUMat3x4:
2513 case glslang::EOpConstructUMat4x2:
2514 case glslang::EOpConstructUMat4x3:
2515 case glslang::EOpConstructUMat4x4:
2516 case glslang::EOpConstructBMat2x2:
2517 case glslang::EOpConstructBMat2x3:
2518 case glslang::EOpConstructBMat2x4:
2519 case glslang::EOpConstructBMat3x2:
2520 case glslang::EOpConstructBMat3x3:
2521 case glslang::EOpConstructBMat3x4:
2522 case glslang::EOpConstructBMat4x2:
2523 case glslang::EOpConstructBMat4x3:
2524 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002525 case glslang::EOpConstructF16Mat2x2:
2526 case glslang::EOpConstructF16Mat2x3:
2527 case glslang::EOpConstructF16Mat2x4:
2528 case glslang::EOpConstructF16Mat3x2:
2529 case glslang::EOpConstructF16Mat3x3:
2530 case glslang::EOpConstructF16Mat3x4:
2531 case glslang::EOpConstructF16Mat4x2:
2532 case glslang::EOpConstructF16Mat4x3:
2533 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002534 isMatrix = true;
2535 // fall through
2536 case glslang::EOpConstructFloat:
2537 case glslang::EOpConstructVec2:
2538 case glslang::EOpConstructVec3:
2539 case glslang::EOpConstructVec4:
2540 case glslang::EOpConstructDouble:
2541 case glslang::EOpConstructDVec2:
2542 case glslang::EOpConstructDVec3:
2543 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002544 case glslang::EOpConstructFloat16:
2545 case glslang::EOpConstructF16Vec2:
2546 case glslang::EOpConstructF16Vec3:
2547 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002548 case glslang::EOpConstructBool:
2549 case glslang::EOpConstructBVec2:
2550 case glslang::EOpConstructBVec3:
2551 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002552 case glslang::EOpConstructInt8:
2553 case glslang::EOpConstructI8Vec2:
2554 case glslang::EOpConstructI8Vec3:
2555 case glslang::EOpConstructI8Vec4:
2556 case glslang::EOpConstructUint8:
2557 case glslang::EOpConstructU8Vec2:
2558 case glslang::EOpConstructU8Vec3:
2559 case glslang::EOpConstructU8Vec4:
2560 case glslang::EOpConstructInt16:
2561 case glslang::EOpConstructI16Vec2:
2562 case glslang::EOpConstructI16Vec3:
2563 case glslang::EOpConstructI16Vec4:
2564 case glslang::EOpConstructUint16:
2565 case glslang::EOpConstructU16Vec2:
2566 case glslang::EOpConstructU16Vec3:
2567 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002568 case glslang::EOpConstructInt:
2569 case glslang::EOpConstructIVec2:
2570 case glslang::EOpConstructIVec3:
2571 case glslang::EOpConstructIVec4:
2572 case glslang::EOpConstructUint:
2573 case glslang::EOpConstructUVec2:
2574 case glslang::EOpConstructUVec3:
2575 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002576 case glslang::EOpConstructInt64:
2577 case glslang::EOpConstructI64Vec2:
2578 case glslang::EOpConstructI64Vec3:
2579 case glslang::EOpConstructI64Vec4:
2580 case glslang::EOpConstructUint64:
2581 case glslang::EOpConstructU64Vec2:
2582 case glslang::EOpConstructU64Vec3:
2583 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002584 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002585 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002586 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002587 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002588 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002589 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002590 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002591 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002592 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002593 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002594 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002595 else if (node->getOp() == glslang::EOpConstructStruct ||
2596 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2597 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002598 std::vector<spv::Id> constituents;
2599 for (int c = 0; c < (int)arguments.size(); ++c)
2600 constituents.push_back(arguments[c]);
Jeff Bolz53134492019-06-25 13:31:10 -05002601 constructed = createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002602 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002603 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002604 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002605 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002606
2607 builder.clearAccessChain();
2608 builder.setAccessChainRValue(constructed);
2609
2610 return false;
2611 }
2612
2613 // These six are component-wise compares with component-wise results.
2614 // Forward on to createBinaryOperation(), requesting a vector result.
2615 case glslang::EOpLessThan:
2616 case glslang::EOpGreaterThan:
2617 case glslang::EOpLessThanEqual:
2618 case glslang::EOpGreaterThanEqual:
2619 case glslang::EOpVectorEqual:
2620 case glslang::EOpVectorNotEqual:
2621 {
2622 // Map the operation to a binary
2623 binOp = node->getOp();
2624 reduceComparison = false;
2625 switch (node->getOp()) {
2626 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2627 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2628 default: binOp = node->getOp(); break;
2629 }
2630
2631 break;
2632 }
2633 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002634 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002635 binOp = glslang::EOpMul;
2636 break;
2637 case glslang::EOpOuterProduct:
2638 // two vectors multiplied to make a matrix
2639 binOp = glslang::EOpOuterProduct;
2640 break;
2641 case glslang::EOpDot:
2642 {
qining25262b32016-05-06 17:25:16 -04002643 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002644 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002645 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002646 binOp = glslang::EOpMul;
2647 break;
2648 }
2649 case glslang::EOpMod:
2650 // when an aggregate, this is the floating-point mod built-in function,
2651 // which can be emitted by the one in createBinaryOperation()
2652 binOp = glslang::EOpMod;
2653 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002654
John Kessenich140f3df2015-06-26 16:58:36 -06002655 case glslang::EOpEmitVertex:
2656 case glslang::EOpEndPrimitive:
2657 case glslang::EOpBarrier:
2658 case glslang::EOpMemoryBarrier:
2659 case glslang::EOpMemoryBarrierAtomicCounter:
2660 case glslang::EOpMemoryBarrierBuffer:
2661 case glslang::EOpMemoryBarrierImage:
2662 case glslang::EOpMemoryBarrierShared:
2663 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002664 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002665 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002666 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002667 case glslang::EOpWorkgroupMemoryBarrier:
2668 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002669 case glslang::EOpSubgroupBarrier:
2670 case glslang::EOpSubgroupMemoryBarrier:
2671 case glslang::EOpSubgroupMemoryBarrierBuffer:
2672 case glslang::EOpSubgroupMemoryBarrierImage:
2673 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002674 noReturnValue = true;
2675 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2676 break;
2677
John Kessenich426394d2015-07-23 10:22:48 -06002678 case glslang::EOpAtomicAdd:
2679 case glslang::EOpAtomicMin:
2680 case glslang::EOpAtomicMax:
2681 case glslang::EOpAtomicAnd:
2682 case glslang::EOpAtomicOr:
2683 case glslang::EOpAtomicXor:
2684 case glslang::EOpAtomicExchange:
2685 case glslang::EOpAtomicCompSwap:
2686 atomic = true;
2687 break;
2688
John Kesseniche5eee8f2019-10-18 01:03:11 -06002689#ifndef GLSLANG_WEB
2690 case glslang::EOpAtomicStore:
2691 noReturnValue = true;
2692 // fallthrough
2693 case glslang::EOpAtomicLoad:
2694 atomic = true;
2695 break;
2696
John Kessenich0d0c6d32017-07-23 16:08:26 -06002697 case glslang::EOpAtomicCounterAdd:
2698 case glslang::EOpAtomicCounterSubtract:
2699 case glslang::EOpAtomicCounterMin:
2700 case glslang::EOpAtomicCounterMax:
2701 case glslang::EOpAtomicCounterAnd:
2702 case glslang::EOpAtomicCounterOr:
2703 case glslang::EOpAtomicCounterXor:
2704 case glslang::EOpAtomicCounterExchange:
2705 case glslang::EOpAtomicCounterCompSwap:
2706 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2707 builder.addCapability(spv::CapabilityAtomicStorageOps);
2708 atomic = true;
2709 break;
2710
Ian Romanickb3bd4022019-01-21 08:57:25 -08002711 case glslang::EOpAbsDifference:
2712 case glslang::EOpAddSaturate:
2713 case glslang::EOpSubSaturate:
2714 case glslang::EOpAverage:
2715 case glslang::EOpAverageRounded:
2716 case glslang::EOpMul32x16:
2717 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
2718 builder.addExtension("SPV_INTEL_shader_integer_functions2");
2719 binOp = node->getOp();
2720 break;
2721
Daniel Kochdb32b242020-03-17 20:42:47 -04002722 case glslang::EOpIgnoreIntersection:
2723 case glslang::EOpTerminateRay:
2724 case glslang::EOpTrace:
2725 case glslang::EOpExecuteCallable:
Chao Chen3c366992018-09-19 11:41:59 -07002726 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2727 noReturnValue = true;
2728 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04002729 case glslang::EOpRayQueryInitialize:
2730 case glslang::EOpRayQueryTerminate:
2731 case glslang::EOpRayQueryGenerateIntersection:
2732 case glslang::EOpRayQueryConfirmIntersection:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002733 builder.addExtension("SPV_KHR_ray_query");
2734 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
Torosdagli06c2eee2020-03-19 11:09:57 -04002735 noReturnValue = true;
2736 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002737 case glslang::EOpRayQueryProceed:
2738 case glslang::EOpRayQueryGetIntersectionType:
2739 case glslang::EOpRayQueryGetRayTMin:
2740 case glslang::EOpRayQueryGetRayFlags:
2741 case glslang::EOpRayQueryGetIntersectionT:
2742 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2743 case glslang::EOpRayQueryGetIntersectionInstanceId:
2744 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2745 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2746 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2747 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2748 case glslang::EOpRayQueryGetIntersectionFrontFace:
2749 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
2750 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2751 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2752 case glslang::EOpRayQueryGetWorldRayDirection:
2753 case glslang::EOpRayQueryGetWorldRayOrigin:
2754 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2755 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2756 builder.addExtension("SPV_KHR_ray_query");
2757 builder.addCapability(spv::CapabilityRayQueryProvisionalKHR);
2758 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002759 case glslang::EOpCooperativeMatrixLoad:
2760 case glslang::EOpCooperativeMatrixStore:
2761 noReturnValue = true;
2762 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002763 case glslang::EOpBeginInvocationInterlock:
2764 case glslang::EOpEndInvocationInterlock:
2765 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2766 noReturnValue = true;
2767 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002768#endif
Chao Chen3c366992018-09-19 11:41:59 -07002769
Jeff Bolz04d73732019-05-31 13:06:01 -05002770 case glslang::EOpDebugPrintf:
2771 noReturnValue = true;
2772 break;
2773
John Kessenich140f3df2015-06-26 16:58:36 -06002774 default:
2775 break;
2776 }
2777
2778 //
2779 // See if it maps to a regular operation.
2780 //
John Kessenich140f3df2015-06-26 16:58:36 -06002781 if (binOp != glslang::EOpNull) {
2782 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2783 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2784 assert(left && right);
2785
2786 builder.clearAccessChain();
2787 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002788 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002789
2790 builder.clearAccessChain();
2791 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002792 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002793
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002794 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002795 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002796 TranslateNoContractionDecoration(node->getType().getQualifier()),
2797 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002798 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002799 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002800 left->getType().getBasicType(), reduceComparison);
2801
2802 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002803 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002804 builder.clearAccessChain();
2805 builder.setAccessChainRValue(result);
2806
2807 return false;
2808 }
2809
John Kessenich426394d2015-07-23 10:22:48 -06002810 //
2811 // Create the list of operands.
2812 //
John Kessenich140f3df2015-06-26 16:58:36 -06002813 glslang::TIntermSequence& glslangOperands = node->getSequence();
2814 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002815 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002816 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002817 // special case l-value operands; there are just a few
2818 bool lvalue = false;
2819 switch (node->getOp()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002820 case glslang::EOpModf:
2821 if (arg == 1)
2822 lvalue = true;
2823 break;
John Kesseniche5eee8f2019-10-18 01:03:11 -06002824
Torosdagli06c2eee2020-03-19 11:09:57 -04002825 case glslang::EOpRayQueryInitialize:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04002826 case glslang::EOpRayQueryTerminate:
2827 case glslang::EOpRayQueryConfirmIntersection:
2828 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04002829 case glslang::EOpRayQueryGenerateIntersection:
2830 case glslang::EOpRayQueryGetIntersectionType:
2831 case glslang::EOpRayQueryGetIntersectionT:
2832 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
2833 case glslang::EOpRayQueryGetIntersectionInstanceId:
2834 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
2835 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
2836 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
2837 case glslang::EOpRayQueryGetIntersectionBarycentrics:
2838 case glslang::EOpRayQueryGetIntersectionFrontFace:
2839 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
2840 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
2841 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
2842 case glslang::EOpRayQueryGetIntersectionWorldToObject:
2843 if (arg == 0)
2844 lvalue = true;
2845 break;
2846
John Kesseniche5eee8f2019-10-18 01:03:11 -06002847 case glslang::EOpAtomicAdd:
2848 case glslang::EOpAtomicMin:
2849 case glslang::EOpAtomicMax:
2850 case glslang::EOpAtomicAnd:
2851 case glslang::EOpAtomicOr:
2852 case glslang::EOpAtomicXor:
2853 case glslang::EOpAtomicExchange:
2854 case glslang::EOpAtomicCompSwap:
2855 if (arg == 0)
2856 lvalue = true;
2857 break;
2858
John Kessenicha28f7a72019-08-06 07:00:58 -06002859#ifndef GLSLANG_WEB
2860 case glslang::EOpFrexp:
2861 if (arg == 1)
2862 lvalue = true;
2863 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002864 case glslang::EOpInterpolateAtSample:
2865 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002866 case glslang::EOpInterpolateAtVertex:
John Kessenich8c8505c2016-07-26 12:50:38 -06002867 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002868 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002869
2870 // Does it need a swizzle inversion? If so, evaluation is inverted;
2871 // operate first on the swizzle base, then apply the swizzle.
John Kessenichbbbd9a22020-03-03 07:21:37 -07002872 // That is, we transform
2873 //
2874 // interpolate(v.zy) -> interpolate(v).zy
2875 //
John Kessenichecba76f2017-01-06 00:34:48 -07002876 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002877 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
John Kessenich8985fc92020-03-03 10:25:07 -07002878 invertedType = convertGlslangToSpvType(
2879 glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
John Kessenich8c8505c2016-07-26 12:50:38 -06002880 }
Rex Xu7a26c172015-12-08 17:12:09 +08002881 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05002882 case glslang::EOpAtomicLoad:
2883 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002884 case glslang::EOpAtomicCounterAdd:
2885 case glslang::EOpAtomicCounterSubtract:
2886 case glslang::EOpAtomicCounterMin:
2887 case glslang::EOpAtomicCounterMax:
2888 case glslang::EOpAtomicCounterAnd:
2889 case glslang::EOpAtomicCounterOr:
2890 case glslang::EOpAtomicCounterXor:
2891 case glslang::EOpAtomicCounterExchange:
2892 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002893 if (arg == 0)
2894 lvalue = true;
2895 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002896 case glslang::EOpAddCarry:
2897 case glslang::EOpSubBorrow:
2898 if (arg == 2)
2899 lvalue = true;
2900 break;
2901 case glslang::EOpUMulExtended:
2902 case glslang::EOpIMulExtended:
2903 if (arg >= 2)
2904 lvalue = true;
2905 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002906 case glslang::EOpCooperativeMatrixLoad:
2907 if (arg == 0 || arg == 1)
2908 lvalue = true;
2909 break;
2910 case glslang::EOpCooperativeMatrixStore:
2911 if (arg == 1)
2912 lvalue = true;
2913 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06002914#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002915 default:
2916 break;
2917 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002918 builder.clearAccessChain();
2919 if (invertedType != spv::NoType && arg == 0)
2920 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2921 else
2922 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002923
John Kessenichb9197c82019-08-11 07:41:45 -06002924#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002925 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2926 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2927
2928 if (arg == 1) {
2929 // fold "element" parameter into the access chain
2930 spv::Builder::AccessChain save = builder.getAccessChain();
2931 builder.clearAccessChain();
2932 glslangOperands[2]->traverse(this);
2933
2934 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2935
2936 builder.setAccessChain(save);
2937
2938 // Point to the first element of the array.
John Kessenich8985fc92020-03-03 10:25:07 -07002939 builder.accessChainPush(elementId,
2940 TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2941 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002942
2943 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2944 unsigned int alignment = builder.getAccessChain().alignment;
2945
2946 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2947 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2948 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2949 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2950 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
John Kessenich8985fc92020-03-03 10:25:07 -07002951 if (builder.getStorageClass(builder.getAccessChain().base) ==
2952 spv::StorageClassPhysicalStorageBufferEXT) {
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002953 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2954 }
2955
2956 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2957
2958 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2959 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2960 }
2961
John Kessenich8985fc92020-03-03 10:25:07 -07002962 if (memoryAccess &
2963 (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2964 memoryAccessOperands.push_back(spv::IdImmediate(true,
2965 builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002966 }
2967 } else if (arg == 2) {
2968 continue;
2969 }
2970 }
John Kessenichb9197c82019-08-11 07:41:45 -06002971#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002972
John Kessenichbbbd9a22020-03-03 07:21:37 -07002973 // for l-values, pass the address, for r-values, pass the value
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002974 if (lvalue) {
John Kessenichbbbd9a22020-03-03 07:21:37 -07002975 if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
2976 // SPIR-V cannot represent an l-value containing a swizzle that doesn't
2977 // reduce to a simple access chain. So, we need a temporary vector to
2978 // receive the result, and must later swizzle that into the original
2979 // l-value.
Cody Northrop4d2298b2020-04-13 21:59:49 -06002980 complexLvalues.push_back(builder.getAccessChain());
2981 temporaryLvalues.push_back(builder.createVariable(spv::StorageClassFunction,
2982 builder.accessChainGetInferredType(), "swizzleTemp"));
2983 operands.push_back(temporaryLvalues.back());
John Kessenichbbbd9a22020-03-03 07:21:37 -07002984 } else {
2985 operands.push_back(builder.accessChainGetLValue());
2986 }
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002987 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2988 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2989 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002990 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Torosdagli06c2eee2020-03-19 11:09:57 -04002991 glslang::TOperator glslangOp = node->getOp();
2992 if (arg == 1 &&
2993 (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
2994 glslangOp == glslang::EOpRayQueryGetIntersectionT ||
2995 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
2996 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
2997 glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
2998 glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
2999 glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
3000 glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
3001 glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
3002 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
3003 glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
3004 glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
3005 glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject
3006 )) {
3007 bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
3008 operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
3009 }
3010 else {
3011 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
3012 }
3013
John Kesseniche485c7a2017-05-31 18:50:53 -06003014 }
John Kessenich140f3df2015-06-26 16:58:36 -06003015 }
John Kessenich426394d2015-07-23 10:22:48 -06003016
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003017 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichb9197c82019-08-11 07:41:45 -06003018#ifndef GLSLANG_WEB
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003019 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
3020 std::vector<spv::IdImmediate> idImmOps;
3021
3022 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3023 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3024 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3025 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3026 // get the pointee type
3027 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
3028 assert(builder.isCooperativeMatrixType(typeId));
3029 // do the op
3030 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
3031 // store the result to the pointer (out param 'm')
3032 builder.createStore(result, operands[0]);
3033 result = 0;
3034 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
3035 std::vector<spv::IdImmediate> idImmOps;
3036
3037 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
3038 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
3039 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
3040 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
3041 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
3042
3043 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
3044 result = 0;
John Kessenichb9197c82019-08-11 07:41:45 -06003045 } else
3046#endif
John Kesseniche5eee8f2019-10-18 01:03:11 -06003047 if (atomic) {
3048 // Handle all atomics
John Kessenich8985fc92020-03-03 10:25:07 -07003049 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
3050 lvalueCoherentFlags);
Jeff Bolz04d73732019-05-31 13:06:01 -05003051 } else if (node->getOp() == glslang::EOpDebugPrintf) {
3052 if (!nonSemanticDebugPrintf) {
3053 nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
3054 }
3055 result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
3056 builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
John Kesseniche5eee8f2019-10-18 01:03:11 -06003057 } else {
John Kessenich426394d2015-07-23 10:22:48 -06003058 // Pass through to generic operations.
3059 switch (glslangOperands.size()) {
3060 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06003061 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06003062 break;
3063 case 1:
John Kessenichead86222018-03-28 18:01:20 -06003064 {
3065 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06003066 TranslateNoContractionDecoration(node->getType().getQualifier()),
3067 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06003068 result = createUnaryOperation(
3069 node->getOp(), decorations,
3070 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05003071 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06003072 }
John Kessenich426394d2015-07-23 10:22:48 -06003073 break;
3074 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06003075 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06003076 break;
3077 }
Cody Northrop4d2298b2020-04-13 21:59:49 -06003078
John Kessenichbbbd9a22020-03-03 07:21:37 -07003079 if (invertedType != spv::NoResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003080 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
Cody Northrop4d2298b2020-04-13 21:59:49 -06003081
3082 for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
3083 builder.setAccessChain(complexLvalues[i]);
3084 builder.accessChainStore(builder.createLoad(temporaryLvalues[i]));
John Kessenichbbbd9a22020-03-03 07:21:37 -07003085 }
John Kessenich140f3df2015-06-26 16:58:36 -06003086 }
3087
3088 if (noReturnValue)
3089 return false;
3090
3091 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04003092 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07003093 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06003094 } else {
3095 builder.clearAccessChain();
3096 builder.setAccessChainRValue(result);
3097 return false;
3098 }
3099}
3100
John Kessenich433e9ff2017-01-26 20:31:11 -07003101// This path handles both if-then-else and ?:
3102// The if-then-else has a node type of void, while
3103// ?: has either a void or a non-void node type
3104//
3105// Leaving the result, when not void:
3106// GLSL only has r-values as the result of a :?, but
3107// if we have an l-value, that can be more efficient if it will
3108// become the base of a complex r-value expression, because the
3109// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06003110bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
3111{
John Kessenich0c1e71a2019-01-10 18:23:06 +07003112 // see if OpSelect can handle it
3113 const auto isOpSelectable = [&]() {
3114 if (node->getBasicType() == glslang::EbtVoid)
3115 return false;
3116 // OpSelect can do all other types starting with SPV 1.4
3117 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
3118 // pre-1.4, only scalars and vectors can be handled
3119 if ((!node->getType().isScalar() && !node->getType().isVector()))
3120 return false;
3121 }
3122 return true;
3123 };
3124
John Kessenich4bee5312018-02-20 21:29:05 -07003125 // See if it simple and safe, or required, to execute both sides.
3126 // Crucially, side effects must be either semantically required or avoided,
3127 // and there are performance trade-offs.
3128 // Return true if required or a good idea (and safe) to execute both sides,
3129 // false otherwise.
3130 const auto bothSidesPolicy = [&]() -> bool {
3131 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07003132 if (node->getTrueBlock() == nullptr ||
3133 node->getFalseBlock() == nullptr)
3134 return false;
3135
John Kessenich4bee5312018-02-20 21:29:05 -07003136 // required? (unless we write additional code to look for side effects
3137 // and make performance trade-offs if none are present)
3138 if (!node->getShortCircuit())
3139 return true;
3140
3141 // if not required to execute both, decide based on performance/practicality...
3142
John Kessenich0c1e71a2019-01-10 18:23:06 +07003143 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07003144 return false;
3145
John Kessenich433e9ff2017-01-26 20:31:11 -07003146 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
3147 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
3148
3149 // return true if a single operand to ? : is okay for OpSelect
3150 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003151 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07003152 };
3153
3154 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
3155 operandOkay(node->getFalseBlock()->getAsTyped());
3156 };
3157
John Kessenich4bee5312018-02-20 21:29:05 -07003158 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
3159 // emit the condition before doing anything with selection
3160 node->getCondition()->traverse(this);
3161 spv::Id condition = accessChainLoad(node->getCondition()->getType());
3162
3163 // Find a way of executing both sides and selecting the right result.
3164 const auto executeBothSides = [&]() -> void {
3165 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07003166 node->getTrueBlock()->traverse(this);
3167 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3168 node->getFalseBlock()->traverse(this);
3169 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
3170
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003171 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003172
John Kessenich4bee5312018-02-20 21:29:05 -07003173 // done if void
3174 if (node->getBasicType() == glslang::EbtVoid)
3175 return;
John Kesseniche434ad92017-03-30 10:09:28 -06003176
John Kessenich4bee5312018-02-20 21:29:05 -07003177 // emit code to select between trueValue and falseValue
3178
3179 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07003180 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07003181 // Emit OpSelect for this selection.
3182
3183 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07003184 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
3185 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07003186 condition = builder.smearScalar(spv::NoPrecision, condition,
3187 builder.makeVectorType(builder.makeBoolType(),
3188 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07003189 }
John Kessenich4bee5312018-02-20 21:29:05 -07003190
3191 // OpSelect
3192 result = builder.createTriOp(spv::OpSelect,
3193 convertGlslangToSpvType(node->getType()), condition,
3194 trueValue, falseValue);
3195
3196 builder.clearAccessChain();
3197 builder.setAccessChainRValue(result);
3198 } else {
3199 // We need control flow to select the result.
3200 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
3201 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
3202
3203 // Selection control:
3204 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3205
3206 // make an "if" based on the value created by the condition
3207 spv::Builder::If ifBuilder(condition, control, builder);
3208
3209 // emit the "then" statement
3210 builder.createStore(trueValue, result);
3211 ifBuilder.makeBeginElse();
3212 // emit the "else" statement
3213 builder.createStore(falseValue, result);
3214
3215 // finish off the control flow
3216 ifBuilder.makeEndIf();
3217
3218 builder.clearAccessChain();
3219 builder.setAccessChainLValue(result);
3220 }
John Kessenich433e9ff2017-01-26 20:31:11 -07003221 };
3222
John Kessenich4bee5312018-02-20 21:29:05 -07003223 // Execute the one side needed, as per the condition
3224 const auto executeOneSide = [&]() {
3225 // Always emit control flow.
3226 if (node->getBasicType() != glslang::EbtVoid)
3227 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07003228
John Kessenich4bee5312018-02-20 21:29:05 -07003229 // Selection control:
3230 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
3231
3232 // make an "if" based on the value created by the condition
3233 spv::Builder::If ifBuilder(condition, control, builder);
3234
3235 // emit the "then" statement
3236 if (node->getTrueBlock() != nullptr) {
3237 node->getTrueBlock()->traverse(this);
3238 if (result != spv::NoResult)
3239 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
3240 }
3241
3242 if (node->getFalseBlock() != nullptr) {
3243 ifBuilder.makeBeginElse();
3244 // emit the "else" statement
3245 node->getFalseBlock()->traverse(this);
3246 if (result != spv::NoResult)
3247 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
3248 }
3249
3250 // finish off the control flow
3251 ifBuilder.makeEndIf();
3252
3253 if (result != spv::NoResult) {
3254 builder.clearAccessChain();
3255 builder.setAccessChainLValue(result);
3256 }
3257 };
3258
3259 // Try for OpSelect (or a requirement to execute both sides)
3260 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07003261 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
3262 if (node->getType().getQualifier().isSpecConstant())
3263 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07003264 executeBothSides();
3265 } else
3266 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06003267
3268 return false;
3269}
3270
3271bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
3272{
3273 // emit and get the condition before doing anything with switch
3274 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003275 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003276
Rex Xu57e65922017-07-04 23:23:40 +08003277 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07003278 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08003279
John Kessenich140f3df2015-06-26 16:58:36 -06003280 // browse the children to sort out code segments
3281 int defaultSegment = -1;
3282 std::vector<TIntermNode*> codeSegments;
3283 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
3284 std::vector<int> caseValues;
3285 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
3286 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
3287 TIntermNode* child = *c;
3288 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02003289 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06003290 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02003291 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich8985fc92020-03-03 10:25:07 -07003292 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
3293 ->getConstArray()[0].getIConst());
John Kessenich140f3df2015-06-26 16:58:36 -06003294 } else
3295 codeSegments.push_back(child);
3296 }
3297
qining25262b32016-05-06 17:25:16 -04003298 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06003299 // statements between the last case and the end of the switch statement
3300 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
3301 (int)codeSegments.size() == defaultSegment)
3302 codeSegments.push_back(nullptr);
3303
3304 // make the switch statement
3305 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
John Kessenich8985fc92020-03-03 10:25:07 -07003306 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
3307 segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06003308
3309 // emit all the code in the segments
3310 breakForLoop.push(false);
3311 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
3312 builder.nextSwitchSegment(segmentBlocks, s);
3313 if (codeSegments[s])
3314 codeSegments[s]->traverse(this);
3315 else
3316 builder.addSwitchBreak();
3317 }
3318 breakForLoop.pop();
3319
3320 builder.endSwitch(segmentBlocks);
3321
3322 return false;
3323}
3324
3325void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
3326{
3327 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003328 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003329
3330 builder.clearAccessChain();
3331 builder.setAccessChainRValue(constant);
3332}
3333
3334bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3335{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003336 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003337 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003338
3339 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003340 std::vector<unsigned int> operands;
3341 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003342
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003343 // Spec requires back edges to target header blocks, and every header block
3344 // must dominate its merge block. Make a header block first to ensure these
3345 // conditions are met. By definition, it will contain OpLoopMerge, followed
3346 // by a block-ending branch. But we don't want to put any other body/test
3347 // instructions in it, since the body/test may have arbitrary instructions,
3348 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003349 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003350 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003351 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003352 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003353 spv::Block& test = builder.makeNewBlock();
3354 builder.createBranch(&test);
3355
3356 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003357 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003358 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003359 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3360
3361 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003362 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003363 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003364 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003365 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003366 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003367
3368 builder.setBuildPoint(&blocks.continue_target);
3369 if (node->getTerminal())
3370 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003371 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003372 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003373 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003374 builder.createBranch(&blocks.body);
3375
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003376 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003377 builder.setBuildPoint(&blocks.body);
3378 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003379 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003380 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003381 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003382
3383 builder.setBuildPoint(&blocks.continue_target);
3384 if (node->getTerminal())
3385 node->getTerminal()->traverse(this);
3386 if (node->getTest()) {
3387 node->getTest()->traverse(this);
3388 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003389 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003390 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003391 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003392 // TODO: unless there was a break/return/discard instruction
3393 // somewhere in the body, this is an infinite loop, so we should
3394 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003395 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003396 }
John Kessenich140f3df2015-06-26 16:58:36 -06003397 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003398 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003399 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003400 return false;
3401}
3402
3403bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3404{
3405 if (node->getExpression())
3406 node->getExpression()->traverse(this);
3407
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003408 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003409
John Kessenich140f3df2015-06-26 16:58:36 -06003410 switch (node->getFlowOp()) {
3411 case glslang::EOpKill:
3412 builder.makeDiscard();
3413 break;
3414 case glslang::EOpBreak:
3415 if (breakForLoop.top())
3416 builder.createLoopExit();
3417 else
3418 builder.addSwitchBreak();
3419 break;
3420 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003421 builder.createLoopContinue();
3422 break;
3423 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003424 if (node->getExpression()) {
3425 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3426 spv::Id returnId = accessChainLoad(glslangReturnType);
3427 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3428 builder.clearAccessChain();
3429 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3430 builder.setAccessChainLValue(copyId);
3431 multiTypeStore(glslangReturnType, returnId);
3432 returnId = builder.createLoad(copyId);
3433 }
3434 builder.makeReturn(false, returnId);
3435 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003436 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003437
3438 builder.clearAccessChain();
3439 break;
3440
John Kessenichb9197c82019-08-11 07:41:45 -06003441#ifndef GLSLANG_WEB
Jeff Bolzba6170b2019-07-01 09:23:23 -05003442 case glslang::EOpDemote:
3443 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3444 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3445 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3446 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003447#endif
Jeff Bolzba6170b2019-07-01 09:23:23 -05003448
John Kessenich140f3df2015-06-26 16:58:36 -06003449 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003450 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452 }
3453
3454 return false;
3455}
3456
John Kessenich9c14f772019-06-17 08:38:35 -06003457spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003458{
qining25262b32016-05-06 17:25:16 -04003459 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003460 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003461 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003462 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003463 spv::Id result = createSpvConstant(*node);
3464 if (result != spv::NoResult)
3465 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003466 }
3467
3468 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003469 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003470 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3471 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003472
John Kessenichb9197c82019-08-11 07:41:45 -06003473 const bool contains16BitType = node->getType().contains16BitFloat() ||
3474 node->getType().contains16BitInt();
Rex Xuf89ad982017-04-07 23:22:33 +08003475 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003476 switch (storageClass) {
3477 case spv::StorageClassInput:
3478 case spv::StorageClassOutput:
John Kessenich8317e6c2019-08-18 23:58:08 -06003479 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003480 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003481 break;
John Kessenich18310872018-05-14 22:08:53 -06003482 case spv::StorageClassUniform:
John Kessenich8317e6c2019-08-18 23:58:08 -06003483 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
Rex Xuf89ad982017-04-07 23:22:33 +08003484 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3485 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003486 else
3487 builder.addCapability(spv::CapabilityStorageUniform16);
3488 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003489#ifndef GLSLANG_WEB
3490 case spv::StorageClassPushConstant:
John Kessenich8317e6c2019-08-18 23:58:08 -06003491 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenichb9197c82019-08-11 07:41:45 -06003492 builder.addCapability(spv::CapabilityStoragePushConstant16);
3493 break;
John Kessenich18310872018-05-14 22:08:53 -06003494 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003495 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich8317e6c2019-08-18 23:58:08 -06003496 builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
John Kessenich18310872018-05-14 22:08:53 -06003497 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3498 break;
John Kessenichb9197c82019-08-11 07:41:45 -06003499#endif
John Kessenich18310872018-05-14 22:08:53 -06003500 default:
John Kessenichb9197c82019-08-11 07:41:45 -06003501 if (node->getType().contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003502 builder.addCapability(spv::CapabilityFloat16);
John Kessenichb9197c82019-08-11 07:41:45 -06003503 if (node->getType().contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003504 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003505 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003506 }
3507 }
Rex Xuf89ad982017-04-07 23:22:33 +08003508
John Kessenichb9197c82019-08-11 07:41:45 -06003509 if (node->getType().contains8BitInt()) {
John Kessenich312dcfb2018-07-03 13:19:51 -06003510 if (storageClass == spv::StorageClassPushConstant) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003511 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
John Kessenich312dcfb2018-07-03 13:19:51 -06003512 builder.addCapability(spv::CapabilityStoragePushConstant8);
3513 } else if (storageClass == spv::StorageClassUniform) {
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::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003516 } else if (storageClass == spv::StorageClassStorageBuffer) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003517 builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
Neil Henningb6b01f02018-10-23 15:02:29 +01003518 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003519 } else {
3520 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003521 }
3522 }
3523
John Kessenich140f3df2015-06-26 16:58:36 -06003524 const char* name = node->getName().c_str();
3525 if (glslang::IsAnonymous(name))
3526 name = "";
3527
Alejandro Piñeiroff6dcca2020-06-04 09:39:31 +02003528 spv::Id initializer = spv::NoResult;
3529
3530 if (node->getType().getQualifier().storage == glslang::EvqUniform &&
3531 !node->getConstArray().empty()) {
3532 int nextConst = 0;
3533 initializer = createSpvConstantFromConstUnionArray(node->getType(),
3534 node->getConstArray(),
3535 nextConst,
3536 false /* specConst */);
3537 }
3538
3539 return builder.createVariable(storageClass, spvType, name, initializer);
John Kessenich140f3df2015-06-26 16:58:36 -06003540}
3541
3542// Return type Id of the sampled type.
3543spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3544{
3545 switch (sampler.type) {
John Kessenicha28f7a72019-08-06 07:00:58 -06003546 case glslang::EbtInt: return builder.makeIntType(32);
3547 case glslang::EbtUint: return builder.makeUintType(32);
John Kessenich140f3df2015-06-26 16:58:36 -06003548 case glslang::EbtFloat: return builder.makeFloatType(32);
John Kessenicha28f7a72019-08-06 07:00:58 -06003549#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08003550 case glslang::EbtFloat16:
3551 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3552 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3553 return builder.makeFloatType(16);
3554#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003555 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003556 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003557 return builder.makeFloatType(32);
3558 }
3559}
3560
John Kessenich8c8505c2016-07-26 12:50:38 -06003561// If node is a swizzle operation, return the type that should be used if
3562// the swizzle base is first consumed by another operation, before the swizzle
3563// is applied.
3564spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3565{
John Kessenichecba76f2017-01-06 00:34:48 -07003566 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003567 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3568 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3569 else
3570 return spv::NoType;
3571}
3572
3573// When inverting a swizzle with a parent op, this function
3574// will apply the swizzle operation to a completed parent operation.
John Kessenich8985fc92020-03-03 10:25:07 -07003575spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
3576 spv::Id parentResult)
John Kessenich8c8505c2016-07-26 12:50:38 -06003577{
3578 std::vector<unsigned> swizzle;
3579 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3580 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3581}
3582
John Kessenich8c8505c2016-07-26 12:50:38 -06003583// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3584void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3585{
3586 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3587 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3588 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3589}
3590
John Kessenich3ac051e2015-12-20 11:29:16 -07003591// Convert from a glslang type to an SPV type, by calling into a
3592// recursive version of this function. This establishes the inherited
3593// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003594spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003595{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003596 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003597}
3598
3599// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003600// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003601// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003602spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003603 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3604 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003605{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003606 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003607
3608 switch (type.getBasicType()) {
3609 case glslang::EbtVoid:
3610 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003611 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003612 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003613 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003614 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3615 // a 32-bit int where non-0 means true.
3616 if (explicitLayout != glslang::ElpNone)
3617 spvType = builder.makeUintType(32);
3618 else
3619 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003620 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003621 case glslang::EbtInt:
3622 spvType = builder.makeIntType(32);
3623 break;
3624 case glslang::EbtUint:
3625 spvType = builder.makeUintType(32);
3626 break;
3627 case glslang::EbtFloat:
3628 spvType = builder.makeFloatType(32);
3629 break;
3630#ifndef GLSLANG_WEB
3631 case glslang::EbtDouble:
3632 spvType = builder.makeFloatType(64);
3633 break;
3634 case glslang::EbtFloat16:
3635 spvType = builder.makeFloatType(16);
3636 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003637 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003638 spvType = builder.makeIntType(8);
3639 break;
3640 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003641 spvType = builder.makeUintType(8);
3642 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003643 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003644 spvType = builder.makeIntType(16);
3645 break;
3646 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003647 spvType = builder.makeUintType(16);
3648 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003649 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003650 spvType = builder.makeIntType(64);
3651 break;
3652 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003653 spvType = builder.makeUintType(64);
3654 break;
John Kessenich426394d2015-07-23 10:22:48 -06003655 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003656 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003657 spvType = builder.makeUintType(32);
3658 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04003659 case glslang::EbtAccStruct:
3660 spvType = builder.makeAccelerationStructureType();
Chao Chenb50c02e2018-09-19 11:42:24 -07003661 break;
Torosdagli06c2eee2020-03-19 11:09:57 -04003662 case glslang::EbtRayQuery:
3663 spvType = builder.makeRayQueryType();
3664 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06003665 case glslang::EbtReference:
3666 {
3667 // Make the forward pointer, then recurse to convert the structure type, then
3668 // patch up the forward pointer with a real pointer type.
3669 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3670 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3671 forwardPointers[type.getReferentType()] = forwardId;
3672 }
3673 spvType = forwardPointers[type.getReferentType()];
3674 if (!forwardReferenceOnly) {
3675 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3676 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3677 forwardPointers[type.getReferentType()],
3678 referentType);
3679 }
3680 }
3681 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003682#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003683 case glslang::EbtSampler:
3684 {
3685 const glslang::TSampler& sampler = type.getSampler();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003686 if (sampler.isPureSampler()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003687 spvType = builder.makeSamplerType();
3688 } else {
3689 // an image is present, make its type
John Kessenich3e4b6ff2019-08-08 01:15:24 -06003690 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
3691 sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
3692 sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
3693 if (sampler.isCombined()) {
John Kessenich6c292d32016-02-15 20:58:50 -07003694 // already has both image and sampler, make the combined type
3695 spvType = builder.makeSampledImageType(spvType);
3696 }
John Kessenich55e7d112015-11-15 21:33:39 -07003697 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003698 }
John Kessenich140f3df2015-06-26 16:58:36 -06003699 break;
3700 case glslang::EbtStruct:
3701 case glslang::EbtBlock:
3702 {
3703 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003704 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003705
3706 // Try to share structs for different layouts, but not yet for other
3707 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003708 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003709 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003710 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003711 break;
3712
3713 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003714 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003715 memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
John Kessenich6090df02016-06-30 21:18:02 -06003716 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003717 }
3718 break;
Jeff Bolz04d73732019-05-31 13:06:01 -05003719 case glslang::EbtString:
3720 // no type used for OpString
3721 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003723 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003724 break;
3725 }
3726
3727 if (type.isMatrix())
3728 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3729 else {
3730 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3731 if (type.getVectorSize() > 1)
3732 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3733 }
3734
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003735 if (type.isCoopMat()) {
3736 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3737 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3738 if (type.getBasicType() == glslang::EbtFloat16)
3739 builder.addCapability(spv::CapabilityFloat16);
Jeff Bolz387657e2019-08-22 20:28:00 -05003740 if (type.getBasicType() == glslang::EbtUint8 ||
3741 type.getBasicType() == glslang::EbtInt8) {
3742 builder.addCapability(spv::CapabilityInt8);
3743 }
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003744
3745 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3746 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3747 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3748
3749 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3750 }
3751
John Kessenich140f3df2015-06-26 16:58:36 -06003752 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003753 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3754
John Kessenichc9a80832015-09-12 12:17:44 -06003755 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003756 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003757 // We need to decorate array strides for types needing explicit layout, except blocks.
3758 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003759 // Use a dummy glslang type for querying internal strides of
3760 // arrays of arrays, but using just a one-dimensional array.
3761 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003762 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3763 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003764
3765 // Will compute the higher-order strides here, rather than making a whole
3766 // pile of types and doing repetitive recursion on their contents.
3767 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3768 }
John Kessenichf8842e52016-01-04 19:22:56 -07003769
3770 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003771 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003772 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003773 if (stride > 0)
3774 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003775 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003776 }
3777 } else {
3778 // single-dimensional array, and don't yet have stride
3779
John Kessenichf8842e52016-01-04 19:22:56 -07003780 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003781 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3782 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003783 }
John Kessenich31ed4832015-09-09 17:51:38 -06003784
John Kessenichead86222018-03-28 18:01:20 -06003785 // Do the outer dimension, which might not be known for a runtime-sized array.
3786 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3787 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003788 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003789 else {
John Kessenichb9197c82019-08-11 07:41:45 -06003790#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06003791 if (!lastBufferBlockMember) {
John Kessenich8317e6c2019-08-18 23:58:08 -06003792 builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
John Kessenich5611c6d2018-04-05 11:25:02 -06003793 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3794 }
John Kessenichb9197c82019-08-11 07:41:45 -06003795#endif
John Kessenich3dd1ce52019-10-17 07:08:40 -06003796 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003797 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003798 if (stride > 0)
3799 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003800 }
3801
3802 return spvType;
3803}
3804
John Kessenich0e737842017-03-24 18:38:16 -06003805// TODO: this functionality should exist at a higher level, in creating the AST
3806//
3807// Identify interface members that don't have their required extension turned on.
3808//
3809bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3810{
John Kessenicha28f7a72019-08-06 07:00:58 -06003811#ifndef GLSLANG_WEB
John Kessenich0e737842017-03-24 18:38:16 -06003812 auto& extensions = glslangIntermediate->getRequestedExtensions();
3813
Rex Xubcf291a2017-03-29 23:01:36 +08003814 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3815 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3816 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003817 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3818 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3819 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003820
3821 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3822 if (member.getFieldName() == "gl_ViewportMask" &&
3823 extensions.find("GL_NV_viewport_array2") == extensions.end())
3824 return true;
3825 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3826 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3827 return true;
3828 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3829 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3830 return true;
3831 }
3832#endif
John Kessenich0e737842017-03-24 18:38:16 -06003833
3834 return false;
3835};
3836
John Kessenich6090df02016-06-30 21:18:02 -06003837// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3838// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3839// Mutually recursive with convertGlslangToSpvType().
3840spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3841 const glslang::TTypeList* glslangMembers,
3842 glslang::TLayoutPacking explicitLayout,
3843 const glslang::TQualifier& qualifier)
3844{
3845 // Create a vector of struct types for SPIR-V to consume
3846 std::vector<spv::Id> spvMembers;
John Kessenich8985fc92020-03-03 10:25:07 -07003847 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
3848 // except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003849 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003850 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3851 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3852 if (glslangMember.hiddenMember()) {
3853 ++memberDelta;
3854 if (type.getBasicType() == glslang::EbtBlock)
Roy05a5b532020-01-03 16:21:34 +08003855 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich6090df02016-06-30 21:18:02 -06003856 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003857 if (type.getBasicType() == glslang::EbtBlock) {
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003858 if (filterMember(glslangMember)) {
3859 memberDelta++;
Roy05a5b532020-01-03 16:21:34 +08003860 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
John Kessenich0e737842017-03-24 18:38:16 -06003861 continue;
Ashwin Lelec1e61d62019-07-22 12:36:38 -07003862 }
Roy05a5b532020-01-03 16:21:34 +08003863 memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003864 }
John Kessenich6090df02016-06-30 21:18:02 -06003865 // modify just this child's view of the qualifier
3866 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3867 InheritQualifiers(memberQualifier, qualifier);
3868
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003869 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003870 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003871 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003872
3873 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003874 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3875 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003876
3877 // Make forward pointers for any pointer members, and create a list of members to
3878 // convert to spirv types after creating the struct.
John Kessenich7015bd62019-08-01 03:28:08 -06003879 if (glslangMember.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003880 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3881 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3882 }
3883 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003884 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3885 true));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003886 } else {
3887 spvMembers.push_back(
John Kessenich8985fc92020-03-03 10:25:07 -07003888 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember,
3889 false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003890 }
John Kessenich6090df02016-06-30 21:18:02 -06003891 }
3892 }
3893
3894 // Make the SPIR-V type
3895 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003896 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003897 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3898
3899 // Decorate it
3900 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3901
John Kessenichd72f4882019-01-16 14:55:37 +07003902 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003903 auto it = deferredForwardPointers[i];
3904 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3905 }
3906
John Kessenich6090df02016-06-30 21:18:02 -06003907 return spvType;
3908}
3909
3910void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3911 const glslang::TTypeList* glslangMembers,
3912 glslang::TLayoutPacking explicitLayout,
3913 const glslang::TQualifier& qualifier,
3914 spv::Id spvType)
3915{
3916 // Name and decorate the non-hidden members
3917 int offset = -1;
3918 int locationOffset = 0; // for use within the members of this struct
3919 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3920 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3921 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003922 if (type.getBasicType() == glslang::EbtBlock) {
Roy05a5b532020-01-03 16:21:34 +08003923 member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
John Kessenich0e737842017-03-24 18:38:16 -06003924 if (filterMember(glslangMember))
3925 continue;
3926 }
John Kessenich6090df02016-06-30 21:18:02 -06003927
3928 // modify just this child's view of the qualifier
3929 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3930 InheritQualifiers(memberQualifier, qualifier);
3931
3932 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003933 if (member < 0)
3934 continue;
3935
3936 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3937 builder.addMemberDecoration(spvType, member,
3938 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3939 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3940 // Add interpolation and auxiliary storage decorations only to
3941 // top-level members of Input and Output storage classes
3942 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3943 type.getQualifier().storage == glslang::EvqVaryingOut) {
3944 if (type.getBasicType() == glslang::EbtBlock ||
3945 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3946 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3947 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenicha28f7a72019-08-06 07:00:58 -06003948#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07003949 addMeshNVDecoration(spvType, member, memberQualifier);
3950#endif
John Kessenich6090df02016-06-30 21:18:02 -06003951 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003952 }
3953 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003954
John Kessenichb9197c82019-08-11 07:41:45 -06003955#ifndef GLSLANG_WEB
John Kessenich5d610ee2018-03-07 18:05:55 -07003956 if (type.getBasicType() == glslang::EbtBlock &&
3957 qualifier.storage == glslang::EvqBuffer) {
3958 // Add memory decorations only to top-level members of shader storage block
3959 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003960 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003961 for (unsigned int i = 0; i < memory.size(); ++i)
3962 builder.addMemberDecoration(spvType, member, memory[i]);
3963 }
John Kessenichf8d1d742019-10-21 06:55:11 -06003964
John Kessenichb9197c82019-08-11 07:41:45 -06003965#endif
John Kessenich6090df02016-06-30 21:18:02 -06003966
John Kessenich5d610ee2018-03-07 18:05:55 -07003967 // Location assignment was already completed correctly by the front end,
3968 // just track whether a member needs to be decorated.
3969 // Ignore member locations if the container is an array, as that's
3970 // ill-specified and decisions have been made to not allow this.
3971 if (! type.isArray() && memberQualifier.hasLocation())
3972 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003973
John Kessenich5d610ee2018-03-07 18:05:55 -07003974 if (qualifier.hasLocation()) // track for upcoming inheritance
3975 locationOffset += glslangIntermediate->computeTypeLocationSize(
3976 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003977
John Kessenich5d610ee2018-03-07 18:05:55 -07003978 // component, XFB, others
3979 if (glslangMember.getQualifier().hasComponent())
3980 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3981 glslangMember.getQualifier().layoutComponent);
3982 if (glslangMember.getQualifier().hasXfbOffset())
3983 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3984 glslangMember.getQualifier().layoutXfbOffset);
3985 else if (explicitLayout != glslang::ElpNone) {
3986 // figure out what to do with offset, which is accumulating
3987 int nextOffset;
3988 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3989 if (offset >= 0)
3990 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3991 offset = nextOffset;
3992 }
John Kessenich6090df02016-06-30 21:18:02 -06003993
John Kessenich5d610ee2018-03-07 18:05:55 -07003994 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3995 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3996 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003997
John Kessenich5d610ee2018-03-07 18:05:55 -07003998 // built-in variable decorations
3999 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
4000 if (builtIn != spv::BuiltInMax)
4001 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08004002
John Kessenichb9197c82019-08-11 07:41:45 -06004003#ifndef GLSLANG_WEB
John Kessenich5611c6d2018-04-05 11:25:02 -06004004 // nonuniform
4005 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
4006
John Kessenichead86222018-03-28 18:01:20 -06004007 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
4008 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
4009 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
4010 memberQualifier.semanticName);
4011 }
4012
John Kessenich5d610ee2018-03-07 18:05:55 -07004013 if (builtIn == spv::BuiltInLayer) {
4014 // SPV_NV_viewport_array2 extension
4015 if (glslangMember.getQualifier().layoutViewportRelative){
4016 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
4017 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
4018 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08004019 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004020 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
4021 builder.addMemberDecoration(spvType, member,
4022 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
4023 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
4024 builder.addCapability(spv::CapabilityShaderStereoViewNV);
4025 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08004026 }
John Kessenich5d610ee2018-03-07 18:05:55 -07004027 }
4028 if (glslangMember.getQualifier().layoutPassthrough) {
4029 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
4030 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
4031 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
4032 }
chaoc771d89f2017-01-13 01:10:53 -08004033#endif
John Kessenich6090df02016-06-30 21:18:02 -06004034 }
4035
4036 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07004037 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
4038 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06004039}
4040
John Kessenich6c292d32016-02-15 20:58:50 -07004041// Turn the expression forming the array size into an id.
4042// This is not quite trivial, because of specialization constants.
4043// Sometimes, a raw constant is turned into an Id, and sometimes
4044// a specialization constant expression is.
4045spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
4046{
4047 // First, see if this is sized with a node, meaning a specialization constant:
4048 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
4049 if (specNode != nullptr) {
4050 builder.clearAccessChain();
4051 specNode->traverse(this);
4052 return accessChainLoad(specNode->getAsTyped()->getType());
4053 }
qining25262b32016-05-06 17:25:16 -04004054
John Kessenich6c292d32016-02-15 20:58:50 -07004055 // Otherwise, need a compile-time (front end) size, get it:
4056 int size = arraySizes.getDimSize(dim);
4057 assert(size > 0);
4058 return builder.makeUintConstant(size);
4059}
4060
John Kessenich103bef92016-02-08 21:38:15 -07004061// Wrap the builder's accessChainLoad to:
4062// - localize handling of RelaxedPrecision
4063// - use the SPIR-V inferred type instead of another conversion of the glslang type
4064// (avoids unnecessary work and possible type punning for structures)
4065// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07004066spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
4067{
John Kessenich103bef92016-02-08 21:38:15 -07004068 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004069
4070 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4071 coherentFlags |= TranslateCoherent(type);
4072
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004073 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004074 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004075
John Kessenich5611c6d2018-04-05 11:25:02 -06004076 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
John Kessenich8985fc92020-03-03 10:25:07 -07004077 TranslateNonUniformDecoration(type.getQualifier()),
4078 nominalTypeId,
4079 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
4080 TranslateMemoryScope(coherentFlags),
4081 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07004082
4083 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08004084 if (type.getBasicType() == glslang::EbtBool) {
4085 if (builder.isScalarType(nominalTypeId)) {
4086 // Conversion for bool
4087 spv::Id boolType = builder.makeBoolType();
4088 if (nominalTypeId != boolType)
4089 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
4090 } else if (builder.isVectorType(nominalTypeId)) {
4091 // Conversion for bvec
4092 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4093 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
4094 if (nominalTypeId != bvecType)
John Kessenich8985fc92020-03-03 10:25:07 -07004095 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
4096 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004097 }
4098 }
John Kessenich103bef92016-02-08 21:38:15 -07004099
4100 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07004101}
4102
Rex Xu27253232016-02-23 17:51:09 +08004103// Wrap the builder's accessChainStore to:
4104// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06004105//
4106// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08004107void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
4108{
4109 // Need to convert to abstract types when necessary
4110 if (type.getBasicType() == glslang::EbtBool) {
4111 spv::Id nominalTypeId = builder.accessChainGetInferredType();
4112
4113 if (builder.isScalarType(nominalTypeId)) {
4114 // Conversion for bool
4115 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06004116 if (nominalTypeId != boolType) {
4117 // keep these outside arguments, for determinant order-of-evaluation
4118 spv::Id one = builder.makeUintConstant(1);
4119 spv::Id zero = builder.makeUintConstant(0);
4120 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
4121 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06004122 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08004123 } else if (builder.isVectorType(nominalTypeId)) {
4124 // Conversion for bvec
4125 int vecSize = builder.getNumTypeComponents(nominalTypeId);
4126 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06004127 if (nominalTypeId != bvecType) {
4128 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06004129 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
4130 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
4131 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06004132 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06004133 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
4134 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08004135 }
4136 }
4137
Jeff Bolz36831c92018-09-05 10:11:41 -05004138 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
4139 coherentFlags |= TranslateCoherent(type);
4140
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004141 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06004142 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004143
Jeff Bolz36831c92018-09-05 10:11:41 -05004144 builder.accessChainStore(rvalue,
John Kessenich8985fc92020-03-03 10:25:07 -07004145 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
4146 ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004147 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08004148}
4149
John Kessenich4bf71552016-09-02 11:20:21 -06004150// For storing when types match at the glslang level, but not might match at the
4151// SPIR-V level.
4152//
4153// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06004154// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06004155// as in a member-decorated way.
4156//
4157// NOTE: This function can handle any store request; if it's not special it
4158// simplifies to a simple OpStore.
4159//
4160// Implicitly uses the existing builder.accessChain as the storage target.
4161void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
4162{
John Kessenichb3e24e42016-09-11 12:33:43 -06004163 // we only do the complex path here if it's an aggregate
4164 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06004165 accessChainStore(type, rValue);
4166 return;
4167 }
4168
John Kessenichb3e24e42016-09-11 12:33:43 -06004169 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06004170 spv::Id rType = builder.getTypeId(rValue);
4171 spv::Id lValue = builder.accessChainGetLValue();
4172 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
4173 if (lType == rType) {
4174 accessChainStore(type, rValue);
4175 return;
4176 }
4177
John Kessenichb3e24e42016-09-11 12:33:43 -06004178 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06004179 // where the two types were the same type in GLSL. This requires member
4180 // by member copy, recursively.
4181
John Kessenichfbb6bdf2019-01-15 21:48:27 +07004182 // SPIR-V 1.4 added an instruction to do help do this.
4183 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
4184 // However, bool in uniform space is changed to int, so
4185 // OpCopyLogical does not work for that.
4186 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
4187 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
4188 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
4189 if (lBool == rBool) {
4190 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
4191 accessChainStore(type, logicalCopy);
4192 return;
4193 }
4194 }
4195
John Kessenichb3e24e42016-09-11 12:33:43 -06004196 // If an array, copy element by element.
4197 if (type.isArray()) {
4198 glslang::TType glslangElementType(type, 0);
4199 spv::Id elementRType = builder.getContainedTypeId(rType);
4200 for (int index = 0; index < type.getOuterArraySize(); ++index) {
4201 // get the source member
4202 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06004203
John Kessenichb3e24e42016-09-11 12:33:43 -06004204 // set up the target storage
4205 builder.clearAccessChain();
4206 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004207 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
4208 type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06004209
John Kessenichb3e24e42016-09-11 12:33:43 -06004210 // store the member
4211 multiTypeStore(glslangElementType, elementRValue);
4212 }
4213 } else {
4214 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06004215
John Kessenichb3e24e42016-09-11 12:33:43 -06004216 // loop over structure members
4217 const glslang::TTypeList& members = *type.getStruct();
4218 for (int m = 0; m < (int)members.size(); ++m) {
4219 const glslang::TType& glslangMemberType = *members[m].type;
4220
4221 // get the source member
4222 spv::Id memberRType = builder.getContainedTypeId(rType, m);
4223 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
4224
4225 // set up the target storage
4226 builder.clearAccessChain();
4227 builder.setAccessChainLValue(lValue);
John Kessenich8985fc92020-03-03 10:25:07 -07004228 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
4229 type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06004230
4231 // store the member
4232 multiTypeStore(glslangMemberType, memberRValue);
4233 }
John Kessenich4bf71552016-09-02 11:20:21 -06004234 }
4235}
4236
John Kessenichf85e8062015-12-19 13:57:10 -07004237// Decide whether or not this type should be
4238// decorated with offsets and strides, and if so
4239// whether std140 or std430 rules should be applied.
4240glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06004241{
John Kessenichf85e8062015-12-19 13:57:10 -07004242 // has to be a block
4243 if (type.getBasicType() != glslang::EbtBlock)
4244 return glslang::ElpNone;
4245
Chao Chen3c366992018-09-19 11:41:59 -07004246 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07004247 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07004248 type.getQualifier().storage != glslang::EvqBuffer &&
4249 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07004250 return glslang::ElpNone;
4251
4252 // return the layout to use
4253 switch (type.getQualifier().layoutPacking) {
4254 case glslang::ElpStd140:
4255 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06004256 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07004257 return type.getQualifier().layoutPacking;
4258 default:
4259 return glslang::ElpNone;
4260 }
John Kessenich31ed4832015-09-09 17:51:38 -06004261}
4262
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004263// Given an array type, returns the integer stride required for that array
John Kessenich8985fc92020-03-03 10:25:07 -07004264int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
4265 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004266{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004267 int size;
John Kessenich49987892015-12-29 17:11:44 -07004268 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004269 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
4270 matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07004271
4272 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004273}
4274
John Kessenich49987892015-12-29 17:11:44 -07004275// 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 -07004276// when used as a member of an interface block
John Kessenich8985fc92020-03-03 10:25:07 -07004277int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
4278 glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004279{
John Kessenich49987892015-12-29 17:11:44 -07004280 glslang::TType elementType;
4281 elementType.shallowCopy(matrixType);
4282 elementType.clearArraySizes();
4283
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004284 int size;
John Kessenich49987892015-12-29 17:11:44 -07004285 int stride;
John Kessenich8985fc92020-03-03 10:25:07 -07004286 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
4287 matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07004288
4289 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07004290}
4291
John Kessenich5e4b1242015-08-06 22:53:06 -06004292// Given a member type of a struct, realign the current offset for it, and compute
4293// the next (not yet aligned) offset for the next member, which will get aligned
4294// on the next call.
4295// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
4296// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
4297// -1 means a non-forced member offset (no decoration needed).
John Kessenich8985fc92020-03-03 10:25:07 -07004298void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
4299 int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06004300{
4301 // this will get a positive value when deemed necessary
4302 nextOffset = -1;
4303
John Kessenich5e4b1242015-08-06 22:53:06 -06004304 // override anything in currentOffset with user-set offset
4305 if (memberType.getQualifier().hasOffset())
4306 currentOffset = memberType.getQualifier().layoutOffset;
4307
4308 // It could be that current linker usage in glslang updated all the layoutOffset,
4309 // in which case the following code does not matter. But, that's not quite right
4310 // once cross-compilation unit GLSL validation is done, as the original user
4311 // settings are needed in layoutOffset, and then the following will come into play.
4312
John Kessenichf85e8062015-12-19 13:57:10 -07004313 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06004314 if (! memberType.getQualifier().hasOffset())
4315 currentOffset = -1;
4316
4317 return;
4318 }
4319
John Kessenichf85e8062015-12-19 13:57:10 -07004320 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06004321 if (currentOffset < 0)
4322 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04004323
John Kessenich5e4b1242015-08-06 22:53:06 -06004324 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
4325 // but possibly not yet correctly aligned.
4326
4327 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07004328 int dummyStride;
John Kessenich8985fc92020-03-03 10:25:07 -07004329 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
4330 matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06004331
4332 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06004333 // TODO: make this consistent in early phases of code:
4334 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
4335 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
4336 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06004337 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06004338 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06004339 int dummySize;
4340 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
4341 if (componentAlignment <= 4)
4342 memberAlignment = componentAlignment;
4343 }
4344
4345 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06004346 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06004347
4348 // Bump up to vec4 if there is a bad straddle
John Kessenich8985fc92020-03-03 10:25:07 -07004349 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
4350 currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06004351 glslang::RoundToPow2(currentOffset, 16);
4352
John Kessenich5e4b1242015-08-06 22:53:06 -06004353 nextOffset = currentOffset + memberSize;
4354}
4355
David Netoa901ffe2016-06-08 14:11:40 +01004356void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06004357{
David Netoa901ffe2016-06-08 14:11:40 +01004358 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
4359 switch (glslangBuiltIn)
4360 {
John Kessenicha28f7a72019-08-06 07:00:58 -06004361 case glslang::EbvPointSize:
4362#ifndef GLSLANG_WEB
David Netoa901ffe2016-06-08 14:11:40 +01004363 case glslang::EbvClipDistance:
4364 case glslang::EbvCullDistance:
chaoc771d89f2017-01-13 01:10:53 -08004365 case glslang::EbvViewportMaskNV:
4366 case glslang::EbvSecondaryPositionNV:
4367 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08004368 case glslang::EbvPositionPerViewNV:
4369 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004370 case glslang::EbvTaskCountNV:
4371 case glslang::EbvPrimitiveCountNV:
4372 case glslang::EbvPrimitiveIndicesNV:
4373 case glslang::EbvClipDistancePerViewNV:
4374 case glslang::EbvCullDistancePerViewNV:
4375 case glslang::EbvLayerPerViewNV:
4376 case glslang::EbvMeshViewCountNV:
4377 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004378#endif
David Netoa901ffe2016-06-08 14:11:40 +01004379 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4380 // Alternately, we could just call this for any glslang built-in, since the
4381 // capability already guards against duplicates.
4382 TranslateBuiltInDecoration(glslangBuiltIn, false);
4383 break;
4384 default:
4385 // Capabilities were already generated when the struct was declared.
4386 break;
4387 }
John Kessenichebb50532016-05-16 19:22:05 -06004388}
4389
John Kessenich6fccb3c2016-09-19 16:01:41 -06004390bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004391{
John Kessenicheee9d532016-09-19 18:09:30 -06004392 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004393}
4394
John Kessenichd41993d2017-09-10 15:21:05 -06004395// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004396// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4397// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004398bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004399{
John Kessenich6a14f782017-12-04 02:48:10 -07004400 assert(qualifier == glslang::EvqIn ||
4401 qualifier == glslang::EvqOut ||
4402 qualifier == glslang::EvqInOut ||
rdbd8edfd82020-06-02 08:30:07 +02004403 qualifier == glslang::EvqUniform ||
John Kessenich6a14f782017-12-04 02:48:10 -07004404 qualifier == glslang::EvqConstReadOnly);
rdbd8edfd82020-06-02 08:30:07 +02004405 return qualifier != glslang::EvqConstReadOnly &&
4406 qualifier != glslang::EvqUniform;
John Kessenichd41993d2017-09-10 15:21:05 -06004407}
4408
4409// Is parameter pass-by-original?
4410bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4411 bool implicitThisParam)
4412{
4413 if (implicitThisParam) // implicit this
4414 return true;
4415 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004416 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004417 return paramType.containsOpaque() || // sampler, etc.
4418 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4419}
4420
John Kessenich140f3df2015-06-26 16:58:36 -06004421// Make all the functions, skeletally, without actually visiting their bodies.
4422void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4423{
John Kessenich8985fc92020-03-03 10:25:07 -07004424 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
4425 bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004426 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4427 if (paramPrecision != spv::NoPrecision)
4428 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004429 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenich7015bd62019-08-01 03:28:08 -06004430 if (type.isReference()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004431 // Original and non-writable params pass the pointer directly and
4432 // use restrict/aliased, others are stored to a pointer in Function
4433 // memory and use RestrictPointer/AliasedPointer.
4434 if (originalParam(type.getQualifier().storage, type, false) ||
4435 !writableParam(type.getQualifier().storage)) {
John Kessenichf8d1d742019-10-21 06:55:11 -06004436 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
4437 spv::DecorationAliased);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004438 } else {
John Kessenichf8d1d742019-10-21 06:55:11 -06004439 decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
4440 spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004441 }
4442 }
John Kessenichfad62972017-07-18 02:35:46 -06004443 };
4444
John Kessenich140f3df2015-06-26 16:58:36 -06004445 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4446 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004447 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004448 continue;
4449
4450 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004451 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004452 //
qining25262b32016-05-06 17:25:16 -04004453 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004454 // function. What it is an address of varies:
4455 //
John Kessenich4bf71552016-09-02 11:20:21 -06004456 // - "in" parameters not marked as "const" can be written to without modifying the calling
4457 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004458 //
4459 // - "const in" parameters can just be the r-value, as no writes need occur.
4460 //
John Kessenich4bf71552016-09-02 11:20:21 -06004461 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4462 // 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 -06004463
4464 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004465 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004466 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4467
John Kessenich155d3512019-08-08 23:29:20 -06004468#ifdef ENABLE_HLSL
John Kessenichfad62972017-07-18 02:35:46 -06004469 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4470 glslangIntermediate->implicitThisName;
John Kessenich155d3512019-08-08 23:29:20 -06004471#else
4472 bool implicitThis = false;
4473#endif
John Kessenich37789792017-03-21 23:56:40 -06004474
John Kessenichfad62972017-07-18 02:35:46 -06004475 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004476 for (int p = 0; p < (int)parameters.size(); ++p) {
4477 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4478 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004479 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004480 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004481 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004482 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4483 else
John Kessenich4bf71552016-09-02 11:20:21 -06004484 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004485 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004486 paramTypes.push_back(typeId);
4487 }
4488
4489 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004490 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4491 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004492 glslFunction->getName().c_str(), paramTypes,
4493 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004494 if (implicitThis)
4495 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004496
4497 // Track function to emit/call later
4498 functionMap[glslFunction->getName().c_str()] = function;
4499
4500 // Set the parameter id's
4501 for (int p = 0; p < (int)parameters.size(); ++p) {
4502 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4503 // give a name too
4504 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004505
4506 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
John Kessenichb9197c82019-08-11 07:41:45 -06004507 if (paramType.contains8BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004508 builder.addCapability(spv::CapabilityInt8);
John Kessenichb9197c82019-08-11 07:41:45 -06004509 if (paramType.contains16BitInt())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004510 builder.addCapability(spv::CapabilityInt16);
John Kessenichb9197c82019-08-11 07:41:45 -06004511 if (paramType.contains16BitFloat())
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004512 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004513 }
4514 }
4515}
4516
4517// Process all the initializers, while skipping the functions and link objects
4518void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4519{
4520 builder.setBuildPoint(shaderEntry->getLastBlock());
4521 for (int i = 0; i < (int)initializers.size(); ++i) {
4522 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
John Kessenich8985fc92020-03-03 10:25:07 -07004523 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
4524 glslang::EOpLinkerObjects) {
John Kessenich140f3df2015-06-26 16:58:36 -06004525
4526 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004527 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004528 initializer->traverse(this);
4529 }
4530 }
4531}
4532
4533// Process all the functions, while skipping initializers.
4534void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4535{
4536 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4537 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004538 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004539 node->traverse(this);
4540 }
4541}
4542
4543void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4544{
qining25262b32016-05-06 17:25:16 -04004545 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004546 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004547 currentFunction = functionMap[node->getName().c_str()];
4548 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004549 builder.setBuildPoint(functionBlock);
4550}
4551
John Kessenich8985fc92020-03-03 10:25:07 -07004552void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
4553 spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004554{
Rex Xufc618912015-09-09 16:42:49 +08004555 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004556
4557 glslang::TSampler sampler = {};
4558 bool cubeCompare = false;
John Kessenicha28f7a72019-08-06 07:00:58 -06004559#ifndef GLSLANG_WEB
Rex Xu1e5d7b02016-11-29 17:36:31 +08004560 bool f16ShadowCompare = false;
4561#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004562 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004563 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4564 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
John Kessenicha28f7a72019-08-06 07:00:58 -06004565#ifndef GLSLANG_WEB
John Kessenich8985fc92020-03-03 10:25:07 -07004566 f16ShadowCompare = sampler.shadow &&
4567 glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004568#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004569 }
4570
John Kessenich140f3df2015-06-26 16:58:36 -06004571 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4572 builder.clearAccessChain();
4573 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004574
John Kessenicha28f7a72019-08-06 07:00:58 -06004575#ifndef GLSLANG_WEB
Rex Xufc618912015-09-09 16:42:49 +08004576 // Special case l-value operands
4577 bool lvalue = false;
4578 switch (node.getOp()) {
4579 case glslang::EOpImageAtomicAdd:
4580 case glslang::EOpImageAtomicMin:
4581 case glslang::EOpImageAtomicMax:
4582 case glslang::EOpImageAtomicAnd:
4583 case glslang::EOpImageAtomicOr:
4584 case glslang::EOpImageAtomicXor:
4585 case glslang::EOpImageAtomicExchange:
4586 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004587 case glslang::EOpImageAtomicLoad:
4588 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004589 if (i == 0)
4590 lvalue = true;
4591 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004592 case glslang::EOpSparseImageLoad:
4593 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4594 lvalue = true;
4595 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004596 case glslang::EOpSparseTexture:
4597 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4598 lvalue = true;
4599 break;
4600 case glslang::EOpSparseTextureClamp:
4601 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4602 lvalue = true;
4603 break;
4604 case glslang::EOpSparseTextureLod:
4605 case glslang::EOpSparseTextureOffset:
4606 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4607 lvalue = true;
4608 break;
Rex Xu48edadf2015-12-31 16:11:41 +08004609 case glslang::EOpSparseTextureFetch:
4610 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4611 lvalue = true;
4612 break;
4613 case glslang::EOpSparseTextureFetchOffset:
4614 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4615 lvalue = true;
4616 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004617 case glslang::EOpSparseTextureLodOffset:
4618 case glslang::EOpSparseTextureGrad:
4619 case glslang::EOpSparseTextureOffsetClamp:
4620 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4621 lvalue = true;
4622 break;
4623 case glslang::EOpSparseTextureGradOffset:
4624 case glslang::EOpSparseTextureGradClamp:
4625 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4626 lvalue = true;
4627 break;
4628 case glslang::EOpSparseTextureGradOffsetClamp:
4629 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4630 lvalue = true;
4631 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004632 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004633 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4634 lvalue = true;
4635 break;
4636 case glslang::EOpSparseTextureGatherOffset:
4637 case glslang::EOpSparseTextureGatherOffsets:
4638 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4639 lvalue = true;
4640 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004641 case glslang::EOpSparseTextureGatherLod:
4642 if (i == 3)
4643 lvalue = true;
4644 break;
4645 case glslang::EOpSparseTextureGatherLodOffset:
4646 case glslang::EOpSparseTextureGatherLodOffsets:
4647 if (i == 4)
4648 lvalue = true;
4649 break;
Rex Xu129799a2017-07-05 17:23:28 +08004650 case glslang::EOpSparseImageLoadLod:
4651 if (i == 3)
4652 lvalue = true;
4653 break;
Chao Chen3a137962018-09-19 11:41:27 -07004654 case glslang::EOpImageSampleFootprintNV:
4655 if (i == 4)
4656 lvalue = true;
4657 break;
4658 case glslang::EOpImageSampleFootprintClampNV:
4659 case glslang::EOpImageSampleFootprintLodNV:
4660 if (i == 5)
4661 lvalue = true;
4662 break;
4663 case glslang::EOpImageSampleFootprintGradNV:
4664 if (i == 6)
4665 lvalue = true;
4666 break;
4667 case glslang::EOpImageSampleFootprintGradClampNV:
4668 if (i == 7)
4669 lvalue = true;
4670 break;
Rex Xufc618912015-09-09 16:42:49 +08004671 default:
4672 break;
4673 }
4674
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004675 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004676 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004677 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4678 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4679 } else
John Kessenicha28f7a72019-08-06 07:00:58 -06004680#endif
John Kessenich32cfd492016-02-02 12:37:46 -07004681 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004682 }
4683}
4684
John Kessenichfc51d282015-08-19 13:34:18 -06004685void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004686{
John Kessenichfc51d282015-08-19 13:34:18 -06004687 builder.clearAccessChain();
4688 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004689 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004690}
John Kessenich140f3df2015-06-26 16:58:36 -06004691
John Kessenichfc51d282015-08-19 13:34:18 -06004692spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4693{
John Kesseniche485c7a2017-05-31 18:50:53 -06004694 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004695 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004696
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004697 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004698
John Kessenichfc51d282015-08-19 13:34:18 -06004699 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004700
John Kessenichf43c7392019-03-31 10:51:57 -06004701 const glslang::TType &imageType = node->getAsAggregate()
4702 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4703 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004704 const glslang::TSampler sampler = imageType.getSampler();
John Kessenicha28f7a72019-08-06 07:00:58 -06004705#ifdef GLSLANG_WEB
4706 const bool f16ShadowCompare = false;
4707#else
Rex Xu1e5d7b02016-11-29 17:36:31 +08004708 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004709 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4710 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004711#endif
4712
John Kessenichf43c7392019-03-31 10:51:57 -06004713 const auto signExtensionMask = [&]() {
4714 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4715 if (sampler.type == glslang::EbtUint)
4716 return spv::ImageOperandsZeroExtendMask;
4717 else if (sampler.type == glslang::EbtInt)
4718 return spv::ImageOperandsSignExtendMask;
4719 }
4720 return spv::ImageOperandsMaskNone;
4721 };
4722
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004723 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4724
John Kessenichfc51d282015-08-19 13:34:18 -06004725 std::vector<spv::Id> arguments;
4726 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004727 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004728 else
4729 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004730 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004731
4732 spv::Builder::TextureParameters params = { };
4733 params.sampler = arguments[0];
4734
Rex Xu04db3f52015-09-16 11:44:02 +08004735 glslang::TCrackedTextureOp cracked;
4736 node->crackTexture(sampler, cracked);
4737
amhagan05506bb2017-06-13 16:53:02 -04004738 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004739
John Kessenichfc51d282015-08-19 13:34:18 -06004740 // Check for queries
4741 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004742 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4743 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004744 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004745
John Kessenichfc51d282015-08-19 13:34:18 -06004746 switch (node->getOp()) {
4747 case glslang::EOpImageQuerySize:
4748 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004749 if (arguments.size() > 1) {
4750 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004751 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004752 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004753 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenicha28f7a72019-08-06 07:00:58 -06004754#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06004755 case glslang::EOpImageQuerySamples:
4756 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004757 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004758 case glslang::EOpTextureQueryLod:
4759 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004760 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004761 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004762 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004763 case glslang::EOpSparseTexelsResident:
4764 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenicha28f7a72019-08-06 07:00:58 -06004765#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004766 default:
4767 assert(0);
4768 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004769 }
John Kessenich140f3df2015-06-26 16:58:36 -06004770 }
4771
LoopDawg4425f242018-02-18 11:40:01 -07004772 int components = node->getType().getVectorSize();
4773
4774 if (node->getOp() == glslang::EOpTextureFetch) {
4775 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4776 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4777 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4778 // here around e.g. which ones return scalars or other types.
4779 components = 4;
4780 }
4781
4782 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4783
4784 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4785
Rex Xufc618912015-09-09 16:42:49 +08004786 // Check for image functions other than queries
4787 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004788 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004789 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004790 spv::IdImmediate image = { true, *(opIt++) };
4791 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004792
4793 // Handle subpass operations
4794 // TODO: GLSL should change to have the "MS" only on the type rather than the
4795 // built-in function.
4796 if (cracked.subpass) {
4797 // add on the (0,0) coordinate
4798 spv::Id zero = builder.makeIntConstant(0);
4799 std::vector<spv::Id> comps;
4800 comps.push_back(zero);
4801 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004802 spv::IdImmediate coord = { true,
4803 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4804 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004805 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4806 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004807 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004808 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4809 }
4810 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004811 operands.push_back(imageOperands);
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004812 if (sampler.isMultiSample()) {
John Kessenichf43c7392019-03-31 10:51:57 -06004813 spv::IdImmediate imageOperand = { true, *(opIt++) };
4814 operands.push_back(imageOperand);
4815 }
John Kessenich6c292d32016-02-15 20:58:50 -07004816 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004817 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4818 builder.setPrecision(result, precision);
4819 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004820 }
4821
John Kessenich149afc32018-08-14 13:31:43 -06004822 spv::IdImmediate coord = { true, *(opIt++) };
4823 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004824 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004825 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004826 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004827 mask = mask | spv::ImageOperandsSampleMask;
4828 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004829 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004830 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4831 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004832 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004833 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004834 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4835 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004836 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004837 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004838 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4839 operands.push_back(imageOperands);
4840 }
4841 if (mask & spv::ImageOperandsSampleMask) {
4842 spv::IdImmediate imageOperand = { true, *opIt++ };
4843 operands.push_back(imageOperand);
4844 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004845 if (mask & spv::ImageOperandsLodMask) {
4846 spv::IdImmediate imageOperand = { true, *opIt++ };
4847 operands.push_back(imageOperand);
4848 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004849 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004850 spv::IdImmediate imageOperand = { true,
4851 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004852 operands.push_back(imageOperand);
4853 }
4854
John Kessenich149afc32018-08-14 13:31:43 -06004855 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004856 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004857
John Kessenich149afc32018-08-14 13:31:43 -06004858 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004859 builder.setPrecision(result[0], precision);
4860
4861 // If needed, add a conversion constructor to the proper size.
4862 if (components != node->getType().getVectorSize())
4863 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4864
4865 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004866 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004867
Jeff Bolz36831c92018-09-05 10:11:41 -05004868 // Push the texel value before the operands
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004869 if (sampler.isMultiSample() || cracked.lod) {
John Kessenich149afc32018-08-14 13:31:43 -06004870 spv::IdImmediate texel = { true, *(opIt + 1) };
4871 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004872 } else {
4873 spv::IdImmediate texel = { true, *opIt };
4874 operands.push_back(texel);
4875 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004876
4877 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004878 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004879 mask = mask | spv::ImageOperandsSampleMask;
4880 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004881 if (cracked.lod) {
4882 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4883 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4884 mask = mask | spv::ImageOperandsLodMask;
4885 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004886 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4887 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004888 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004889 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004890 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4891 operands.push_back(imageOperands);
4892 }
4893 if (mask & spv::ImageOperandsSampleMask) {
4894 spv::IdImmediate imageOperand = { true, *opIt++ };
4895 operands.push_back(imageOperand);
4896 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004897 if (mask & spv::ImageOperandsLodMask) {
4898 spv::IdImmediate imageOperand = { true, *opIt++ };
4899 operands.push_back(imageOperand);
4900 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004901 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004902 spv::IdImmediate imageOperand = { true,
4903 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004904 operands.push_back(imageOperand);
4905 }
4906
John Kessenich56bab042015-09-16 10:54:31 -06004907 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004908 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004909 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004910 return spv::NoResult;
John Kessenichf43c7392019-03-31 10:51:57 -06004911 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4912 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu5eafa472016-02-19 22:24:03 +08004913 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004914 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004915 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4916
Jeff Bolz36831c92018-09-05 10:11:41 -05004917 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004918 if (sampler.isMultiSample()) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004919 mask = mask | spv::ImageOperandsSampleMask;
4920 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004921 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004922 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4923 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4924
Jeff Bolz36831c92018-09-05 10:11:41 -05004925 mask = mask | spv::ImageOperandsLodMask;
4926 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004927 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4928 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004929 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004930 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004931 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004932 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004933 }
4934 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004935 spv::IdImmediate imageOperand = { true, *opIt++ };
4936 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004937 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004938 if (mask & spv::ImageOperandsLodMask) {
4939 spv::IdImmediate imageOperand = { true, *opIt++ };
4940 operands.push_back(imageOperand);
4941 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004942 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenich8985fc92020-03-03 10:25:07 -07004943 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
4944 TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004945 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004946 }
4947
4948 // Create the return type that was a special structure
4949 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004950 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004951 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4952 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4953
4954 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4955
4956 // Decode the return type
4957 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4958 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004959 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004960 // Process image atomic operations
4961
4962 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4963 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004964 // For non-MS, the sample value should be 0
John Kessenich3e4b6ff2019-08-08 01:15:24 -06004965 spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
John Kessenich149afc32018-08-14 13:31:43 -06004966 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004967
Jeff Bolz36831c92018-09-05 10:11:41 -05004968 spv::Id resultTypeId;
4969 // imageAtomicStore has a void return type so base the pointer type on
4970 // the type of the value operand.
4971 if (node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufb18b6d2020-02-22 22:04:31 +08004972 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
Jeff Bolz36831c92018-09-05 10:11:41 -05004973 } else {
4974 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4975 }
John Kessenich56bab042015-09-16 10:54:31 -06004976 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Jeff Bolz39ffdaf2020-03-09 10:48:12 -05004977 if (imageType.getQualifier().nonUniform) {
4978 builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
4979 }
Rex Xufc618912015-09-09 16:42:49 +08004980
4981 std::vector<spv::Id> operands;
4982 operands.push_back(pointer);
4983 for (; opIt != arguments.end(); ++opIt)
4984 operands.push_back(*opIt);
4985
John Kessenich8985fc92020-03-03 10:25:07 -07004986 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(),
4987 lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004988 }
4989 }
4990
John Kessenicha28f7a72019-08-06 07:00:58 -06004991#ifndef GLSLANG_WEB
amhagan05506bb2017-06-13 16:53:02 -04004992 // Check for fragment mask functions other than queries
4993 if (cracked.fragMask) {
4994 assert(sampler.ms);
4995
4996 auto opIt = arguments.begin();
4997 std::vector<spv::Id> operands;
4998
4999 // Extract the image if necessary
5000 if (builder.isSampledImage(params.sampler))
5001 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5002
5003 operands.push_back(params.sampler);
5004 ++opIt;
5005
5006 if (sampler.isSubpass()) {
5007 // add on the (0,0) coordinate
5008 spv::Id zero = builder.makeIntConstant(0);
5009 std::vector<spv::Id> comps;
5010 comps.push_back(zero);
5011 comps.push_back(zero);
John Kessenich8985fc92020-03-03 10:25:07 -07005012 operands.push_back(builder.makeCompositeConstant(
5013 builder.makeVectorType(builder.makeIntType(32), 2), comps));
amhagan05506bb2017-06-13 16:53:02 -04005014 }
5015
5016 for (; opIt != arguments.end(); ++opIt)
5017 operands.push_back(*opIt);
5018
5019 spv::Op fragMaskOp = spv::OpNop;
5020 if (node->getOp() == glslang::EOpFragmentMaskFetch)
5021 fragMaskOp = spv::OpFragmentMaskFetchAMD;
5022 else if (node->getOp() == glslang::EOpFragmentFetch)
5023 fragMaskOp = spv::OpFragmentFetchAMD;
5024
5025 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
5026 builder.addCapability(spv::CapabilityFragmentMaskAMD);
5027 return builder.createOp(fragMaskOp, resultType(), operands);
5028 }
5029#endif
5030
Rex Xufc618912015-09-09 16:42:49 +08005031 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08005032 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07005033 bool imageFootprint = node->isImageFootprint();
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005034 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
Rex Xu71519fe2015-11-11 15:35:47 +08005035
John Kessenichfc51d282015-08-19 13:34:18 -06005036 // check for bias argument
5037 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08005038 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005039 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08005040 if (cracked.gather)
5041 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08005042
5043 if (f16ShadowCompare)
5044 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005045 if (cracked.offset)
5046 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08005047 else if (cracked.offsets)
5048 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06005049 if (cracked.grad)
5050 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08005051 if (cracked.lodClamp)
5052 ++nonBiasArgCount;
5053 if (sparse)
5054 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07005055 if (imageFootprint)
5056 //Following three extra arguments
5057 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5058 nonBiasArgCount += 3;
John Kessenichfc51d282015-08-19 13:34:18 -06005059 if ((int)arguments.size() > nonBiasArgCount)
5060 bias = true;
5061 }
5062
John Kessenicha5c33d62016-06-02 23:45:21 -06005063 // See if the sampler param should really be just the SPV image part
5064 if (cracked.fetch) {
5065 // a fetch needs to have the image extracted first
5066 if (builder.isSampledImage(params.sampler))
5067 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
5068 }
5069
John Kessenicha28f7a72019-08-06 07:00:58 -06005070#ifndef GLSLANG_WEB
Rex Xu225e0fc2016-11-17 17:47:59 +08005071 if (cracked.gather) {
5072 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
5073 if (bias || cracked.lod ||
5074 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
5075 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08005076 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08005077 }
5078 }
5079#endif
5080
John Kessenichfc51d282015-08-19 13:34:18 -06005081 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07005082
John Kessenichfc51d282015-08-19 13:34:18 -06005083 params.coords = arguments[1];
5084 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07005085 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07005086
5087 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08005088 if (cubeCompare || f16ShadowCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06005089 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08005090 ++extraArgs;
5091 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07005092 params.Dref = arguments[2];
5093 ++extraArgs;
5094 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06005095 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06005096 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06005097 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06005098 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06005099 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005100 dRefComp = builder.getNumComponents(params.coords) - 1;
5101 indexes.push_back(dRefComp);
John Kessenich8985fc92020-03-03 10:25:07 -07005102 params.Dref = builder.createCompositeExtract(params.coords,
5103 builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
John Kessenichfc51d282015-08-19 13:34:18 -06005104 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005105
5106 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06005107 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005108 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06005109 ++extraArgs;
John Kessenichb9197c82019-08-11 07:41:45 -06005110 } else if (glslangIntermediate->getStage() != EShLangFragment &&
5111 !(glslangIntermediate->getStage() == EShLangCompute &&
5112 glslangIntermediate->hasLayoutDerivativeModeNone())) {
John Kessenich019f08f2016-02-15 15:40:42 -07005113 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
5114 noImplicitLod = true;
5115 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005116
5117 // multisample
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005118 if (sampler.isMultiSample()) {
LoopDawgef94b1a2017-07-24 18:45:37 -06005119 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08005120 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005121 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005122
5123 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06005124 if (cracked.grad) {
5125 params.gradX = arguments[2 + extraArgs];
5126 params.gradY = arguments[3 + extraArgs];
5127 extraArgs += 2;
5128 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005129
5130 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07005131 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06005132 params.offset = arguments[2 + extraArgs];
5133 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005134 } else if (cracked.offsets) {
5135 params.offsets = arguments[2 + extraArgs];
5136 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06005137 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005138
John Kessenich3e4b6ff2019-08-08 01:15:24 -06005139#ifndef GLSLANG_WEB
John Kessenich76d4dfc2016-06-16 12:43:23 -06005140 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08005141 if (cracked.lodClamp) {
5142 params.lodClamp = arguments[2 + extraArgs];
5143 ++extraArgs;
5144 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005145 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08005146 if (sparse) {
5147 params.texelOut = arguments[2 + extraArgs];
5148 ++extraArgs;
5149 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06005150 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07005151 if (cracked.gather && ! sampler.shadow) {
5152 // default component is 0, if missing, otherwise an argument
5153 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06005154 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07005155 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08005156 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06005157 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08005158 }
Chao Chen3a137962018-09-19 11:41:27 -07005159 spv::Id resultStruct = spv::NoResult;
5160 if (imageFootprint) {
5161 //Following three extra arguments
5162 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
5163 params.granularity = arguments[2 + extraArgs];
5164 params.coarse = arguments[3 + extraArgs];
5165 resultStruct = arguments[4 + extraArgs];
5166 extraArgs += 3;
5167 }
5168#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08005169 // bias
5170 if (bias) {
5171 params.bias = arguments[2 + extraArgs];
5172 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07005173 }
John Kessenichfc51d282015-08-19 13:34:18 -06005174
John Kessenicha28f7a72019-08-06 07:00:58 -06005175#ifndef GLSLANG_WEB
Chao Chen3a137962018-09-19 11:41:27 -07005176 if (imageFootprint) {
5177 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
5178 builder.addCapability(spv::CapabilityImageFootprintNV);
5179
5180
5181 //resultStructType(OpenGL type) contains 5 elements:
5182 //struct gl_TextureFootprint2DNV {
5183 // uvec2 anchor;
5184 // uvec2 offset;
5185 // uvec2 mask;
5186 // uint lod;
5187 // uint granularity;
5188 //};
5189 //or
5190 //struct gl_TextureFootprint3DNV {
5191 // uvec3 anchor;
5192 // uvec3 offset;
5193 // uvec2 mask;
5194 // uint lod;
5195 // uint granularity;
5196 //};
5197 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
5198 assert(builder.isStructType(resultStructType));
5199
5200 //resType (SPIR-V type) contains 6 elements:
5201 //Member 0 must be a Boolean type scalar(LOD),
5202 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
5203 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
5204 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
5205 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
5206 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
5207 std::vector<spv::Id> members;
5208 members.push_back(resultType());
5209 for (int i = 0; i < 5; i++) {
5210 members.push_back(builder.getContainedTypeId(resultStructType, i));
5211 }
5212 spv::Id resType = builder.makeStructType(members, "ResType");
5213
5214 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06005215 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
5216 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07005217
5218 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
5219 for (int i = 0; i < 5; i++) {
5220 builder.clearAccessChain();
5221 builder.setAccessChainLValue(resultStruct);
5222
5223 //Accessing to a struct we created, no coherent flag is set
5224 spv::Builder::AccessChain::CoherentFlags flags;
5225 flags.clear();
5226
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005227 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
John Kessenich8985fc92020-03-03 10:25:07 -07005228 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
5229 i+1));
Chao Chen3a137962018-09-19 11:41:27 -07005230 }
5231 return builder.createCompositeExtract(res, resultType(), 0);
5232 }
5233#endif
5234
John Kessenich65336482016-06-16 14:06:26 -06005235 // projective component (might not to move)
5236 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
5237 // are divided by the last component of P."
5238 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
5239 // unused components will appear after all used components."
5240 if (cracked.proj) {
5241 int projSourceComp = builder.getNumComponents(params.coords) - 1;
5242 int projTargetComp;
5243 switch (sampler.dim) {
5244 case glslang::Esd1D: projTargetComp = 1; break;
5245 case glslang::Esd2D: projTargetComp = 2; break;
5246 case glslang::EsdRect: projTargetComp = 2; break;
5247 default: projTargetComp = projSourceComp; break;
5248 }
5249 // copy the projective coordinate if we have to
5250 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07005251 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005252 builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
John Kessenich65336482016-06-16 14:06:26 -06005253 params.coords = builder.createCompositeInsert(projComp, params.coords,
John Kessenich8985fc92020-03-03 10:25:07 -07005254 builder.getTypeId(params.coords), projTargetComp);
John Kessenich65336482016-06-16 14:06:26 -06005255 }
5256 }
5257
John Kessenichf8d1d742019-10-21 06:55:11 -06005258#ifndef GLSLANG_WEB
Jeff Bolz36831c92018-09-05 10:11:41 -05005259 // nonprivate
5260 if (imageType.getQualifier().nonprivate) {
5261 params.nonprivate = true;
5262 }
5263
5264 // volatile
5265 if (imageType.getQualifier().volatil) {
5266 params.volatil = true;
5267 }
John Kessenichf8d1d742019-10-21 06:55:11 -06005268#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05005269
St0fFa1184dd2018-04-09 21:08:14 +02005270 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06005271 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
5272 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02005273 );
LoopDawg4425f242018-02-18 11:40:01 -07005274
5275 if (components != node->getType().getVectorSize())
5276 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
5277
5278 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06005279}
5280
5281spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
5282{
5283 // Grab the function's pointer from the previously created function
5284 spv::Function* function = functionMap[node->getName().c_str()];
5285 if (! function)
5286 return 0;
5287
5288 const glslang::TIntermSequence& glslangArgs = node->getSequence();
5289 const glslang::TQualifierList& qualifiers = node->getQualifierList();
5290
5291 // See comments in makeFunctions() for details about the semantics for parameter passing.
5292 //
5293 // These imply we need a four step process:
5294 // 1. Evaluate the arguments
5295 // 2. Allocate and make copies of in, out, and inout arguments
5296 // 3. Make the call
5297 // 4. Copy back the results
5298
John Kessenichd3ed90b2018-05-04 11:43:03 -06005299 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06005300 std::vector<spv::Builder::AccessChain> lValues;
5301 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07005302 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06005303 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005304 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06005305 // build l-value
5306 builder.clearAccessChain();
5307 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005308 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005309 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005310 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005311 // save l-value
5312 lValues.push_back(builder.getAccessChain());
5313 } else {
5314 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005315 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005316 }
5317 }
5318
5319 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5320 // copy the original into that space.
5321 //
5322 // Also, build up the list of actual arguments to pass in for the call
5323 int lValueCount = 0;
5324 int rValueCount = 0;
5325 std::vector<spv::Id> spvArgs;
5326 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5327 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005328 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005329 builder.setAccessChain(lValues[lValueCount]);
5330 arg = builder.accessChainGetLValue();
5331 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005332 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005333 // need space to hold the copy
John Kessenich8985fc92020-03-03 10:25:07 -07005334 arg = builder.createVariable(spv::StorageClassFunction,
5335 builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005336 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5337 // need to copy the input into output space
5338 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005339 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005340 builder.clearAccessChain();
5341 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005342 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005343 }
5344 ++lValueCount;
5345 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005346 // process r-value, which involves a copy for a type mismatch
5347 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5348 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5349 builder.clearAccessChain();
5350 builder.setAccessChainLValue(argCopy);
5351 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5352 arg = builder.createLoad(argCopy);
5353 } else
5354 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005355 ++rValueCount;
5356 }
5357 spvArgs.push_back(arg);
5358 }
5359
5360 // 3. Make the call.
5361 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005362 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005363
5364 // 4. Copy back out an "out" arguments.
5365 lValueCount = 0;
5366 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005367 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005368 ++lValueCount;
5369 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005370 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5371 spv::Id copy = builder.createLoad(spvArgs[a]);
5372 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005373 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005374 }
5375 ++lValueCount;
5376 }
5377 }
5378
5379 return result;
5380}
5381
5382// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005383spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005384 spv::Id typeId, spv::Id left, spv::Id right,
5385 glslang::TBasicType typeProxy, bool reduceComparison)
5386{
John Kessenich66011cb2018-03-06 16:12:04 -07005387 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5388 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005389 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005390
5391 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005392 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005393 bool comparison = false;
5394
5395 switch (op) {
5396 case glslang::EOpAdd:
5397 case glslang::EOpAddAssign:
5398 if (isFloat)
5399 binOp = spv::OpFAdd;
5400 else
5401 binOp = spv::OpIAdd;
5402 break;
5403 case glslang::EOpSub:
5404 case glslang::EOpSubAssign:
5405 if (isFloat)
5406 binOp = spv::OpFSub;
5407 else
5408 binOp = spv::OpISub;
5409 break;
5410 case glslang::EOpMul:
5411 case glslang::EOpMulAssign:
5412 if (isFloat)
5413 binOp = spv::OpFMul;
5414 else
5415 binOp = spv::OpIMul;
5416 break;
5417 case glslang::EOpVectorTimesScalar:
5418 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005419 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005420 if (builder.isVector(right))
5421 std::swap(left, right);
5422 assert(builder.isScalar(right));
5423 needMatchingVectors = false;
5424 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005425 } else if (isFloat)
5426 binOp = spv::OpFMul;
5427 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005428 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005429 break;
5430 case glslang::EOpVectorTimesMatrix:
5431 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005432 binOp = spv::OpVectorTimesMatrix;
5433 break;
5434 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005435 binOp = spv::OpMatrixTimesVector;
5436 break;
5437 case glslang::EOpMatrixTimesScalar:
5438 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005439 binOp = spv::OpMatrixTimesScalar;
5440 break;
5441 case glslang::EOpMatrixTimesMatrix:
5442 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005443 binOp = spv::OpMatrixTimesMatrix;
5444 break;
5445 case glslang::EOpOuterProduct:
5446 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005447 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005448 break;
5449
5450 case glslang::EOpDiv:
5451 case glslang::EOpDivAssign:
5452 if (isFloat)
5453 binOp = spv::OpFDiv;
5454 else if (isUnsigned)
5455 binOp = spv::OpUDiv;
5456 else
5457 binOp = spv::OpSDiv;
5458 break;
5459 case glslang::EOpMod:
5460 case glslang::EOpModAssign:
5461 if (isFloat)
5462 binOp = spv::OpFMod;
5463 else if (isUnsigned)
5464 binOp = spv::OpUMod;
5465 else
5466 binOp = spv::OpSMod;
5467 break;
5468 case glslang::EOpRightShift:
5469 case glslang::EOpRightShiftAssign:
5470 if (isUnsigned)
5471 binOp = spv::OpShiftRightLogical;
5472 else
5473 binOp = spv::OpShiftRightArithmetic;
5474 break;
5475 case glslang::EOpLeftShift:
5476 case glslang::EOpLeftShiftAssign:
5477 binOp = spv::OpShiftLeftLogical;
5478 break;
5479 case glslang::EOpAnd:
5480 case glslang::EOpAndAssign:
5481 binOp = spv::OpBitwiseAnd;
5482 break;
5483 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005484 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005485 binOp = spv::OpLogicalAnd;
5486 break;
5487 case glslang::EOpInclusiveOr:
5488 case glslang::EOpInclusiveOrAssign:
5489 binOp = spv::OpBitwiseOr;
5490 break;
5491 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005492 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 binOp = spv::OpLogicalOr;
5494 break;
5495 case glslang::EOpExclusiveOr:
5496 case glslang::EOpExclusiveOrAssign:
5497 binOp = spv::OpBitwiseXor;
5498 break;
5499 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005500 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005501 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005502 break;
5503
Ian Romanickb3bd4022019-01-21 08:57:25 -08005504 case glslang::EOpAbsDifference:
5505 binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
5506 break;
5507
5508 case glslang::EOpAddSaturate:
5509 binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
5510 break;
5511
5512 case glslang::EOpSubSaturate:
5513 binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
5514 break;
5515
5516 case glslang::EOpAverage:
5517 binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
5518 break;
5519
5520 case glslang::EOpAverageRounded:
5521 binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
5522 break;
5523
5524 case glslang::EOpMul32x16:
5525 binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
5526 break;
5527
John Kessenich140f3df2015-06-26 16:58:36 -06005528 case glslang::EOpLessThan:
5529 case glslang::EOpGreaterThan:
5530 case glslang::EOpLessThanEqual:
5531 case glslang::EOpGreaterThanEqual:
5532 case glslang::EOpEqual:
5533 case glslang::EOpNotEqual:
5534 case glslang::EOpVectorEqual:
5535 case glslang::EOpVectorNotEqual:
5536 comparison = true;
5537 break;
5538 default:
5539 break;
5540 }
5541
John Kessenich7c1aa102015-10-15 13:29:11 -06005542 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005543 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005544 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005545 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5546 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005547 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005548
5549 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005550 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005551 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005552
qining25262b32016-05-06 17:25:16 -04005553 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005554 decorations.addNoContraction(builder, result);
5555 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005556 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005557 }
5558
5559 if (! comparison)
5560 return 0;
5561
John Kessenich7c1aa102015-10-15 13:29:11 -06005562 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005563
John Kessenich4583b612016-08-07 19:14:22 -06005564 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005565 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5566 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenichb9197c82019-08-11 07:41:45 -06005567 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005568 return result;
5569 }
John Kessenich140f3df2015-06-26 16:58:36 -06005570
5571 switch (op) {
5572 case glslang::EOpLessThan:
5573 if (isFloat)
5574 binOp = spv::OpFOrdLessThan;
5575 else if (isUnsigned)
5576 binOp = spv::OpULessThan;
5577 else
5578 binOp = spv::OpSLessThan;
5579 break;
5580 case glslang::EOpGreaterThan:
5581 if (isFloat)
5582 binOp = spv::OpFOrdGreaterThan;
5583 else if (isUnsigned)
5584 binOp = spv::OpUGreaterThan;
5585 else
5586 binOp = spv::OpSGreaterThan;
5587 break;
5588 case glslang::EOpLessThanEqual:
5589 if (isFloat)
5590 binOp = spv::OpFOrdLessThanEqual;
5591 else if (isUnsigned)
5592 binOp = spv::OpULessThanEqual;
5593 else
5594 binOp = spv::OpSLessThanEqual;
5595 break;
5596 case glslang::EOpGreaterThanEqual:
5597 if (isFloat)
5598 binOp = spv::OpFOrdGreaterThanEqual;
5599 else if (isUnsigned)
5600 binOp = spv::OpUGreaterThanEqual;
5601 else
5602 binOp = spv::OpSGreaterThanEqual;
5603 break;
5604 case glslang::EOpEqual:
5605 case glslang::EOpVectorEqual:
5606 if (isFloat)
5607 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005608 else if (isBool)
5609 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005610 else
5611 binOp = spv::OpIEqual;
5612 break;
5613 case glslang::EOpNotEqual:
5614 case glslang::EOpVectorNotEqual:
5615 if (isFloat)
5616 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005617 else if (isBool)
5618 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005619 else
5620 binOp = spv::OpINotEqual;
5621 break;
5622 default:
5623 break;
5624 }
5625
qining25262b32016-05-06 17:25:16 -04005626 if (binOp != spv::OpNop) {
5627 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005628 decorations.addNoContraction(builder, result);
5629 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005630 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005631 }
John Kessenich140f3df2015-06-26 16:58:36 -06005632
5633 return 0;
5634}
5635
John Kessenich04bb8a02015-12-12 12:28:14 -07005636//
5637// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5638// These can be any of:
5639//
5640// matrix * scalar
5641// scalar * matrix
5642// matrix * matrix linear algebraic
5643// matrix * vector
5644// vector * matrix
5645// matrix * matrix componentwise
5646// matrix op matrix op in {+, -, /}
5647// matrix op scalar op in {+, -, /}
5648// scalar op matrix op in {+, -, /}
5649//
John Kessenichead86222018-03-28 18:01:20 -06005650spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5651 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005652{
5653 bool firstClass = true;
5654
5655 // First, handle first-class matrix operations (* and matrix/scalar)
5656 switch (op) {
5657 case spv::OpFDiv:
5658 if (builder.isMatrix(left) && builder.isScalar(right)) {
5659 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005660 spv::Id resultType = builder.getTypeId(right);
5661 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005662 op = spv::OpMatrixTimesScalar;
5663 } else
5664 firstClass = false;
5665 break;
5666 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005667 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005668 std::swap(left, right);
5669 assert(builder.isScalar(right));
5670 break;
5671 case spv::OpVectorTimesMatrix:
5672 assert(builder.isVector(left));
5673 assert(builder.isMatrix(right));
5674 break;
5675 case spv::OpMatrixTimesVector:
5676 assert(builder.isMatrix(left));
5677 assert(builder.isVector(right));
5678 break;
5679 case spv::OpMatrixTimesMatrix:
5680 assert(builder.isMatrix(left));
5681 assert(builder.isMatrix(right));
5682 break;
5683 default:
5684 firstClass = false;
5685 break;
5686 }
5687
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005688 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5689 firstClass = true;
5690
qining25262b32016-05-06 17:25:16 -04005691 if (firstClass) {
5692 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichb9197c82019-08-11 07:41:45 -06005693 decorations.addNoContraction(builder, result);
5694 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005695 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005696 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005697
LoopDawg592860c2016-06-09 08:57:35 -06005698 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005699 // The result type of all of them is the same type as the (a) matrix operand.
5700 // The algorithm is to:
5701 // - break the matrix(es) into vectors
5702 // - smear any scalar to a vector
5703 // - do vector operations
5704 // - make a matrix out the vector results
5705 switch (op) {
5706 case spv::OpFAdd:
5707 case spv::OpFSub:
5708 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005709 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005710 case spv::OpFMul:
5711 {
5712 // one time set up...
5713 bool leftMat = builder.isMatrix(left);
5714 bool rightMat = builder.isMatrix(right);
5715 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5716 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5717 spv::Id scalarType = builder.getScalarTypeId(typeId);
5718 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5719 std::vector<spv::Id> results;
5720 spv::Id smearVec = spv::NoResult;
5721 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005722 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005723 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005724 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005725
5726 // do each vector op
5727 for (unsigned int c = 0; c < numCols; ++c) {
5728 std::vector<unsigned int> indexes;
5729 indexes.push_back(c);
5730 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5731 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005732 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichb9197c82019-08-11 07:41:45 -06005733 decorations.addNoContraction(builder, result);
5734 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005735 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005736 }
5737
5738 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005739 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06005740 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06005741 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005742 }
5743 default:
5744 assert(0);
5745 return spv::NoResult;
5746 }
5747}
5748
John Kessenichead86222018-03-28 18:01:20 -06005749spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
John Kessenich8985fc92020-03-03 10:25:07 -07005750 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005751{
5752 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005753 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005754 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005755 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5756 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005757
5758 switch (op) {
5759 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005760 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005761 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005762 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005763 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005764 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005765 unaryOp = spv::OpSNegate;
5766 break;
5767
5768 case glslang::EOpLogicalNot:
5769 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005770 unaryOp = spv::OpLogicalNot;
5771 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005772 case glslang::EOpBitwiseNot:
5773 unaryOp = spv::OpNot;
5774 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005775
John Kessenich140f3df2015-06-26 16:58:36 -06005776 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005777 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005778 break;
5779 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005780 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005781 break;
5782 case glslang::EOpTranspose:
5783 unaryOp = spv::OpTranspose;
5784 break;
5785
5786 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005787 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005788 break;
5789 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005790 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005791 break;
5792 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005793 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005794 break;
5795 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005796 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005797 break;
5798 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005799 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005800 break;
5801 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005802 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005803 break;
5804 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005805 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005806 break;
5807 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005808 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005809 break;
5810
5811 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005812 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005813 break;
5814 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005815 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005818 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005819 break;
5820 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005821 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005822 break;
5823 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005824 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005825 break;
5826 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005827 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005828 break;
5829
5830 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005831 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005834 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005835 break;
5836
5837 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005838 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005839 break;
5840 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005841 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005844 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005845 break;
5846 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005847 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005848 break;
5849 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005850 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005851 break;
5852 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005853 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005854 break;
5855
5856 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005857 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005858 break;
5859 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005860 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005861 break;
5862 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005863 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
5865 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005866 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005867 break;
5868 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005869 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005870 break;
5871 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005872 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005873 break;
5874
5875 case glslang::EOpIsNan:
5876 unaryOp = spv::OpIsNan;
5877 break;
5878 case glslang::EOpIsInf:
5879 unaryOp = spv::OpIsInf;
5880 break;
LoopDawg592860c2016-06-09 08:57:35 -06005881 case glslang::EOpIsFinite:
5882 unaryOp = spv::OpIsFinite;
5883 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005884
Rex Xucbc426e2015-12-15 16:03:10 +08005885 case glslang::EOpFloatBitsToInt:
5886 case glslang::EOpFloatBitsToUint:
5887 case glslang::EOpIntBitsToFloat:
5888 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005889 case glslang::EOpDoubleBitsToInt64:
5890 case glslang::EOpDoubleBitsToUint64:
5891 case glslang::EOpInt64BitsToDouble:
5892 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005893 case glslang::EOpFloat16BitsToInt16:
5894 case glslang::EOpFloat16BitsToUint16:
5895 case glslang::EOpInt16BitsToFloat16:
5896 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005897 unaryOp = spv::OpBitcast;
5898 break;
5899
John Kessenich140f3df2015-06-26 16:58:36 -06005900 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005901 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005902 break;
5903 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005904 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005905 break;
5906 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005907 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005908 break;
5909 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005910 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005911 break;
5912 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005913 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005914 break;
5915 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005916 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005917 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005918#ifndef GLSLANG_WEB
John Kessenichfc51d282015-08-19 13:34:18 -06005919 case glslang::EOpPackSnorm4x8:
5920 libCall = spv::GLSLstd450PackSnorm4x8;
5921 break;
5922 case glslang::EOpUnpackSnorm4x8:
5923 libCall = spv::GLSLstd450UnpackSnorm4x8;
5924 break;
5925 case glslang::EOpPackUnorm4x8:
5926 libCall = spv::GLSLstd450PackUnorm4x8;
5927 break;
5928 case glslang::EOpUnpackUnorm4x8:
5929 libCall = spv::GLSLstd450UnpackUnorm4x8;
5930 break;
5931 case glslang::EOpPackDouble2x32:
5932 libCall = spv::GLSLstd450PackDouble2x32;
5933 break;
5934 case glslang::EOpUnpackDouble2x32:
5935 libCall = spv::GLSLstd450UnpackDouble2x32;
5936 break;
John Kessenichb9197c82019-08-11 07:41:45 -06005937#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005938
Rex Xu8ff43de2016-04-22 16:51:45 +08005939 case glslang::EOpPackInt2x32:
5940 case glslang::EOpUnpackInt2x32:
5941 case glslang::EOpPackUint2x32:
5942 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005943 case glslang::EOpPack16:
5944 case glslang::EOpPack32:
5945 case glslang::EOpPack64:
5946 case glslang::EOpUnpack32:
5947 case glslang::EOpUnpack16:
5948 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005949 case glslang::EOpPackInt2x16:
5950 case glslang::EOpUnpackInt2x16:
5951 case glslang::EOpPackUint2x16:
5952 case glslang::EOpUnpackUint2x16:
5953 case glslang::EOpPackInt4x16:
5954 case glslang::EOpUnpackInt4x16:
5955 case glslang::EOpPackUint4x16:
5956 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005957 case glslang::EOpPackFloat2x16:
5958 case glslang::EOpUnpackFloat2x16:
5959 unaryOp = spv::OpBitcast;
5960 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005961
John Kessenich140f3df2015-06-26 16:58:36 -06005962 case glslang::EOpDPdx:
5963 unaryOp = spv::OpDPdx;
5964 break;
5965 case glslang::EOpDPdy:
5966 unaryOp = spv::OpDPdy;
5967 break;
5968 case glslang::EOpFwidth:
5969 unaryOp = spv::OpFwidth;
5970 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06005971
John Kessenich140f3df2015-06-26 16:58:36 -06005972 case glslang::EOpAny:
5973 unaryOp = spv::OpAny;
5974 break;
5975 case glslang::EOpAll:
5976 unaryOp = spv::OpAll;
5977 break;
5978
5979 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005980 if (isFloat)
5981 libCall = spv::GLSLstd450FAbs;
5982 else
5983 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005984 break;
5985 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005986 if (isFloat)
5987 libCall = spv::GLSLstd450FSign;
5988 else
5989 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005990 break;
5991
John Kessenicha28f7a72019-08-06 07:00:58 -06005992#ifndef GLSLANG_WEB
5993 case glslang::EOpDPdxFine:
5994 unaryOp = spv::OpDPdxFine;
5995 break;
5996 case glslang::EOpDPdyFine:
5997 unaryOp = spv::OpDPdyFine;
5998 break;
5999 case glslang::EOpFwidthFine:
6000 unaryOp = spv::OpFwidthFine;
6001 break;
6002 case glslang::EOpDPdxCoarse:
6003 unaryOp = spv::OpDPdxCoarse;
6004 break;
6005 case glslang::EOpDPdyCoarse:
6006 unaryOp = spv::OpDPdyCoarse;
6007 break;
6008 case glslang::EOpFwidthCoarse:
6009 unaryOp = spv::OpFwidthCoarse;
6010 break;
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04006011 case glslang::EOpRayQueryProceed:
6012 unaryOp = spv::OpRayQueryProceedKHR;
6013 break;
6014 case glslang::EOpRayQueryGetRayTMin:
6015 unaryOp = spv::OpRayQueryGetRayTMinKHR;
6016 break;
6017 case glslang::EOpRayQueryGetRayFlags:
6018 unaryOp = spv::OpRayQueryGetRayFlagsKHR;
6019 break;
6020 case glslang::EOpRayQueryGetWorldRayOrigin:
6021 unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
6022 break;
6023 case glslang::EOpRayQueryGetWorldRayDirection:
6024 unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
6025 break;
6026 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
6027 unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
6028 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006029 case glslang::EOpInterpolateAtCentroid:
6030 if (typeProxy == glslang::EbtFloat16)
6031 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6032 libCall = spv::GLSLstd450InterpolateAtCentroid;
6033 break;
John Kessenichfc51d282015-08-19 13:34:18 -06006034 case glslang::EOpAtomicCounterIncrement:
6035 case glslang::EOpAtomicCounterDecrement:
6036 case glslang::EOpAtomicCounter:
6037 {
6038 // Handle all of the atomics in one place, in createAtomicOperation()
6039 std::vector<spv::Id> operands;
6040 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006041 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06006042 }
6043
John Kessenichfc51d282015-08-19 13:34:18 -06006044 case glslang::EOpBitFieldReverse:
6045 unaryOp = spv::OpBitReverse;
6046 break;
6047 case glslang::EOpBitCount:
6048 unaryOp = spv::OpBitCount;
6049 break;
6050 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006051 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006052 break;
6053 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07006054 if (isUnsigned)
6055 libCall = spv::GLSLstd450FindUMsb;
6056 else
6057 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06006058 break;
6059
Ian Romanickb3bd4022019-01-21 08:57:25 -08006060 case glslang::EOpCountLeadingZeros:
6061 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6062 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6063 unaryOp = spv::OpUCountLeadingZerosINTEL;
6064 break;
6065
6066 case glslang::EOpCountTrailingZeros:
6067 builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
6068 builder.addExtension("SPV_INTEL_shader_integer_functions2");
6069 unaryOp = spv::OpUCountTrailingZerosINTEL;
6070 break;
6071
Rex Xu574ab042016-04-14 16:53:07 +08006072 case glslang::EOpBallot:
6073 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006074 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08006075 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08006076 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08006077 case glslang::EOpMinInvocations:
6078 case glslang::EOpMaxInvocations:
6079 case glslang::EOpAddInvocations:
6080 case glslang::EOpMinInvocationsNonUniform:
6081 case glslang::EOpMaxInvocationsNonUniform:
6082 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006083 case glslang::EOpMinInvocationsInclusiveScan:
6084 case glslang::EOpMaxInvocationsInclusiveScan:
6085 case glslang::EOpAddInvocationsInclusiveScan:
6086 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6087 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6088 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6089 case glslang::EOpMinInvocationsExclusiveScan:
6090 case glslang::EOpMaxInvocationsExclusiveScan:
6091 case glslang::EOpAddInvocationsExclusiveScan:
6092 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6093 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6094 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu51596642016-09-21 18:56:12 +08006095 {
6096 std::vector<spv::Id> operands;
6097 operands.push_back(operand);
6098 return createInvocationsOperation(op, typeId, operands, typeProxy);
6099 }
John Kessenich66011cb2018-03-06 16:12:04 -07006100 case glslang::EOpSubgroupAll:
6101 case glslang::EOpSubgroupAny:
6102 case glslang::EOpSubgroupAllEqual:
6103 case glslang::EOpSubgroupBroadcastFirst:
6104 case glslang::EOpSubgroupBallot:
6105 case glslang::EOpSubgroupInverseBallot:
6106 case glslang::EOpSubgroupBallotBitCount:
6107 case glslang::EOpSubgroupBallotInclusiveBitCount:
6108 case glslang::EOpSubgroupBallotExclusiveBitCount:
6109 case glslang::EOpSubgroupBallotFindLSB:
6110 case glslang::EOpSubgroupBallotFindMSB:
6111 case glslang::EOpSubgroupAdd:
6112 case glslang::EOpSubgroupMul:
6113 case glslang::EOpSubgroupMin:
6114 case glslang::EOpSubgroupMax:
6115 case glslang::EOpSubgroupAnd:
6116 case glslang::EOpSubgroupOr:
6117 case glslang::EOpSubgroupXor:
6118 case glslang::EOpSubgroupInclusiveAdd:
6119 case glslang::EOpSubgroupInclusiveMul:
6120 case glslang::EOpSubgroupInclusiveMin:
6121 case glslang::EOpSubgroupInclusiveMax:
6122 case glslang::EOpSubgroupInclusiveAnd:
6123 case glslang::EOpSubgroupInclusiveOr:
6124 case glslang::EOpSubgroupInclusiveXor:
6125 case glslang::EOpSubgroupExclusiveAdd:
6126 case glslang::EOpSubgroupExclusiveMul:
6127 case glslang::EOpSubgroupExclusiveMin:
6128 case glslang::EOpSubgroupExclusiveMax:
6129 case glslang::EOpSubgroupExclusiveAnd:
6130 case glslang::EOpSubgroupExclusiveOr:
6131 case glslang::EOpSubgroupExclusiveXor:
6132 case glslang::EOpSubgroupQuadSwapHorizontal:
6133 case glslang::EOpSubgroupQuadSwapVertical:
6134 case glslang::EOpSubgroupQuadSwapDiagonal: {
6135 std::vector<spv::Id> operands;
6136 operands.push_back(operand);
6137 return createSubgroupOperation(op, typeId, operands, typeProxy);
6138 }
Rex Xu9d93a232016-05-05 12:30:44 +08006139 case glslang::EOpMbcnt:
6140 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6141 libCall = spv::MbcntAMD;
6142 break;
6143
6144 case glslang::EOpCubeFaceIndex:
6145 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6146 libCall = spv::CubeFaceIndexAMD;
6147 break;
6148
6149 case glslang::EOpCubeFaceCoord:
6150 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
6151 libCall = spv::CubeFaceCoordAMD;
6152 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006153 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006154 unaryOp = spv::OpGroupNonUniformPartitionNV;
6155 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006156 case glslang::EOpConstructReference:
6157 unaryOp = spv::OpBitcast;
6158 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06006159#endif
Jeff Bolz88220d52019-05-08 10:24:46 -05006160
6161 case glslang::EOpCopyObject:
6162 unaryOp = spv::OpCopyObject;
6163 break;
6164
John Kessenich140f3df2015-06-26 16:58:36 -06006165 default:
6166 return 0;
6167 }
6168
6169 spv::Id id;
6170 if (libCall >= 0) {
6171 std::vector<spv::Id> args;
6172 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08006173 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08006174 } else {
John Kessenich91cef522016-05-05 16:45:40 -06006175 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08006176 }
John Kessenich140f3df2015-06-26 16:58:36 -06006177
John Kessenichb9197c82019-08-11 07:41:45 -06006178 decorations.addNoContraction(builder, id);
6179 decorations.addNonUniform(builder, id);
John Kessenichead86222018-03-28 18:01:20 -06006180 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006181}
6182
John Kessenich7a53f762016-01-20 11:19:27 -07006183// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06006184spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
6185 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07006186{
6187 // Handle unary operations vector by vector.
6188 // The result type is the same type as the original type.
6189 // The algorithm is to:
6190 // - break the matrix into vectors
6191 // - apply the operation to each vector
6192 // - make a matrix out the vector results
6193
6194 // get the types sorted out
6195 int numCols = builder.getNumColumns(operand);
6196 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08006197 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
6198 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07006199 std::vector<spv::Id> results;
6200
6201 // do each vector op
6202 for (int c = 0; c < numCols; ++c) {
6203 std::vector<unsigned int> indexes;
6204 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08006205 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
6206 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichb9197c82019-08-11 07:41:45 -06006207 decorations.addNoContraction(builder, destVec);
6208 decorations.addNonUniform(builder, destVec);
John Kessenichead86222018-03-28 18:01:20 -06006209 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07006210 }
6211
6212 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06006213 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006214 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006215 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07006216}
6217
John Kessenichad7645f2018-06-04 19:11:25 -06006218// For converting integers where both the bitwidth and the signedness could
6219// change, but only do the width change here. The caller is still responsible
6220// for the signedness conversion.
6221spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07006222{
John Kessenichad7645f2018-06-04 19:11:25 -06006223 // Get the result type width, based on the type to convert to.
6224 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006225 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06006226 case glslang::EOpConvInt16ToUint8:
6227 case glslang::EOpConvIntToUint8:
6228 case glslang::EOpConvInt64ToUint8:
6229 case glslang::EOpConvUint16ToInt8:
6230 case glslang::EOpConvUintToInt8:
6231 case glslang::EOpConvUint64ToInt8:
6232 width = 8;
6233 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006234 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06006235 case glslang::EOpConvIntToUint16:
6236 case glslang::EOpConvInt64ToUint16:
6237 case glslang::EOpConvUint8ToInt16:
6238 case glslang::EOpConvUintToInt16:
6239 case glslang::EOpConvUint64ToInt16:
6240 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07006241 break;
6242 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06006243 case glslang::EOpConvInt16ToUint:
6244 case glslang::EOpConvInt64ToUint:
6245 case glslang::EOpConvUint8ToInt:
6246 case glslang::EOpConvUint16ToInt:
6247 case glslang::EOpConvUint64ToInt:
6248 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07006249 break;
6250 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006251 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006252 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006253 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006254 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006255 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06006256 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07006257 break;
6258
6259 default:
6260 assert(false && "Default missing");
6261 break;
6262 }
6263
John Kessenichad7645f2018-06-04 19:11:25 -06006264 // Get the conversion operation and result type,
6265 // based on the target width, but the source type.
6266 spv::Id type = spv::NoType;
6267 spv::Op convOp = spv::OpNop;
6268 switch(op) {
6269 case glslang::EOpConvInt8ToUint16:
6270 case glslang::EOpConvInt8ToUint:
6271 case glslang::EOpConvInt8ToUint64:
6272 case glslang::EOpConvInt16ToUint8:
6273 case glslang::EOpConvInt16ToUint:
6274 case glslang::EOpConvInt16ToUint64:
6275 case glslang::EOpConvIntToUint8:
6276 case glslang::EOpConvIntToUint16:
6277 case glslang::EOpConvIntToUint64:
6278 case glslang::EOpConvInt64ToUint8:
6279 case glslang::EOpConvInt64ToUint16:
6280 case glslang::EOpConvInt64ToUint:
6281 convOp = spv::OpSConvert;
6282 type = builder.makeIntType(width);
6283 break;
6284 default:
6285 convOp = spv::OpUConvert;
6286 type = builder.makeUintType(width);
6287 break;
6288 }
6289
John Kessenich66011cb2018-03-06 16:12:04 -07006290 if (vectorSize > 0)
6291 type = builder.makeVectorType(type, vectorSize);
6292
John Kessenichad7645f2018-06-04 19:11:25 -06006293 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006294}
6295
John Kessenichead86222018-03-28 18:01:20 -06006296spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
6297 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06006298{
6299 spv::Op convOp = spv::OpNop;
6300 spv::Id zero = 0;
6301 spv::Id one = 0;
6302
6303 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
6304
6305 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07006306 case glslang::EOpConvIntToBool:
6307 case glslang::EOpConvUintToBool:
6308 zero = builder.makeUintConstant(0);
6309 zero = makeSmearedConstant(zero, vectorSize);
6310 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006311 case glslang::EOpConvFloatToBool:
6312 zero = builder.makeFloatConstant(0.0F);
6313 zero = makeSmearedConstant(zero, vectorSize);
6314 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
John Kessenich140f3df2015-06-26 16:58:36 -06006315 case glslang::EOpConvBoolToFloat:
6316 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006317 zero = builder.makeFloatConstant(0.0F);
6318 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06006319 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006320
John Kessenich140f3df2015-06-26 16:58:36 -06006321 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006322 case glslang::EOpConvBoolToInt64:
John Kessenichb9197c82019-08-11 07:41:45 -06006323#ifndef GLSLANG_WEB
6324 if (op == glslang::EOpConvBoolToInt64) {
Rex Xucabbb782017-03-24 13:41:14 +08006325 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006326 one = builder.makeInt64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006327 } else
6328#endif
6329 {
6330 zero = builder.makeIntConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006331 one = builder.makeIntConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006332 }
Rex Xucabbb782017-03-24 13:41:14 +08006333
John Kessenich140f3df2015-06-26 16:58:36 -06006334 convOp = spv::OpSelect;
6335 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006336
John Kessenich140f3df2015-06-26 16:58:36 -06006337 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006338 case glslang::EOpConvBoolToUint64:
John Kessenichb9197c82019-08-11 07:41:45 -06006339#ifndef GLSLANG_WEB
6340 if (op == glslang::EOpConvBoolToUint64) {
Rex Xucabbb782017-03-24 13:41:14 +08006341 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006342 one = builder.makeUint64Constant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006343 } else
6344#endif
6345 {
6346 zero = builder.makeUintConstant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006347 one = builder.makeUintConstant(1);
John Kessenichb9197c82019-08-11 07:41:45 -06006348 }
Rex Xucabbb782017-03-24 13:41:14 +08006349
John Kessenich140f3df2015-06-26 16:58:36 -06006350 convOp = spv::OpSelect;
6351 break;
6352
John Kessenich66011cb2018-03-06 16:12:04 -07006353 case glslang::EOpConvInt8ToFloat16:
6354 case glslang::EOpConvInt8ToFloat:
6355 case glslang::EOpConvInt8ToDouble:
6356 case glslang::EOpConvInt16ToFloat16:
6357 case glslang::EOpConvInt16ToFloat:
6358 case glslang::EOpConvInt16ToDouble:
6359 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006360 case glslang::EOpConvIntToFloat:
6361 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006362 case glslang::EOpConvInt64ToFloat:
6363 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006364 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006365 convOp = spv::OpConvertSToF;
6366 break;
6367
John Kessenich66011cb2018-03-06 16:12:04 -07006368 case glslang::EOpConvUint8ToFloat16:
6369 case glslang::EOpConvUint8ToFloat:
6370 case glslang::EOpConvUint8ToDouble:
6371 case glslang::EOpConvUint16ToFloat16:
6372 case glslang::EOpConvUint16ToFloat:
6373 case glslang::EOpConvUint16ToDouble:
6374 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006375 case glslang::EOpConvUintToFloat:
6376 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006377 case glslang::EOpConvUint64ToFloat:
6378 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006379 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006380 convOp = spv::OpConvertUToF;
6381 break;
6382
John Kessenich66011cb2018-03-06 16:12:04 -07006383 case glslang::EOpConvFloat16ToInt8:
6384 case glslang::EOpConvFloatToInt8:
6385 case glslang::EOpConvDoubleToInt8:
6386 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006387 case glslang::EOpConvFloatToInt16:
6388 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006389 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006390 case glslang::EOpConvFloatToInt:
6391 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006392 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006393 case glslang::EOpConvFloatToInt64:
6394 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006395 convOp = spv::OpConvertFToS;
6396 break;
6397
John Kessenich66011cb2018-03-06 16:12:04 -07006398 case glslang::EOpConvUint8ToInt8:
6399 case glslang::EOpConvInt8ToUint8:
6400 case glslang::EOpConvUint16ToInt16:
6401 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006402 case glslang::EOpConvUintToInt:
6403 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006404 case glslang::EOpConvUint64ToInt64:
6405 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006406 if (builder.isInSpecConstCodeGenMode()) {
6407 // Build zero scalar or vector for OpIAdd.
John Kessenich39697cd2019-08-08 10:35:51 -06006408#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07006409 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6410 zero = builder.makeUint8Constant(0);
6411 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006412 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006413 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6414 zero = builder.makeUint64Constant(0);
John Kessenich39697cd2019-08-08 10:35:51 -06006415 } else
6416#endif
6417 {
Rex Xucabbb782017-03-24 13:41:14 +08006418 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006419 }
qining189b2032016-04-12 23:16:20 -04006420 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006421 // Use OpIAdd, instead of OpBitcast to do the conversion when
6422 // generating for OpSpecConstantOp instruction.
6423 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6424 }
6425 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006426 convOp = spv::OpBitcast;
6427 break;
6428
John Kessenich66011cb2018-03-06 16:12:04 -07006429 case glslang::EOpConvFloat16ToUint8:
6430 case glslang::EOpConvFloatToUint8:
6431 case glslang::EOpConvDoubleToUint8:
6432 case glslang::EOpConvFloat16ToUint16:
6433 case glslang::EOpConvFloatToUint16:
6434 case glslang::EOpConvDoubleToUint16:
6435 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006436 case glslang::EOpConvFloatToUint:
6437 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006438 case glslang::EOpConvFloatToUint64:
6439 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006440 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006441 convOp = spv::OpConvertFToU;
6442 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006443
John Kessenich39697cd2019-08-08 10:35:51 -06006444#ifndef GLSLANG_WEB
6445 case glslang::EOpConvInt8ToBool:
6446 case glslang::EOpConvUint8ToBool:
6447 zero = builder.makeUint8Constant(0);
6448 zero = makeSmearedConstant(zero, vectorSize);
6449 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6450 case glslang::EOpConvInt16ToBool:
6451 case glslang::EOpConvUint16ToBool:
6452 zero = builder.makeUint16Constant(0);
6453 zero = makeSmearedConstant(zero, vectorSize);
6454 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6455 case glslang::EOpConvInt64ToBool:
6456 case glslang::EOpConvUint64ToBool:
6457 zero = builder.makeUint64Constant(0);
6458 zero = makeSmearedConstant(zero, vectorSize);
6459 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
6460 case glslang::EOpConvDoubleToBool:
6461 zero = builder.makeDoubleConstant(0.0);
6462 zero = makeSmearedConstant(zero, vectorSize);
6463 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6464 case glslang::EOpConvFloat16ToBool:
6465 zero = builder.makeFloat16Constant(0.0F);
6466 zero = makeSmearedConstant(zero, vectorSize);
6467 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
6468 case glslang::EOpConvBoolToDouble:
6469 convOp = spv::OpSelect;
6470 zero = builder.makeDoubleConstant(0.0);
6471 one = builder.makeDoubleConstant(1.0);
6472 break;
6473 case glslang::EOpConvBoolToFloat16:
6474 convOp = spv::OpSelect;
6475 zero = builder.makeFloat16Constant(0.0F);
6476 one = builder.makeFloat16Constant(1.0F);
6477 break;
6478 case glslang::EOpConvBoolToInt8:
6479 zero = builder.makeInt8Constant(0);
6480 one = builder.makeInt8Constant(1);
6481 convOp = spv::OpSelect;
6482 break;
6483 case glslang::EOpConvBoolToUint8:
6484 zero = builder.makeUint8Constant(0);
6485 one = builder.makeUint8Constant(1);
6486 convOp = spv::OpSelect;
6487 break;
6488 case glslang::EOpConvBoolToInt16:
6489 zero = builder.makeInt16Constant(0);
6490 one = builder.makeInt16Constant(1);
6491 convOp = spv::OpSelect;
6492 break;
6493 case glslang::EOpConvBoolToUint16:
6494 zero = builder.makeUint16Constant(0);
6495 one = builder.makeUint16Constant(1);
6496 convOp = spv::OpSelect;
6497 break;
6498 case glslang::EOpConvDoubleToFloat:
6499 case glslang::EOpConvFloatToDouble:
6500 case glslang::EOpConvDoubleToFloat16:
6501 case glslang::EOpConvFloat16ToDouble:
6502 case glslang::EOpConvFloatToFloat16:
6503 case glslang::EOpConvFloat16ToFloat:
6504 convOp = spv::OpFConvert;
6505 if (builder.isMatrixType(destType))
6506 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
6507 break;
6508
John Kessenich66011cb2018-03-06 16:12:04 -07006509 case glslang::EOpConvInt8ToInt16:
6510 case glslang::EOpConvInt8ToInt:
6511 case glslang::EOpConvInt8ToInt64:
6512 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006513 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006514 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006515 case glslang::EOpConvIntToInt8:
6516 case glslang::EOpConvIntToInt16:
6517 case glslang::EOpConvIntToInt64:
6518 case glslang::EOpConvInt64ToInt8:
6519 case glslang::EOpConvInt64ToInt16:
6520 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006521 convOp = spv::OpSConvert;
6522 break;
6523
John Kessenich66011cb2018-03-06 16:12:04 -07006524 case glslang::EOpConvUint8ToUint16:
6525 case glslang::EOpConvUint8ToUint:
6526 case glslang::EOpConvUint8ToUint64:
6527 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006528 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006529 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006530 case glslang::EOpConvUintToUint8:
6531 case glslang::EOpConvUintToUint16:
6532 case glslang::EOpConvUintToUint64:
6533 case glslang::EOpConvUint64ToUint8:
6534 case glslang::EOpConvUint64ToUint16:
6535 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006536 convOp = spv::OpUConvert;
6537 break;
6538
John Kessenich66011cb2018-03-06 16:12:04 -07006539 case glslang::EOpConvInt8ToUint16:
6540 case glslang::EOpConvInt8ToUint:
6541 case glslang::EOpConvInt8ToUint64:
6542 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006543 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006544 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006545 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006546 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006547 case glslang::EOpConvIntToUint64:
6548 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006549 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006550 case glslang::EOpConvInt64ToUint:
6551 case glslang::EOpConvUint8ToInt16:
6552 case glslang::EOpConvUint8ToInt:
6553 case glslang::EOpConvUint8ToInt64:
6554 case glslang::EOpConvUint16ToInt8:
6555 case glslang::EOpConvUint16ToInt:
6556 case glslang::EOpConvUint16ToInt64:
6557 case glslang::EOpConvUintToInt8:
6558 case glslang::EOpConvUintToInt16:
6559 case glslang::EOpConvUintToInt64:
6560 case glslang::EOpConvUint64ToInt8:
6561 case glslang::EOpConvUint64ToInt16:
6562 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006563 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006564 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006565
6566 if (builder.isInSpecConstCodeGenMode()) {
6567 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006568 switch(op) {
6569 case glslang::EOpConvInt16ToUint8:
6570 case glslang::EOpConvIntToUint8:
6571 case glslang::EOpConvInt64ToUint8:
6572 case glslang::EOpConvUint16ToInt8:
6573 case glslang::EOpConvUintToInt8:
6574 case glslang::EOpConvUint64ToInt8:
6575 zero = builder.makeUint8Constant(0);
6576 break;
6577 case glslang::EOpConvInt8ToUint16:
6578 case glslang::EOpConvIntToUint16:
6579 case glslang::EOpConvInt64ToUint16:
6580 case glslang::EOpConvUint8ToInt16:
6581 case glslang::EOpConvUintToInt16:
6582 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006583 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006584 break;
6585 case glslang::EOpConvInt8ToUint:
6586 case glslang::EOpConvInt16ToUint:
6587 case glslang::EOpConvInt64ToUint:
6588 case glslang::EOpConvUint8ToInt:
6589 case glslang::EOpConvUint16ToInt:
6590 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006591 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006592 break;
6593 case glslang::EOpConvInt8ToUint64:
6594 case glslang::EOpConvInt16ToUint64:
6595 case glslang::EOpConvIntToUint64:
6596 case glslang::EOpConvUint8ToInt64:
6597 case glslang::EOpConvUint16ToInt64:
6598 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006599 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006600 break;
6601 default:
6602 assert(false && "Default missing");
6603 break;
6604 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006605 zero = makeSmearedConstant(zero, vectorSize);
6606 // Use OpIAdd, instead of OpBitcast to do the conversion when
6607 // generating for OpSpecConstantOp instruction.
6608 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6609 }
6610 // For normal run-time conversion instruction, use OpBitcast.
6611 convOp = spv::OpBitcast;
6612 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006613 case glslang::EOpConvUint64ToPtr:
6614 convOp = spv::OpConvertUToPtr;
6615 break;
6616 case glslang::EOpConvPtrToUint64:
6617 convOp = spv::OpConvertPtrToU;
6618 break;
John Kessenich90e402f2019-09-17 23:19:38 -06006619 case glslang::EOpConvPtrToUvec2:
6620 case glslang::EOpConvUvec2ToPtr:
John Kessenichee8e9c12019-10-10 20:54:21 -06006621 if (builder.isVector(operand))
6622 builder.promoteIncorporatedExtension(spv::E_SPV_EXT_physical_storage_buffer,
6623 spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
John Kessenich90e402f2019-09-17 23:19:38 -06006624 convOp = spv::OpBitcast;
6625 break;
John Kessenich39697cd2019-08-08 10:35:51 -06006626#endif
6627
John Kessenich140f3df2015-06-26 16:58:36 -06006628 default:
6629 break;
6630 }
6631
6632 spv::Id result = 0;
6633 if (convOp == spv::OpNop)
6634 return result;
6635
6636 if (convOp == spv::OpSelect) {
6637 zero = makeSmearedConstant(zero, vectorSize);
6638 one = makeSmearedConstant(one, vectorSize);
6639 result = builder.createTriOp(convOp, destType, operand, one, zero);
6640 } else
6641 result = builder.createUnaryOp(convOp, destType, operand);
6642
John Kessenichead86222018-03-28 18:01:20 -06006643 result = builder.setPrecision(result, decorations.precision);
John Kessenichb9197c82019-08-11 07:41:45 -06006644 decorations.addNonUniform(builder, result);
John Kessenichead86222018-03-28 18:01:20 -06006645 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006646}
6647
6648spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6649{
6650 if (vectorSize == 0)
6651 return constant;
6652
6653 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6654 std::vector<spv::Id> components;
6655 for (int c = 0; c < vectorSize; ++c)
6656 components.push_back(constant);
6657 return builder.makeCompositeConstant(vectorTypeId, components);
6658}
6659
John Kessenich426394d2015-07-23 10:22:48 -06006660// For glslang ops that map to SPV atomic opCodes
John Kessenich8985fc92020-03-03 10:25:07 -07006661spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
6662 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
6663 const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich426394d2015-07-23 10:22:48 -06006664{
6665 spv::Op opCode = spv::OpNop;
6666
6667 switch (op) {
6668 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006669 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006670 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006671 opCode = spv::OpAtomicIAdd;
6672 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006673 case glslang::EOpAtomicCounterSubtract:
6674 opCode = spv::OpAtomicISub;
6675 break;
John Kessenich426394d2015-07-23 10:22:48 -06006676 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006677 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006678 case glslang::EOpAtomicCounterMin:
John Kessenich8985fc92020-03-03 10:25:07 -07006679 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6680 spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006681 break;
6682 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006683 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006684 case glslang::EOpAtomicCounterMax:
John Kessenich8985fc92020-03-03 10:25:07 -07006685 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ?
6686 spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006687 break;
6688 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006689 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006690 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006691 opCode = spv::OpAtomicAnd;
6692 break;
6693 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006694 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006695 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006696 opCode = spv::OpAtomicOr;
6697 break;
6698 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006699 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006700 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006701 opCode = spv::OpAtomicXor;
6702 break;
6703 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006704 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006705 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006706 opCode = spv::OpAtomicExchange;
6707 break;
6708 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006709 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006710 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006711 opCode = spv::OpAtomicCompareExchange;
6712 break;
6713 case glslang::EOpAtomicCounterIncrement:
6714 opCode = spv::OpAtomicIIncrement;
6715 break;
6716 case glslang::EOpAtomicCounterDecrement:
6717 opCode = spv::OpAtomicIDecrement;
6718 break;
6719 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006720 case glslang::EOpImageAtomicLoad:
6721 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006722 opCode = spv::OpAtomicLoad;
6723 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006724 case glslang::EOpAtomicStore:
6725 case glslang::EOpImageAtomicStore:
6726 opCode = spv::OpAtomicStore;
6727 break;
John Kessenich426394d2015-07-23 10:22:48 -06006728 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006729 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006730 break;
6731 }
6732
Rex Xue8fe8b02017-09-26 15:42:56 +08006733 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6734 builder.addCapability(spv::CapabilityInt64Atomics);
6735
John Kessenich426394d2015-07-23 10:22:48 -06006736 // Sort out the operands
6737 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006738 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006739 // - compare-exchange swaps the value and comparator
6740 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006741 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006742 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6743 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6744 spv::Id scopeId;
6745 if (glslangIntermediate->usingVulkanMemoryModel()) {
6746 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6747 } else {
6748 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6749 }
6750 // semantics default to relaxed
John Kessenich8985fc92020-03-03 10:25:07 -07006751 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
6752 glslangIntermediate->usingVulkanMemoryModel() ?
John Kessenichb9197c82019-08-11 07:41:45 -06006753 spv::MemorySemanticsVolatileMask :
6754 spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006755 spv::Id semanticsId2 = semanticsId;
6756
6757 pointerId = operands[0];
6758 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6759 // no additional operands
6760 } else if (opCode == spv::OpAtomicCompareExchange) {
6761 compareId = operands[1];
6762 valueId = operands[2];
6763 if (operands.size() > 3) {
6764 scopeId = operands[3];
John Kessenich8985fc92020-03-03 10:25:07 -07006765 semanticsId = builder.makeUintConstant(
6766 builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6767 semanticsId2 = builder.makeUintConstant(
6768 builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006769 }
6770 } else if (opCode == spv::OpAtomicLoad) {
6771 if (operands.size() > 1) {
6772 scopeId = operands[1];
John Kessenich8985fc92020-03-03 10:25:07 -07006773 semanticsId = builder.makeUintConstant(
6774 builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006775 }
6776 } else {
6777 // atomic store or RMW
6778 valueId = operands[1];
6779 if (operands.size() > 2) {
6780 scopeId = operands[2];
John Kessenich8985fc92020-03-03 10:25:07 -07006781 semanticsId = builder.makeUintConstant
6782 (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
Jeff Bolz36831c92018-09-05 10:11:41 -05006783 }
Rex Xu04db3f52015-09-16 11:44:02 +08006784 }
John Kessenich426394d2015-07-23 10:22:48 -06006785
Jeff Bolz36831c92018-09-05 10:11:41 -05006786 // Check for capabilities
6787 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006788 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6789 spv::MemorySemanticsMakeVisibleKHRMask |
6790 spv::MemorySemanticsOutputMemoryKHRMask |
6791 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006792 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6793 }
John Kessenich426394d2015-07-23 10:22:48 -06006794
Jeff Bolz36831c92018-09-05 10:11:41 -05006795 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6796 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6797 }
John Kessenich48d6e792017-10-06 21:21:48 -06006798
Jeff Bolz36831c92018-09-05 10:11:41 -05006799 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6800 spvAtomicOperands.push_back(pointerId);
6801 spvAtomicOperands.push_back(scopeId);
6802 spvAtomicOperands.push_back(semanticsId);
6803 if (opCode == spv::OpAtomicCompareExchange) {
6804 spvAtomicOperands.push_back(semanticsId2);
6805 spvAtomicOperands.push_back(valueId);
6806 spvAtomicOperands.push_back(compareId);
6807 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6808 spvAtomicOperands.push_back(valueId);
6809 }
John Kessenich48d6e792017-10-06 21:21:48 -06006810
Jeff Bolz36831c92018-09-05 10:11:41 -05006811 if (opCode == spv::OpAtomicStore) {
6812 builder.createNoResultOp(opCode, spvAtomicOperands);
6813 return 0;
6814 } else {
6815 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6816
6817 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6818 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6819 if (op == glslang::EOpAtomicCounterDecrement)
6820 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6821
6822 return resultId;
6823 }
John Kessenich426394d2015-07-23 10:22:48 -06006824}
6825
John Kessenich91cef522016-05-05 16:45:40 -06006826// Create group invocation operations.
John Kessenich8985fc92020-03-03 10:25:07 -07006827spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
6828 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006829{
John Kessenich66011cb2018-03-06 16:12:04 -07006830 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6831 bool isFloat = isTypeFloat(typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +08006832
Rex Xu51596642016-09-21 18:56:12 +08006833 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006834 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006835 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6836
chaocf200da82016-12-20 12:44:35 -08006837 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6838 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006839 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6840 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006841 } else if (op == glslang::EOpAnyInvocation ||
6842 op == glslang::EOpAllInvocations ||
6843 op == glslang::EOpAllInvocationsEqual) {
6844 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6845 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006846 } else {
6847 builder.addCapability(spv::CapabilityGroups);
Rex Xu17ff3432016-10-14 17:41:45 +08006848 if (op == glslang::EOpMinInvocationsNonUniform ||
6849 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006850 op == glslang::EOpAddInvocationsNonUniform ||
6851 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6852 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6853 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6854 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6855 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6856 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006857 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +08006858
Rex Xu430ef402016-10-14 17:22:23 +08006859 switch (op) {
6860 case glslang::EOpMinInvocations:
6861 case glslang::EOpMaxInvocations:
6862 case glslang::EOpAddInvocations:
6863 case glslang::EOpMinInvocationsNonUniform:
6864 case glslang::EOpMaxInvocationsNonUniform:
6865 case glslang::EOpAddInvocationsNonUniform:
6866 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006867 break;
6868 case glslang::EOpMinInvocationsInclusiveScan:
6869 case glslang::EOpMaxInvocationsInclusiveScan:
6870 case glslang::EOpAddInvocationsInclusiveScan:
6871 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6872 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6873 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6874 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006875 break;
6876 case glslang::EOpMinInvocationsExclusiveScan:
6877 case glslang::EOpMaxInvocationsExclusiveScan:
6878 case glslang::EOpAddInvocationsExclusiveScan:
6879 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6880 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6881 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6882 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006883 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006884 default:
6885 break;
Rex Xu430ef402016-10-14 17:22:23 +08006886 }
John Kessenich149afc32018-08-14 13:31:43 -06006887 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6888 spvGroupOperands.push_back(scope);
6889 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006890 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006891 spvGroupOperands.push_back(groupOp);
6892 }
Rex Xu51596642016-09-21 18:56:12 +08006893 }
6894
John Kessenich149afc32018-08-14 13:31:43 -06006895 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6896 spv::IdImmediate op = { true, *opIt };
6897 spvGroupOperands.push_back(op);
6898 }
John Kessenich91cef522016-05-05 16:45:40 -06006899
6900 switch (op) {
6901 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006902 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006903 break;
John Kessenich91cef522016-05-05 16:45:40 -06006904 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006905 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006906 break;
John Kessenich91cef522016-05-05 16:45:40 -06006907 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006908 opCode = spv::OpSubgroupAllEqualKHR;
6909 break;
Rex Xu51596642016-09-21 18:56:12 +08006910 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006911 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006912 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006913 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006914 break;
6915 case glslang::EOpReadFirstInvocation:
6916 opCode = spv::OpSubgroupFirstInvocationKHR;
6917 break;
6918 case glslang::EOpBallot:
6919 {
6920 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6921 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6922 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6923 //
6924 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6925 //
6926 spv::Id uintType = builder.makeUintType(32);
6927 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6928 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6929
6930 std::vector<spv::Id> components;
6931 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6932 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6933
6934 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6935 return builder.createUnaryOp(spv::OpBitcast, typeId,
6936 builder.createCompositeConstruct(uvec2Type, components));
6937 }
6938
Rex Xu9d93a232016-05-05 12:30:44 +08006939 case glslang::EOpMinInvocations:
6940 case glslang::EOpMaxInvocations:
6941 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006942 case glslang::EOpMinInvocationsInclusiveScan:
6943 case glslang::EOpMaxInvocationsInclusiveScan:
6944 case glslang::EOpAddInvocationsInclusiveScan:
6945 case glslang::EOpMinInvocationsExclusiveScan:
6946 case glslang::EOpMaxInvocationsExclusiveScan:
6947 case glslang::EOpAddInvocationsExclusiveScan:
6948 if (op == glslang::EOpMinInvocations ||
6949 op == glslang::EOpMinInvocationsInclusiveScan ||
6950 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006951 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006952 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006953 else {
6954 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006955 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006956 else
Rex Xu51596642016-09-21 18:56:12 +08006957 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006958 }
Rex Xu430ef402016-10-14 17:22:23 +08006959 } else if (op == glslang::EOpMaxInvocations ||
6960 op == glslang::EOpMaxInvocationsInclusiveScan ||
6961 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006962 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006963 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006964 else {
6965 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006966 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006967 else
Rex Xu51596642016-09-21 18:56:12 +08006968 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006969 }
6970 } else {
6971 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006972 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006973 else
Rex Xu51596642016-09-21 18:56:12 +08006974 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006975 }
6976
Rex Xu2bbbe062016-08-23 15:41:05 +08006977 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006978 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006979
6980 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006981 case glslang::EOpMinInvocationsNonUniform:
6982 case glslang::EOpMaxInvocationsNonUniform:
6983 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006984 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6985 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6986 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6987 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6988 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6989 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6990 if (op == glslang::EOpMinInvocationsNonUniform ||
6991 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6992 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006993 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006994 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006995 else {
6996 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006997 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006998 else
Rex Xu51596642016-09-21 18:56:12 +08006999 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007000 }
7001 }
Rex Xu430ef402016-10-14 17:22:23 +08007002 else if (op == glslang::EOpMaxInvocationsNonUniform ||
7003 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
7004 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08007005 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007006 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007007 else {
7008 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08007009 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007010 else
Rex Xu51596642016-09-21 18:56:12 +08007011 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007012 }
7013 }
7014 else {
7015 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08007016 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007017 else
Rex Xu51596642016-09-21 18:56:12 +08007018 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08007019 }
7020
Rex Xu2bbbe062016-08-23 15:41:05 +08007021 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08007022 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08007023
7024 break;
John Kessenich91cef522016-05-05 16:45:40 -06007025 default:
7026 logger->missingFunctionality("invocation operation");
7027 return spv::NoResult;
7028 }
Rex Xu51596642016-09-21 18:56:12 +08007029
7030 assert(opCode != spv::OpNop);
7031 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06007032}
7033
Rex Xu2bbbe062016-08-23 15:41:05 +08007034// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06007035spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
7036 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08007037{
7038 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
7039 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08007040 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08007041 op == spv::OpSubgroupReadInvocationKHR ||
John Kessenich8985fc92020-03-03 10:25:07 -07007042 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
7043 op == spv::OpGroupSMinNonUniformAMD ||
7044 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
7045 op == spv::OpGroupSMaxNonUniformAMD ||
Rex Xu2bbbe062016-08-23 15:41:05 +08007046 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
7047
7048 // Handle group invocation operations scalar by scalar.
7049 // The result type is the same type as the original type.
7050 // The algorithm is to:
7051 // - break the vector into scalars
7052 // - apply the operation to each scalar
7053 // - make a vector out the scalar results
7054
7055 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08007056 int numComponents = builder.getNumComponents(operands[0]);
7057 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08007058 std::vector<spv::Id> results;
7059
7060 // do each scalar op
7061 for (int comp = 0; comp < numComponents; ++comp) {
7062 std::vector<unsigned int> indexes;
7063 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06007064 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
7065 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08007066 if (op == spv::OpSubgroupReadInvocationKHR) {
7067 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007068 spv::IdImmediate operand = { true, operands[1] };
7069 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08007070 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06007071 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7072 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08007073 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06007074 spv::IdImmediate operand = { true, operands[1] };
7075 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08007076 } else {
John Kessenich149afc32018-08-14 13:31:43 -06007077 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7078 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06007079 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007080 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08007081 spvGroupOperands.push_back(scalar);
7082 }
Rex Xu2bbbe062016-08-23 15:41:05 +08007083
Rex Xub7072052016-09-26 15:53:40 +08007084 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08007085 }
7086
7087 // put the pieces together
7088 return builder.createCompositeConstruct(typeId, results);
7089}
Rex Xu2bbbe062016-08-23 15:41:05 +08007090
John Kessenich66011cb2018-03-06 16:12:04 -07007091// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06007092spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
7093 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07007094{
7095 // Add the required capabilities.
7096 switch (op) {
7097 case glslang::EOpSubgroupElect:
7098 builder.addCapability(spv::CapabilityGroupNonUniform);
7099 break;
7100 case glslang::EOpSubgroupAll:
7101 case glslang::EOpSubgroupAny:
7102 case glslang::EOpSubgroupAllEqual:
7103 builder.addCapability(spv::CapabilityGroupNonUniform);
7104 builder.addCapability(spv::CapabilityGroupNonUniformVote);
7105 break;
7106 case glslang::EOpSubgroupBroadcast:
7107 case glslang::EOpSubgroupBroadcastFirst:
7108 case glslang::EOpSubgroupBallot:
7109 case glslang::EOpSubgroupInverseBallot:
7110 case glslang::EOpSubgroupBallotBitExtract:
7111 case glslang::EOpSubgroupBallotBitCount:
7112 case glslang::EOpSubgroupBallotInclusiveBitCount:
7113 case glslang::EOpSubgroupBallotExclusiveBitCount:
7114 case glslang::EOpSubgroupBallotFindLSB:
7115 case glslang::EOpSubgroupBallotFindMSB:
7116 builder.addCapability(spv::CapabilityGroupNonUniform);
7117 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
7118 break;
7119 case glslang::EOpSubgroupShuffle:
7120 case glslang::EOpSubgroupShuffleXor:
7121 builder.addCapability(spv::CapabilityGroupNonUniform);
7122 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
7123 break;
7124 case glslang::EOpSubgroupShuffleUp:
7125 case glslang::EOpSubgroupShuffleDown:
7126 builder.addCapability(spv::CapabilityGroupNonUniform);
7127 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
7128 break;
7129 case glslang::EOpSubgroupAdd:
7130 case glslang::EOpSubgroupMul:
7131 case glslang::EOpSubgroupMin:
7132 case glslang::EOpSubgroupMax:
7133 case glslang::EOpSubgroupAnd:
7134 case glslang::EOpSubgroupOr:
7135 case glslang::EOpSubgroupXor:
7136 case glslang::EOpSubgroupInclusiveAdd:
7137 case glslang::EOpSubgroupInclusiveMul:
7138 case glslang::EOpSubgroupInclusiveMin:
7139 case glslang::EOpSubgroupInclusiveMax:
7140 case glslang::EOpSubgroupInclusiveAnd:
7141 case glslang::EOpSubgroupInclusiveOr:
7142 case glslang::EOpSubgroupInclusiveXor:
7143 case glslang::EOpSubgroupExclusiveAdd:
7144 case glslang::EOpSubgroupExclusiveMul:
7145 case glslang::EOpSubgroupExclusiveMin:
7146 case glslang::EOpSubgroupExclusiveMax:
7147 case glslang::EOpSubgroupExclusiveAnd:
7148 case glslang::EOpSubgroupExclusiveOr:
7149 case glslang::EOpSubgroupExclusiveXor:
7150 builder.addCapability(spv::CapabilityGroupNonUniform);
7151 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
7152 break;
7153 case glslang::EOpSubgroupClusteredAdd:
7154 case glslang::EOpSubgroupClusteredMul:
7155 case glslang::EOpSubgroupClusteredMin:
7156 case glslang::EOpSubgroupClusteredMax:
7157 case glslang::EOpSubgroupClusteredAnd:
7158 case glslang::EOpSubgroupClusteredOr:
7159 case glslang::EOpSubgroupClusteredXor:
7160 builder.addCapability(spv::CapabilityGroupNonUniform);
7161 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
7162 break;
7163 case glslang::EOpSubgroupQuadBroadcast:
7164 case glslang::EOpSubgroupQuadSwapHorizontal:
7165 case glslang::EOpSubgroupQuadSwapVertical:
7166 case glslang::EOpSubgroupQuadSwapDiagonal:
7167 builder.addCapability(spv::CapabilityGroupNonUniform);
7168 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
7169 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007170 case glslang::EOpSubgroupPartitionedAdd:
7171 case glslang::EOpSubgroupPartitionedMul:
7172 case glslang::EOpSubgroupPartitionedMin:
7173 case glslang::EOpSubgroupPartitionedMax:
7174 case glslang::EOpSubgroupPartitionedAnd:
7175 case glslang::EOpSubgroupPartitionedOr:
7176 case glslang::EOpSubgroupPartitionedXor:
7177 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7178 case glslang::EOpSubgroupPartitionedInclusiveMul:
7179 case glslang::EOpSubgroupPartitionedInclusiveMin:
7180 case glslang::EOpSubgroupPartitionedInclusiveMax:
7181 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7182 case glslang::EOpSubgroupPartitionedInclusiveOr:
7183 case glslang::EOpSubgroupPartitionedInclusiveXor:
7184 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7185 case glslang::EOpSubgroupPartitionedExclusiveMul:
7186 case glslang::EOpSubgroupPartitionedExclusiveMin:
7187 case glslang::EOpSubgroupPartitionedExclusiveMax:
7188 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7189 case glslang::EOpSubgroupPartitionedExclusiveOr:
7190 case glslang::EOpSubgroupPartitionedExclusiveXor:
7191 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
7192 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
7193 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007194 default: assert(0 && "Unhandled subgroup operation!");
7195 }
7196
Jeff Bolzc5b669e2019-09-08 08:49:18 -05007197
7198 const bool isUnsigned = isTypeUnsignedInt(typeProxy);
7199 const bool isFloat = isTypeFloat(typeProxy);
John Kessenich66011cb2018-03-06 16:12:04 -07007200 const bool isBool = typeProxy == glslang::EbtBool;
7201
7202 spv::Op opCode = spv::OpNop;
7203
7204 // Figure out which opcode to use.
7205 switch (op) {
7206 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
7207 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
7208 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
7209 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
7210 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
7211 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
7212 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
7213 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
7214 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
7215 case glslang::EOpSubgroupBallotBitCount:
7216 case glslang::EOpSubgroupBallotInclusiveBitCount:
7217 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
7218 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
7219 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
7220 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
7221 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
7222 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
7223 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
7224 case glslang::EOpSubgroupAdd:
7225 case glslang::EOpSubgroupInclusiveAdd:
7226 case glslang::EOpSubgroupExclusiveAdd:
7227 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007228 case glslang::EOpSubgroupPartitionedAdd:
7229 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7230 case glslang::EOpSubgroupPartitionedExclusiveAdd:
John Kessenich66011cb2018-03-06 16:12:04 -07007231 if (isFloat) {
7232 opCode = spv::OpGroupNonUniformFAdd;
7233 } else {
7234 opCode = spv::OpGroupNonUniformIAdd;
7235 }
7236 break;
7237 case glslang::EOpSubgroupMul:
7238 case glslang::EOpSubgroupInclusiveMul:
7239 case glslang::EOpSubgroupExclusiveMul:
7240 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007241 case glslang::EOpSubgroupPartitionedMul:
7242 case glslang::EOpSubgroupPartitionedInclusiveMul:
7243 case glslang::EOpSubgroupPartitionedExclusiveMul:
John Kessenich66011cb2018-03-06 16:12:04 -07007244 if (isFloat) {
7245 opCode = spv::OpGroupNonUniformFMul;
7246 } else {
7247 opCode = spv::OpGroupNonUniformIMul;
7248 }
7249 break;
7250 case glslang::EOpSubgroupMin:
7251 case glslang::EOpSubgroupInclusiveMin:
7252 case glslang::EOpSubgroupExclusiveMin:
7253 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007254 case glslang::EOpSubgroupPartitionedMin:
7255 case glslang::EOpSubgroupPartitionedInclusiveMin:
7256 case glslang::EOpSubgroupPartitionedExclusiveMin:
John Kessenich66011cb2018-03-06 16:12:04 -07007257 if (isFloat) {
7258 opCode = spv::OpGroupNonUniformFMin;
7259 } else if (isUnsigned) {
7260 opCode = spv::OpGroupNonUniformUMin;
7261 } else {
7262 opCode = spv::OpGroupNonUniformSMin;
7263 }
7264 break;
7265 case glslang::EOpSubgroupMax:
7266 case glslang::EOpSubgroupInclusiveMax:
7267 case glslang::EOpSubgroupExclusiveMax:
7268 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007269 case glslang::EOpSubgroupPartitionedMax:
7270 case glslang::EOpSubgroupPartitionedInclusiveMax:
7271 case glslang::EOpSubgroupPartitionedExclusiveMax:
John Kessenich66011cb2018-03-06 16:12:04 -07007272 if (isFloat) {
7273 opCode = spv::OpGroupNonUniformFMax;
7274 } else if (isUnsigned) {
7275 opCode = spv::OpGroupNonUniformUMax;
7276 } else {
7277 opCode = spv::OpGroupNonUniformSMax;
7278 }
7279 break;
7280 case glslang::EOpSubgroupAnd:
7281 case glslang::EOpSubgroupInclusiveAnd:
7282 case glslang::EOpSubgroupExclusiveAnd:
7283 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007284 case glslang::EOpSubgroupPartitionedAnd:
7285 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7286 case glslang::EOpSubgroupPartitionedExclusiveAnd:
John Kessenich66011cb2018-03-06 16:12:04 -07007287 if (isBool) {
7288 opCode = spv::OpGroupNonUniformLogicalAnd;
7289 } else {
7290 opCode = spv::OpGroupNonUniformBitwiseAnd;
7291 }
7292 break;
7293 case glslang::EOpSubgroupOr:
7294 case glslang::EOpSubgroupInclusiveOr:
7295 case glslang::EOpSubgroupExclusiveOr:
7296 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007297 case glslang::EOpSubgroupPartitionedOr:
7298 case glslang::EOpSubgroupPartitionedInclusiveOr:
7299 case glslang::EOpSubgroupPartitionedExclusiveOr:
John Kessenich66011cb2018-03-06 16:12:04 -07007300 if (isBool) {
7301 opCode = spv::OpGroupNonUniformLogicalOr;
7302 } else {
7303 opCode = spv::OpGroupNonUniformBitwiseOr;
7304 }
7305 break;
7306 case glslang::EOpSubgroupXor:
7307 case glslang::EOpSubgroupInclusiveXor:
7308 case glslang::EOpSubgroupExclusiveXor:
7309 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007310 case glslang::EOpSubgroupPartitionedXor:
7311 case glslang::EOpSubgroupPartitionedInclusiveXor:
7312 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007313 if (isBool) {
7314 opCode = spv::OpGroupNonUniformLogicalXor;
7315 } else {
7316 opCode = spv::OpGroupNonUniformBitwiseXor;
7317 }
7318 break;
7319 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
7320 case glslang::EOpSubgroupQuadSwapHorizontal:
7321 case glslang::EOpSubgroupQuadSwapVertical:
7322 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
7323 default: assert(0 && "Unhandled subgroup operation!");
7324 }
7325
John Kessenich149afc32018-08-14 13:31:43 -06007326 // get the right Group Operation
7327 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07007328 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06007329 default:
7330 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007331 case glslang::EOpSubgroupBallotBitCount:
7332 case glslang::EOpSubgroupAdd:
7333 case glslang::EOpSubgroupMul:
7334 case glslang::EOpSubgroupMin:
7335 case glslang::EOpSubgroupMax:
7336 case glslang::EOpSubgroupAnd:
7337 case glslang::EOpSubgroupOr:
7338 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06007339 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007340 break;
7341 case glslang::EOpSubgroupBallotInclusiveBitCount:
7342 case glslang::EOpSubgroupInclusiveAdd:
7343 case glslang::EOpSubgroupInclusiveMul:
7344 case glslang::EOpSubgroupInclusiveMin:
7345 case glslang::EOpSubgroupInclusiveMax:
7346 case glslang::EOpSubgroupInclusiveAnd:
7347 case glslang::EOpSubgroupInclusiveOr:
7348 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007349 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007350 break;
7351 case glslang::EOpSubgroupBallotExclusiveBitCount:
7352 case glslang::EOpSubgroupExclusiveAdd:
7353 case glslang::EOpSubgroupExclusiveMul:
7354 case glslang::EOpSubgroupExclusiveMin:
7355 case glslang::EOpSubgroupExclusiveMax:
7356 case glslang::EOpSubgroupExclusiveAnd:
7357 case glslang::EOpSubgroupExclusiveOr:
7358 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007359 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007360 break;
7361 case glslang::EOpSubgroupClusteredAdd:
7362 case glslang::EOpSubgroupClusteredMul:
7363 case glslang::EOpSubgroupClusteredMin:
7364 case glslang::EOpSubgroupClusteredMax:
7365 case glslang::EOpSubgroupClusteredAnd:
7366 case glslang::EOpSubgroupClusteredOr:
7367 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007368 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007369 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007370 case glslang::EOpSubgroupPartitionedAdd:
7371 case glslang::EOpSubgroupPartitionedMul:
7372 case glslang::EOpSubgroupPartitionedMin:
7373 case glslang::EOpSubgroupPartitionedMax:
7374 case glslang::EOpSubgroupPartitionedAnd:
7375 case glslang::EOpSubgroupPartitionedOr:
7376 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007377 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007378 break;
7379 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7380 case glslang::EOpSubgroupPartitionedInclusiveMul:
7381 case glslang::EOpSubgroupPartitionedInclusiveMin:
7382 case glslang::EOpSubgroupPartitionedInclusiveMax:
7383 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7384 case glslang::EOpSubgroupPartitionedInclusiveOr:
7385 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007386 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007387 break;
7388 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7389 case glslang::EOpSubgroupPartitionedExclusiveMul:
7390 case glslang::EOpSubgroupPartitionedExclusiveMin:
7391 case glslang::EOpSubgroupPartitionedExclusiveMax:
7392 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7393 case glslang::EOpSubgroupPartitionedExclusiveOr:
7394 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007395 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007396 break;
John Kessenich66011cb2018-03-06 16:12:04 -07007397 }
7398
John Kessenich149afc32018-08-14 13:31:43 -06007399 // build the instruction
7400 std::vector<spv::IdImmediate> spvGroupOperands;
7401
7402 // Every operation begins with the Execution Scope operand.
7403 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7404 spvGroupOperands.push_back(executionScope);
7405
7406 // Next, for all operations that use a Group Operation, push that as an operand.
7407 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007408 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007409 spvGroupOperands.push_back(groupOperand);
7410 }
7411
John Kessenich66011cb2018-03-06 16:12:04 -07007412 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007413 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7414 spv::IdImmediate operand = { true, *opIt };
7415 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007416 }
7417
7418 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007419 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007420 switch (op) {
7421 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007422 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7423 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7424 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7425 }
7426 if (directionId != spv::NoResult) {
7427 spv::IdImmediate direction = { true, directionId };
7428 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007429 }
7430
7431 return builder.createOp(opCode, typeId, spvGroupOperands);
7432}
7433
John Kessenich8985fc92020-03-03 10:25:07 -07007434spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
7435 spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06007436{
John Kessenich66011cb2018-03-06 16:12:04 -07007437 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7438 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007439
John Kessenich140f3df2015-06-26 16:58:36 -06007440 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007441 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007442 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007443 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007444 spv::Id typeId0 = 0;
7445 if (consumedOperands > 0)
7446 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007447 spv::Id typeId1 = 0;
7448 if (consumedOperands > 1)
7449 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007450 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007451
7452 switch (op) {
7453 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007454 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007455 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007456 else if (isUnsigned)
7457 libCall = spv::GLSLstd450UMin;
7458 else
7459 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007460 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007461 break;
7462 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007463 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007464 break;
7465 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007466 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007467 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007468 else if (isUnsigned)
7469 libCall = spv::GLSLstd450UMax;
7470 else
7471 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007472 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007473 break;
7474 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007475 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007476 break;
7477 case glslang::EOpDot:
7478 opCode = spv::OpDot;
7479 break;
7480 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007481 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007482 break;
7483
7484 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007485 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007486 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007487 else if (isUnsigned)
7488 libCall = spv::GLSLstd450UClamp;
7489 else
7490 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007491 builder.promoteScalar(precision, operands.front(), operands[1]);
7492 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007493 break;
7494 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007495 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7496 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007497 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007498 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007499 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007500 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007501 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007502 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007503 break;
7504 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007505 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007506 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007507 break;
7508 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007509 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007510 builder.promoteScalar(precision, operands[0], operands[2]);
7511 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007512 break;
7513
7514 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007515 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007516 break;
7517 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007518 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007519 break;
7520 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007521 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007522 break;
7523 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007524 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007525 break;
7526 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007527 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007528 break;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007529 case glslang::EOpBarrier:
7530 {
7531 // This is for the extended controlBarrier function, with four operands.
7532 // The unextended barrier() goes through createNoArgOperation.
7533 assert(operands.size() == 4);
7534 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7535 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7536 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
John Kessenich8985fc92020-03-03 10:25:07 -07007537 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
7538 (spv::MemorySemanticsMask)semantics);
John Kessenich3dd1ce52019-10-17 07:08:40 -06007539 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7540 spv::MemorySemanticsMakeVisibleKHRMask |
7541 spv::MemorySemanticsOutputMemoryKHRMask |
7542 spv::MemorySemanticsVolatileMask)) {
7543 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7544 }
John Kessenich8985fc92020-03-03 10:25:07 -07007545 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
7546 memoryScope == spv::ScopeDevice)) {
John Kessenich3dd1ce52019-10-17 07:08:40 -06007547 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7548 }
7549 return 0;
7550 }
7551 break;
7552 case glslang::EOpMemoryBarrier:
7553 {
7554 // This is for the extended memoryBarrier function, with three operands.
7555 // The unextended memoryBarrier() goes through createNoArgOperation.
7556 assert(operands.size() == 3);
7557 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7558 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7559 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7560 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7561 spv::MemorySemanticsMakeVisibleKHRMask |
7562 spv::MemorySemanticsOutputMemoryKHRMask |
7563 spv::MemorySemanticsVolatileMask)) {
7564 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7565 }
7566 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7567 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7568 }
7569 return 0;
7570 }
7571 break;
7572
John Kessenicha28f7a72019-08-06 07:00:58 -06007573#ifndef GLSLANG_WEB
Rex Xu7a26c172015-12-08 17:12:09 +08007574 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007575 if (typeProxy == glslang::EbtFloat16)
7576 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007577 libCall = spv::GLSLstd450InterpolateAtSample;
7578 break;
7579 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007580 if (typeProxy == glslang::EbtFloat16)
7581 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu7a26c172015-12-08 17:12:09 +08007582 libCall = spv::GLSLstd450InterpolateAtOffset;
7583 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007584 case glslang::EOpAddCarry:
7585 opCode = spv::OpIAddCarry;
7586 typeId = builder.makeStructResultType(typeId0, typeId0);
7587 consumedOperands = 2;
7588 break;
7589 case glslang::EOpSubBorrow:
7590 opCode = spv::OpISubBorrow;
7591 typeId = builder.makeStructResultType(typeId0, typeId0);
7592 consumedOperands = 2;
7593 break;
7594 case glslang::EOpUMulExtended:
7595 opCode = spv::OpUMulExtended;
7596 typeId = builder.makeStructResultType(typeId0, typeId0);
7597 consumedOperands = 2;
7598 break;
7599 case glslang::EOpIMulExtended:
7600 opCode = spv::OpSMulExtended;
7601 typeId = builder.makeStructResultType(typeId0, typeId0);
7602 consumedOperands = 2;
7603 break;
7604 case glslang::EOpBitfieldExtract:
7605 if (isUnsigned)
7606 opCode = spv::OpBitFieldUExtract;
7607 else
7608 opCode = spv::OpBitFieldSExtract;
7609 break;
7610 case glslang::EOpBitfieldInsert:
7611 opCode = spv::OpBitFieldInsert;
7612 break;
7613
7614 case glslang::EOpFma:
7615 libCall = spv::GLSLstd450Fma;
7616 break;
7617 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007618 {
7619 libCall = spv::GLSLstd450FrexpStruct;
7620 assert(builder.isPointerType(typeId1));
7621 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007622 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007623 if (width == 16)
7624 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7625 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
Rex Xu470026f2017-03-29 17:12:40 +08007626 if (builder.getNumComponents(operands[0]) == 1)
7627 frexpIntType = builder.makeIntegerType(width, true);
7628 else
John Kessenich8985fc92020-03-03 10:25:07 -07007629 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
7630 builder.getNumComponents(operands[0]));
Rex Xu470026f2017-03-29 17:12:40 +08007631 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7632 consumedOperands = 1;
7633 }
John Kessenich55e7d112015-11-15 21:33:39 -07007634 break;
7635 case glslang::EOpLdexp:
7636 libCall = spv::GLSLstd450Ldexp;
7637 break;
7638
Rex Xu574ab042016-04-14 16:53:07 +08007639 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007640 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007641
John Kessenich66011cb2018-03-06 16:12:04 -07007642 case glslang::EOpSubgroupBroadcast:
7643 case glslang::EOpSubgroupBallotBitExtract:
7644 case glslang::EOpSubgroupShuffle:
7645 case glslang::EOpSubgroupShuffleXor:
7646 case glslang::EOpSubgroupShuffleUp:
7647 case glslang::EOpSubgroupShuffleDown:
7648 case glslang::EOpSubgroupClusteredAdd:
7649 case glslang::EOpSubgroupClusteredMul:
7650 case glslang::EOpSubgroupClusteredMin:
7651 case glslang::EOpSubgroupClusteredMax:
7652 case glslang::EOpSubgroupClusteredAnd:
7653 case glslang::EOpSubgroupClusteredOr:
7654 case glslang::EOpSubgroupClusteredXor:
7655 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007656 case glslang::EOpSubgroupPartitionedAdd:
7657 case glslang::EOpSubgroupPartitionedMul:
7658 case glslang::EOpSubgroupPartitionedMin:
7659 case glslang::EOpSubgroupPartitionedMax:
7660 case glslang::EOpSubgroupPartitionedAnd:
7661 case glslang::EOpSubgroupPartitionedOr:
7662 case glslang::EOpSubgroupPartitionedXor:
7663 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7664 case glslang::EOpSubgroupPartitionedInclusiveMul:
7665 case glslang::EOpSubgroupPartitionedInclusiveMin:
7666 case glslang::EOpSubgroupPartitionedInclusiveMax:
7667 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7668 case glslang::EOpSubgroupPartitionedInclusiveOr:
7669 case glslang::EOpSubgroupPartitionedInclusiveXor:
7670 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7671 case glslang::EOpSubgroupPartitionedExclusiveMul:
7672 case glslang::EOpSubgroupPartitionedExclusiveMin:
7673 case glslang::EOpSubgroupPartitionedExclusiveMax:
7674 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7675 case glslang::EOpSubgroupPartitionedExclusiveOr:
7676 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich66011cb2018-03-06 16:12:04 -07007677 return createSubgroupOperation(op, typeId, operands, typeProxy);
7678
Rex Xu9d93a232016-05-05 12:30:44 +08007679 case glslang::EOpSwizzleInvocations:
7680 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7681 libCall = spv::SwizzleInvocationsAMD;
7682 break;
7683 case glslang::EOpSwizzleInvocationsMasked:
7684 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7685 libCall = spv::SwizzleInvocationsMaskedAMD;
7686 break;
7687 case glslang::EOpWriteInvocation:
7688 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7689 libCall = spv::WriteInvocationAMD;
7690 break;
7691
7692 case glslang::EOpMin3:
7693 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7694 if (isFloat)
7695 libCall = spv::FMin3AMD;
7696 else {
7697 if (isUnsigned)
7698 libCall = spv::UMin3AMD;
7699 else
7700 libCall = spv::SMin3AMD;
7701 }
7702 break;
7703 case glslang::EOpMax3:
7704 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7705 if (isFloat)
7706 libCall = spv::FMax3AMD;
7707 else {
7708 if (isUnsigned)
7709 libCall = spv::UMax3AMD;
7710 else
7711 libCall = spv::SMax3AMD;
7712 }
7713 break;
7714 case glslang::EOpMid3:
7715 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7716 if (isFloat)
7717 libCall = spv::FMid3AMD;
7718 else {
7719 if (isUnsigned)
7720 libCall = spv::UMid3AMD;
7721 else
7722 libCall = spv::SMid3AMD;
7723 }
7724 break;
7725
7726 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007727 if (typeProxy == glslang::EbtFloat16)
7728 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007729 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7730 libCall = spv::InterpolateAtVertexAMD;
7731 break;
Chao Chen3c366992018-09-19 11:41:59 -07007732
Daniel Kochdb32b242020-03-17 20:42:47 -04007733 case glslang::EOpReportIntersection:
Chao Chenb50c02e2018-09-19 11:42:24 -07007734 typeId = builder.makeBoolType();
Daniel Kochdb32b242020-03-17 20:42:47 -04007735 opCode = spv::OpReportIntersectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007736 break;
Daniel Kochdb32b242020-03-17 20:42:47 -04007737 case glslang::EOpTrace:
Daniel Kochdb32b242020-03-17 20:42:47 -04007738 builder.createNoResultOp(spv::OpTraceRayKHR, operands);
Ashwin Leleff1783d2018-10-22 16:41:44 -07007739 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04007740 case glslang::EOpExecuteCallable:
Daniel Kochdb32b242020-03-17 20:42:47 -04007741 builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007742 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007743
7744 case glslang::EOpRayQueryInitialize:
Torosdagli06c2eee2020-03-19 11:09:57 -04007745 builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
7746 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007747 case glslang::EOpRayQueryTerminate:
Torosdagli06c2eee2020-03-19 11:09:57 -04007748 builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
7749 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007750 case glslang::EOpRayQueryGenerateIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007751 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
7752 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007753 case glslang::EOpRayQueryConfirmIntersection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007754 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
7755 return 0;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007756 case glslang::EOpRayQueryProceed:
Torosdagli06c2eee2020-03-19 11:09:57 -04007757 typeId = builder.makeBoolType();
7758 opCode = spv::OpRayQueryProceedKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007759 break;
7760 case glslang::EOpRayQueryGetIntersectionType:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007761 typeId = builder.makeUintType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007762 opCode = spv::OpRayQueryGetIntersectionTypeKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007763 break;
7764 case glslang::EOpRayQueryGetRayTMin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007765 typeId = builder.makeFloatType(32);
7766 opCode = spv::OpRayQueryGetRayTMinKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007767 break;
7768 case glslang::EOpRayQueryGetRayFlags:
Torosdagli06c2eee2020-03-19 11:09:57 -04007769 typeId = builder.makeIntType(32);
7770 opCode = spv::OpRayQueryGetRayFlagsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007771 break;
7772 case glslang::EOpRayQueryGetIntersectionT:
Neslisah Torosdagli50a72282020-03-20 18:23:27 -04007773 typeId = builder.makeFloatType(32);
Torosdagli06c2eee2020-03-19 11:09:57 -04007774 opCode = spv::OpRayQueryGetIntersectionTKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007775 break;
7776 case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007777 typeId = builder.makeIntType(32);
7778 opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007779 break;
7780 case glslang::EOpRayQueryGetIntersectionInstanceId:
Torosdagli06c2eee2020-03-19 11:09:57 -04007781 typeId = builder.makeIntType(32);
7782 opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007783 break;
7784 case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
Torosdagli06c2eee2020-03-19 11:09:57 -04007785 typeId = builder.makeIntType(32);
7786 opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007787 break;
7788 case glslang::EOpRayQueryGetIntersectionGeometryIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007789 typeId = builder.makeIntType(32);
7790 opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007791 break;
7792 case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
Torosdagli06c2eee2020-03-19 11:09:57 -04007793 typeId = builder.makeIntType(32);
7794 opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007795 break;
7796 case glslang::EOpRayQueryGetIntersectionBarycentrics:
Torosdagli06c2eee2020-03-19 11:09:57 -04007797 typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
7798 opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007799 break;
7800 case glslang::EOpRayQueryGetIntersectionFrontFace:
Torosdagli06c2eee2020-03-19 11:09:57 -04007801 typeId = builder.makeBoolType();
7802 opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007803 break;
7804 case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
Torosdagli06c2eee2020-03-19 11:09:57 -04007805 typeId = builder.makeBoolType();
7806 opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007807 break;
7808 case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007809 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7810 opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007811 break;
7812 case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007813 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7814 opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007815 break;
7816 case glslang::EOpRayQueryGetWorldRayDirection:
Torosdagli06c2eee2020-03-19 11:09:57 -04007817 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7818 opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007819 break;
7820 case glslang::EOpRayQueryGetWorldRayOrigin:
Torosdagli06c2eee2020-03-19 11:09:57 -04007821 typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
7822 opCode = spv::OpRayQueryGetWorldRayOriginKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007823 break;
7824 case glslang::EOpRayQueryGetIntersectionObjectToWorld:
Torosdagli06c2eee2020-03-19 11:09:57 -04007825 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007826 opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007827 break;
7828 case glslang::EOpRayQueryGetIntersectionWorldToObject:
Torosdagli06c2eee2020-03-19 11:09:57 -04007829 typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
Torosdagli06c2eee2020-03-19 11:09:57 -04007830 opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
Neslisah Torosdaglicea93842020-03-25 08:13:32 -04007831 break;
Chao Chen3c366992018-09-19 11:41:59 -07007832 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7833 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7834 return 0;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007835 case glslang::EOpCooperativeMatrixMulAdd:
7836 opCode = spv::OpCooperativeMatrixMulAddNV;
7837 break;
John Kessenicha28f7a72019-08-06 07:00:58 -06007838#endif // GLSLANG_WEB
John Kessenich140f3df2015-06-26 16:58:36 -06007839 default:
7840 return 0;
7841 }
7842
7843 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007844 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007845 // Use an extended instruction from the standard library.
7846 // Construct the call arguments, without modifying the original operands vector.
7847 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7848 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007849 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007850 } else if (opCode == spv::OpDot && !isFloat) {
7851 // int dot(int, int)
7852 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7853 const int componentCount = builder.getNumComponents(operands[0]);
7854 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7855 builder.setPrecision(mulOp, precision);
7856 id = builder.createCompositeExtract(mulOp, typeId, 0);
7857 for (int i = 1; i < componentCount; ++i) {
7858 builder.setPrecision(id, precision);
John Kessenich5de15a22019-12-26 10:56:54 -07007859 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
t.jungb16bea82018-11-15 10:21:36 +01007860 }
John Kessenich2359bd02015-12-06 19:29:11 -07007861 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007862 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007863 case 0:
7864 // should all be handled by visitAggregate and createNoArgOperation
7865 assert(0);
7866 return 0;
7867 case 1:
7868 // should all be handled by createUnaryOperation
7869 assert(0);
7870 return 0;
7871 case 2:
7872 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7873 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007874 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007875 // anything 3 or over doesn't have l-value operands, so all should be consumed
7876 assert(consumedOperands == operands.size());
7877 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007878 break;
7879 }
7880 }
7881
John Kessenichb9197c82019-08-11 07:41:45 -06007882#ifndef GLSLANG_WEB
John Kessenich55e7d112015-11-15 21:33:39 -07007883 // Decode the return types that were structures
7884 switch (op) {
7885 case glslang::EOpAddCarry:
7886 case glslang::EOpSubBorrow:
7887 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7888 id = builder.createCompositeExtract(id, typeId0, 0);
7889 break;
7890 case glslang::EOpUMulExtended:
7891 case glslang::EOpIMulExtended:
7892 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7893 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7894 break;
7895 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007896 {
7897 assert(operands.size() == 2);
7898 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7899 // "exp" is floating-point type (from HLSL intrinsic)
7900 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7901 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7902 builder.createStore(member1, operands[1]);
7903 } else
7904 // "exp" is integer type (from GLSL built-in function)
7905 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7906 id = builder.createCompositeExtract(id, typeId0, 0);
7907 }
John Kessenich55e7d112015-11-15 21:33:39 -07007908 break;
7909 default:
7910 break;
7911 }
John Kessenichb9197c82019-08-11 07:41:45 -06007912#endif
John Kessenich55e7d112015-11-15 21:33:39 -07007913
John Kessenich32cfd492016-02-02 12:37:46 -07007914 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007915}
7916
Rex Xu9d93a232016-05-05 12:30:44 +08007917// Intrinsics with no arguments (or no return value, and no precision).
7918spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007919{
Jeff Bolz36831c92018-09-05 10:11:41 -05007920 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
John Kessenich8985fc92020-03-03 10:25:07 -07007921 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
7922 spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007923
7924 switch (op) {
John Kessenich140f3df2015-06-26 16:58:36 -06007925 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007926 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007927 if (glslangIntermediate->usingVulkanMemoryModel()) {
7928 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7929 spv::MemorySemanticsOutputMemoryKHRMask |
7930 spv::MemorySemanticsAcquireReleaseMask);
7931 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7932 } else {
7933 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7934 }
John Kessenich82979362017-12-11 04:02:24 -07007935 } else {
7936 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7937 spv::MemorySemanticsWorkgroupMemoryMask |
7938 spv::MemorySemanticsAcquireReleaseMask);
7939 }
John Kessenich140f3df2015-06-26 16:58:36 -06007940 return 0;
7941 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007942 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7943 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007944 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007945 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007946 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7947 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007948 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007949 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007950 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7951 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007952 return 0;
7953 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007954 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7955 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007956 return 0;
John Kessenich3dd1ce52019-10-17 07:08:40 -06007957#ifndef GLSLANG_WEB
7958 case glslang::EOpMemoryBarrierAtomicCounter:
7959 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7960 spv::MemorySemanticsAcquireReleaseMask);
7961 return 0;
7962 case glslang::EOpMemoryBarrierImage:
7963 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7964 spv::MemorySemanticsAcquireReleaseMask);
7965 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007966 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007967 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007968 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007969 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007970 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007971 case glslang::EOpDeviceMemoryBarrier:
7972 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7973 spv::MemorySemanticsImageMemoryMask |
7974 spv::MemorySemanticsAcquireReleaseMask);
7975 return 0;
7976 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7977 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7978 spv::MemorySemanticsImageMemoryMask |
7979 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007980 return 0;
7981 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007982 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7983 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007984 return 0;
7985 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007986 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7987 spv::MemorySemanticsWorkgroupMemoryMask |
7988 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007989 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007990 case glslang::EOpSubgroupBarrier:
7991 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7992 spv::MemorySemanticsAcquireReleaseMask);
7993 return spv::NoResult;
7994 case glslang::EOpSubgroupMemoryBarrier:
7995 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7996 spv::MemorySemanticsAcquireReleaseMask);
7997 return spv::NoResult;
7998 case glslang::EOpSubgroupMemoryBarrierBuffer:
7999 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
8000 spv::MemorySemanticsAcquireReleaseMask);
8001 return spv::NoResult;
8002 case glslang::EOpSubgroupMemoryBarrierImage:
8003 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
8004 spv::MemorySemanticsAcquireReleaseMask);
8005 return spv::NoResult;
8006 case glslang::EOpSubgroupMemoryBarrierShared:
8007 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
8008 spv::MemorySemanticsAcquireReleaseMask);
8009 return spv::NoResult;
John Kessenichf8d1d742019-10-21 06:55:11 -06008010
8011 case glslang::EOpEmitVertex:
8012 builder.createNoResultOp(spv::OpEmitVertex);
8013 return 0;
8014 case glslang::EOpEndPrimitive:
8015 builder.createNoResultOp(spv::OpEndPrimitive);
8016 return 0;
8017
John Kessenich66011cb2018-03-06 16:12:04 -07008018 case glslang::EOpSubgroupElect: {
8019 std::vector<spv::Id> operands;
8020 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
8021 }
Rex Xu9d93a232016-05-05 12:30:44 +08008022 case glslang::EOpTime:
8023 {
8024 std::vector<spv::Id> args; // Dummy arguments
8025 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
8026 return builder.setPrecision(id, precision);
8027 }
Daniel Kochdb32b242020-03-17 20:42:47 -04008028 case glslang::EOpIgnoreIntersection:
8029 builder.createNoResultOp(spv::OpIgnoreIntersectionKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008030 return 0;
Daniel Kochdb32b242020-03-17 20:42:47 -04008031 case glslang::EOpTerminateRay:
8032 builder.createNoResultOp(spv::OpTerminateRayKHR);
Chao Chenb50c02e2018-09-19 11:42:24 -07008033 return 0;
Torosdagli06c2eee2020-03-19 11:09:57 -04008034 case glslang::EOpRayQueryInitialize:
8035 builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
8036 return 0;
8037 case glslang::EOpRayQueryTerminate:
8038 builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
8039 return 0;
8040 case glslang::EOpRayQueryGenerateIntersection:
8041 builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
8042 return 0;
8043 case glslang::EOpRayQueryConfirmIntersection:
8044 builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
8045 return 0;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05008046 case glslang::EOpBeginInvocationInterlock:
8047 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
8048 return 0;
8049 case glslang::EOpEndInvocationInterlock:
8050 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
8051 return 0;
8052
Jeff Bolzba6170b2019-07-01 09:23:23 -05008053 case glslang::EOpIsHelperInvocation:
8054 {
8055 std::vector<spv::Id> args; // Dummy arguments
Rex Xubb7307b2019-07-15 14:57:20 +08008056 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
8057 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
8058 return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
Jeff Bolzba6170b2019-07-01 09:23:23 -05008059 }
8060
amhagan91fb0092019-07-10 21:14:38 -04008061 case glslang::EOpReadClockSubgroupKHR: {
8062 std::vector<spv::Id> args;
8063 args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
8064 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8065 builder.addCapability(spv::CapabilityShaderClockKHR);
8066 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8067 }
8068
8069 case glslang::EOpReadClockDeviceKHR: {
8070 std::vector<spv::Id> args;
8071 args.push_back(builder.makeUintConstant(spv::ScopeDevice));
8072 builder.addExtension(spv::E_SPV_KHR_shader_clock);
8073 builder.addCapability(spv::CapabilityShaderClockKHR);
8074 return builder.createOp(spv::OpReadClockKHR, typeId, args);
8075 }
John Kessenich3dd1ce52019-10-17 07:08:40 -06008076#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008077 default:
John Kessenich155d3512019-08-08 23:29:20 -06008078 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008079 }
John Kessenich155d3512019-08-08 23:29:20 -06008080
8081 logger->missingFunctionality("unknown operation with no arguments");
8082
8083 return 0;
John Kessenich140f3df2015-06-26 16:58:36 -06008084}
8085
8086spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
8087{
John Kessenich2f273362015-07-18 22:34:27 -06008088 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06008089 spv::Id id;
8090 if (symbolValues.end() != iter) {
8091 id = iter->second;
8092 return id;
8093 }
8094
8095 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06008096 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
Daniel Kochdb32b242020-03-17 20:42:47 -04008097 auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06008098 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06008099 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06008100 if (forcedType.second != spv::NoType)
8101 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06008102
Rex Xuc884b4a2016-06-29 15:03:44 +08008103 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008104 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
8105 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
8106 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenicha28f7a72019-08-06 07:00:58 -06008107#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008108 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
John Kessenichb9197c82019-08-11 07:41:45 -06008109 if (symbol->getQualifier().hasComponent())
8110 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
8111 if (symbol->getQualifier().hasIndex())
8112 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
Chao Chen3c366992018-09-19 11:41:59 -07008113#endif
John Kessenich6c292d32016-02-15 20:58:50 -07008114 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07008115 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich91e4aa52016-07-07 17:46:42 -06008116 // atomic counters use this:
8117 if (symbol->getQualifier().hasOffset())
8118 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008119 }
8120
scygan2c864272016-05-18 18:09:17 +02008121 if (symbol->getQualifier().hasLocation())
8122 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07008123 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07008124 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07008125 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06008126 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07008127 }
John Kessenich140f3df2015-06-26 16:58:36 -06008128 if (symbol->getQualifier().hasSet())
8129 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07008130 else if (IsDescriptorResource(symbol->getType())) {
8131 // default to 0
8132 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
8133 }
John Kessenich140f3df2015-06-26 16:58:36 -06008134 if (symbol->getQualifier().hasBinding())
8135 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06008136 else if (IsDescriptorResource(symbol->getType())) {
8137 // default to 0
8138 builder.addDecoration(id, spv::DecorationBinding, 0);
8139 }
John Kessenich6c292d32016-02-15 20:58:50 -07008140 if (symbol->getQualifier().hasAttachment())
8141 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06008142 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07008143 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07008144 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008145 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07008146 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
8147 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
8148 builder.addDecoration(id, spv::DecorationXfbStride, stride);
8149 }
8150 if (symbol->getQualifier().hasXfbOffset())
8151 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06008152 }
8153
John Kessenichb9197c82019-08-11 07:41:45 -06008154 // add built-in variable decoration
8155 if (builtIn != spv::BuiltInMax) {
8156 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
8157 }
8158
8159#ifndef GLSLANG_WEB
Rex Xu1da878f2016-02-21 20:59:01 +08008160 if (symbol->getType().isImage()) {
8161 std::vector<spv::Decoration> memory;
John Kessenich8985fc92020-03-03 10:25:07 -07008162 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
8163 glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08008164 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07008165 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08008166 }
8167
John Kessenich5611c6d2018-04-05 11:25:02 -06008168 // nonuniform
8169 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
8170
chaoc0ad6a4e2016-12-19 16:29:34 -08008171 if (builtIn == spv::BuiltInSampleMask) {
8172 spv::Decoration decoration;
8173 // GL_NV_sample_mask_override_coverage extension
8174 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08008175 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08008176 else
8177 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07008178 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08008179 if (decoration != spv::DecorationMax) {
Jason Macnakdbd4c3c2019-07-12 14:33:02 -07008180 builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
chaoc0ad6a4e2016-12-19 16:29:34 -08008181 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
8182 }
8183 }
chaoc771d89f2017-01-13 01:10:53 -08008184 else if (builtIn == spv::BuiltInLayer) {
8185 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06008186 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008187 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08008188 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
8189 builder.addExtension(spv::E_SPV_NV_viewport_array2);
8190 }
John Kessenichb41bff62017-08-11 13:07:17 -06008191 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008192 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
8193 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08008194 builder.addCapability(spv::CapabilityShaderStereoViewNV);
8195 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
8196 }
8197 }
8198
chaoc6e5acae2016-12-20 13:28:52 -08008199 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07008200 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08008201 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08008202 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
8203 }
Chao Chen9eada4b2018-09-19 11:39:56 -07008204 if (symbol->getQualifier().pervertexNV) {
8205 builder.addDecoration(id, spv::DecorationPerVertexNV);
8206 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
8207 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
8208 }
chaoc0ad6a4e2016-12-19 16:29:34 -08008209
John Kessenich5d610ee2018-03-07 18:05:55 -07008210 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
8211 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
8212 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
8213 symbol->getType().getQualifier().semanticName);
8214 }
8215
John Kessenich7015bd62019-08-01 03:28:08 -06008216 if (symbol->isReference()) {
John Kessenich8985fc92020-03-03 10:25:07 -07008217 builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
8218 spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008219 }
John Kessenichb9197c82019-08-11 07:41:45 -06008220#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008221
John Kessenich140f3df2015-06-26 16:58:36 -06008222 return id;
8223}
8224
John Kessenicha28f7a72019-08-06 07:00:58 -06008225#ifndef GLSLANG_WEB
Chao Chen3c366992018-09-19 11:41:59 -07008226// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
8227void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
8228{
8229 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07008230 if (qualifier.perPrimitiveNV) {
8231 // Need to add capability/extension for fragment shader.
8232 // Mesh shader already adds this by default.
8233 if (glslangIntermediate->getStage() == EShLangFragment) {
8234 builder.addCapability(spv::CapabilityMeshShadingNV);
8235 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8236 }
Chao Chen3c366992018-09-19 11:41:59 -07008237 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008238 }
Chao Chen3c366992018-09-19 11:41:59 -07008239 if (qualifier.perViewNV)
8240 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
8241 if (qualifier.perTaskNV)
8242 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
8243 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07008244 if (qualifier.perPrimitiveNV) {
8245 // Need to add capability/extension for fragment shader.
8246 // Mesh shader already adds this by default.
8247 if (glslangIntermediate->getStage() == EShLangFragment) {
8248 builder.addCapability(spv::CapabilityMeshShadingNV);
8249 builder.addExtension(spv::E_SPV_NV_mesh_shader);
8250 }
Chao Chen3c366992018-09-19 11:41:59 -07008251 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07008252 }
Chao Chen3c366992018-09-19 11:41:59 -07008253 if (qualifier.perViewNV)
8254 builder.addDecoration(id, spv::DecorationPerViewNV);
8255 if (qualifier.perTaskNV)
8256 builder.addDecoration(id, spv::DecorationPerTaskNV);
8257 }
8258}
8259#endif
8260
John Kessenich55e7d112015-11-15 21:33:39 -07008261// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07008262// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07008263//
8264// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
8265//
8266// Recursively walk the nodes. The nodes form a tree whose leaves are
8267// regular constants, which themselves are trees that createSpvConstant()
8268// recursively walks. So, this function walks the "top" of the tree:
8269// - emit specialization constant-building instructions for specConstant
8270// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04008271spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07008272{
John Kessenich7cc0e282016-03-20 00:46:02 -06008273 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07008274
qining4f4bb812016-04-03 23:55:17 -04008275 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07008276 if (! node.getQualifier().specConstant) {
8277 // hand off to the non-spec-constant path
8278 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
8279 int nextConst = 0;
John Kessenich8985fc92020-03-03 10:25:07 -07008280 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
8281 node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
8282 nextConst, false);
John Kessenich6c292d32016-02-15 20:58:50 -07008283 }
8284
8285 // We now know we have a specialization constant to build
8286
Ricardo Garcia232ba0d2020-06-03 15:52:55 +02008287 // Extra capabilities may be needed.
8288 if (node.getType().contains8BitInt())
8289 builder.addCapability(spv::CapabilityInt8);
8290 if (node.getType().contains16BitFloat())
8291 builder.addCapability(spv::CapabilityFloat16);
8292 if (node.getType().contains16BitInt())
8293 builder.addCapability(spv::CapabilityInt16);
8294 if (node.getType().contains64BitInt())
8295 builder.addCapability(spv::CapabilityInt64);
8296 if (node.getType().containsDouble())
8297 builder.addCapability(spv::CapabilityFloat64);
8298
John Kessenichd94c0032016-05-30 19:29:40 -06008299 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04008300 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
8301 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
8302 std::vector<spv::Id> dimConstId;
8303 for (int dim = 0; dim < 3; ++dim) {
8304 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
8305 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07008306 if (specConst) {
8307 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
8308 glslangIntermediate->getLocalSizeSpecId(dim));
8309 }
qining4f4bb812016-04-03 23:55:17 -04008310 }
8311 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
8312 }
8313
8314 // An AST node labelled as specialization constant should be a symbol node.
8315 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
8316 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008317 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04008318 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04008319 // Traverse the constant constructor sub tree like generating normal run-time instructions.
8320 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
8321 // will set the builder into spec constant op instruction generating mode.
8322 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008323 result = accessChainLoad(sub_tree->getType());
8324 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04008325 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008326 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05008327 } else {
8328 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05008329 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07008330 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07008331 builder.addName(result, sn->getName().c_str());
8332 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07008333 }
qining4f4bb812016-04-03 23:55:17 -04008334
8335 // Neither a front-end constant node, nor a specialization constant node with constant union array or
8336 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04008337 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04008338 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07008339}
8340
John Kessenich140f3df2015-06-26 16:58:36 -06008341// Use 'consts' as the flattened glslang source of scalar constants to recursively
8342// build the aggregate SPIR-V constant.
8343//
8344// If there are not enough elements present in 'consts', 0 will be substituted;
8345// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
8346//
John Kessenich8985fc92020-03-03 10:25:07 -07008347spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
8348 const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06008349{
8350 // vector of constants for SPIR-V
8351 std::vector<spv::Id> spvConsts;
8352
8353 // Type is used for struct and array constants
8354 spv::Id typeId = convertGlslangToSpvType(glslangType);
8355
8356 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008357 glslang::TType elementType(glslangType, 0);
8358 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04008359 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06008360 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06008361 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06008362 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04008363 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06008364 } else if (glslangType.isCoopMat()) {
8365 glslang::TType componentType(glslangType.getBasicType());
8366 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06008367 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06008368 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
8369 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04008370 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06008371 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06008372 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
8373 bool zero = nextConst >= consts.size();
8374 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008375 case glslang::EbtInt:
8376 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
8377 break;
8378 case glslang::EbtUint:
8379 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
8380 break;
8381 case glslang::EbtFloat:
8382 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8383 break;
8384 case glslang::EbtBool:
8385 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
8386 break;
8387#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008388 case glslang::EbtInt8:
8389 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
8390 break;
8391 case glslang::EbtUint8:
8392 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
8393 break;
8394 case glslang::EbtInt16:
8395 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
8396 break;
8397 case glslang::EbtUint16:
8398 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
8399 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008400 case glslang::EbtInt64:
8401 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
8402 break;
8403 case glslang::EbtUint64:
8404 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
8405 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008406 case glslang::EbtDouble:
8407 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
8408 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008409 case glslang::EbtFloat16:
8410 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
8411 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008412#endif
John Kessenich140f3df2015-06-26 16:58:36 -06008413 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008414 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008415 break;
8416 }
8417 ++nextConst;
8418 }
8419 } else {
8420 // we have a non-aggregate (scalar) constant
8421 bool zero = nextConst >= consts.size();
8422 spv::Id scalar = 0;
8423 switch (glslangType.getBasicType()) {
John Kessenich39697cd2019-08-08 10:35:51 -06008424 case glslang::EbtInt:
8425 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
8426 break;
8427 case glslang::EbtUint:
8428 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
8429 break;
8430 case glslang::EbtFloat:
8431 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8432 break;
8433 case glslang::EbtBool:
8434 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
8435 break;
8436#ifndef GLSLANG_WEB
John Kessenich66011cb2018-03-06 16:12:04 -07008437 case glslang::EbtInt8:
8438 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
8439 break;
8440 case glslang::EbtUint8:
8441 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
8442 break;
8443 case glslang::EbtInt16:
8444 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
8445 break;
8446 case glslang::EbtUint16:
8447 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
8448 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08008449 case glslang::EbtInt64:
8450 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
8451 break;
8452 case glslang::EbtUint64:
8453 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8454 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008455 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07008456 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06008457 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08008458 case glslang::EbtFloat16:
8459 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
8460 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06008461 case glslang::EbtReference:
8462 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
8463 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
8464 break;
John Kessenich39697cd2019-08-08 10:35:51 -06008465#endif
Jeff Bolz04d73732019-05-31 13:06:01 -05008466 case glslang::EbtString:
8467 scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
8468 break;
John Kessenich140f3df2015-06-26 16:58:36 -06008469 default:
John Kessenich55e7d112015-11-15 21:33:39 -07008470 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06008471 break;
8472 }
8473 ++nextConst;
8474 return scalar;
8475 }
8476
8477 return builder.makeCompositeConstant(typeId, spvConsts);
8478}
8479
John Kessenich7c1aa102015-10-15 13:29:11 -06008480// Return true if the node is a constant or symbol whose reading has no
8481// non-trivial observable cost or effect.
8482bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8483{
8484 // don't know what this is
8485 if (node == nullptr)
8486 return false;
8487
8488 // a constant is safe
8489 if (node->getAsConstantUnion() != nullptr)
8490 return true;
8491
8492 // not a symbol means non-trivial
8493 if (node->getAsSymbolNode() == nullptr)
8494 return false;
8495
8496 // a symbol, depends on what's being read
8497 switch (node->getType().getQualifier().storage) {
8498 case glslang::EvqTemporary:
8499 case glslang::EvqGlobal:
8500 case glslang::EvqIn:
8501 case glslang::EvqInOut:
8502 case glslang::EvqConst:
8503 case glslang::EvqConstReadOnly:
8504 case glslang::EvqUniform:
8505 return true;
8506 default:
8507 return false;
8508 }
qining25262b32016-05-06 17:25:16 -04008509}
John Kessenich7c1aa102015-10-15 13:29:11 -06008510
8511// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008512// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008513// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008514// Return true if trivial.
8515bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8516{
8517 if (node == nullptr)
8518 return false;
8519
John Kessenich84cc15f2017-05-24 16:44:47 -06008520 // count non scalars as trivial, as well as anything coming from HLSL
8521 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008522 return true;
8523
John Kessenich7c1aa102015-10-15 13:29:11 -06008524 // symbols and constants are trivial
8525 if (isTrivialLeaf(node))
8526 return true;
8527
8528 // otherwise, it needs to be a simple operation or one or two leaf nodes
8529
8530 // not a simple operation
8531 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8532 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8533 if (binaryNode == nullptr && unaryNode == nullptr)
8534 return false;
8535
8536 // not on leaf nodes
8537 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8538 return false;
8539
8540 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8541 return false;
8542 }
8543
8544 switch (node->getAsOperator()->getOp()) {
8545 case glslang::EOpLogicalNot:
8546 case glslang::EOpConvIntToBool:
8547 case glslang::EOpConvUintToBool:
8548 case glslang::EOpConvFloatToBool:
8549 case glslang::EOpConvDoubleToBool:
8550 case glslang::EOpEqual:
8551 case glslang::EOpNotEqual:
8552 case glslang::EOpLessThan:
8553 case glslang::EOpGreaterThan:
8554 case glslang::EOpLessThanEqual:
8555 case glslang::EOpGreaterThanEqual:
8556 case glslang::EOpIndexDirect:
8557 case glslang::EOpIndexDirectStruct:
8558 case glslang::EOpLogicalXor:
8559 case glslang::EOpAny:
8560 case glslang::EOpAll:
8561 return true;
8562 default:
8563 return false;
8564 }
8565}
8566
8567// Emit short-circuiting code, where 'right' is never evaluated unless
8568// the left side is true (for &&) or false (for ||).
John Kessenich8985fc92020-03-03 10:25:07 -07008569spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
8570 glslang::TIntermTyped& right)
John Kessenich7c1aa102015-10-15 13:29:11 -06008571{
8572 spv::Id boolTypeId = builder.makeBoolType();
8573
8574 // emit left operand
8575 builder.clearAccessChain();
8576 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008577 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008578
8579 // Operands to accumulate OpPhi operands
8580 std::vector<spv::Id> phiOperands;
8581 // accumulate left operand's phi information
8582 phiOperands.push_back(leftId);
8583 phiOperands.push_back(builder.getBuildPoint()->getId());
8584
8585 // Make the two kinds of operation symmetric with a "!"
8586 // || => emit "if (! left) result = right"
8587 // && => emit "if ( left) result = right"
8588 //
8589 // TODO: this runtime "not" for || could be avoided by adding functionality
8590 // to 'builder' to have an "else" without an "then"
8591 if (op == glslang::EOpLogicalOr)
8592 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8593
8594 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008595 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008596
8597 // emit right operand as the "then" part of the "if"
8598 builder.clearAccessChain();
8599 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008600 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008601
8602 // accumulate left operand's phi information
8603 phiOperands.push_back(rightId);
8604 phiOperands.push_back(builder.getBuildPoint()->getId());
8605
8606 // finish the "if"
8607 ifBuilder.makeEndIf();
8608
8609 // phi together the two results
8610 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8611}
8612
John Kessenicha28f7a72019-08-06 07:00:58 -06008613#ifndef GLSLANG_WEB
Rex Xu9d93a232016-05-05 12:30:44 +08008614// Return type Id of the imported set of extended instructions corresponds to the name.
8615// Import this set if it has not been imported yet.
8616spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8617{
8618 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8619 return extBuiltinMap[name];
8620 else {
Rex Xu51596642016-09-21 18:56:12 +08008621 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008622 spv::Id extBuiltins = builder.import(name);
8623 extBuiltinMap[name] = extBuiltins;
8624 return extBuiltins;
8625 }
8626}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008627#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008628
John Kessenich140f3df2015-06-26 16:58:36 -06008629}; // end anonymous namespace
8630
8631namespace glslang {
8632
John Kessenich68d78fd2015-07-12 19:28:10 -06008633void GetSpirvVersion(std::string& version)
8634{
John Kessenich9e55f632015-07-15 10:03:39 -06008635 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008636 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008637 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008638 version = buf;
8639}
8640
John Kessenicha372a3e2017-11-02 22:32:14 -06008641// For low-order part of the generator's magic number. Bump up
8642// when there is a change in the style (e.g., if SSA form changes,
8643// or a different instruction sequence to do something gets used).
8644int GetSpirvGeneratorVersion()
8645{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008646 // return 1; // start
8647 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008648 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008649 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008650 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008651 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8652 // versions 4 and 6 each generate OpArrayLength as it has long been done
John Kessenich31c33702019-11-02 21:26:40 -06008653 // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
8654 return 8; // switch to new dead block eliminator; use OpUnreachable
John Kessenicha372a3e2017-11-02 22:32:14 -06008655}
8656
John Kessenich140f3df2015-06-26 16:58:36 -06008657// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008658void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008659{
8660 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008661 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008662 if (out.fail())
8663 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008664 for (int i = 0; i < (int)spirv.size(); ++i) {
8665 unsigned int word = spirv[i];
8666 out.write((const char*)&word, 4);
8667 }
8668 out.close();
8669}
8670
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008671// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008672void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008673{
John Kessenich155d3512019-08-08 23:29:20 -06008674#ifndef GLSLANG_WEB
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008675 std::ofstream out;
8676 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008677 if (out.fail())
8678 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008679 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008680 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008681 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008682 if (varName != nullptr) {
8683 out << "\t #pragma once" << std::endl;
8684 out << "const uint32_t " << varName << "[] = {" << std::endl;
8685 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008686 const int WORDS_PER_LINE = 8;
8687 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8688 out << "\t";
8689 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8690 const unsigned int word = spirv[i + j];
8691 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8692 if (i + j + 1 < (int)spirv.size()) {
8693 out << ",";
8694 }
8695 }
8696 out << std::endl;
8697 }
Flavio15017db2017-02-15 14:29:33 -08008698 if (varName != nullptr) {
8699 out << "};";
8700 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008701 out.close();
John Kessenich155d3512019-08-08 23:29:20 -06008702#endif
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008703}
8704
John Kessenich140f3df2015-06-26 16:58:36 -06008705//
8706// Set up the glslang traversal
8707//
John Kessenich4e11b612018-08-30 16:56:59 -06008708void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008709{
Lei Zhang17535f72016-05-04 15:55:59 -04008710 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008711 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008712}
8713
John Kessenich4e11b612018-08-30 16:56:59 -06008714void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008715 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008716{
John Kessenich140f3df2015-06-26 16:58:36 -06008717 TIntermNode* root = intermediate.getTreeRoot();
8718
8719 if (root == 0)
8720 return;
8721
John Kessenich4e11b612018-08-30 16:56:59 -06008722 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008723 if (options == nullptr)
8724 options = &defaultOptions;
8725
John Kessenich4e11b612018-08-30 16:56:59 -06008726 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008727
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008728 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008729 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008730 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008731 it.dumpSpv(spirv);
8732
GregFfb03a552018-03-29 11:49:14 -06008733#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008734 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8735 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008736 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8737 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008738 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008739 prelegalization = false;
8740 }
John Kessenich717c80a2018-08-23 15:17:10 -06008741
John Kessenich4e11b612018-08-30 16:56:59 -06008742 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008743 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008744
John Kessenich717c80a2018-08-23 15:17:10 -06008745 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008746 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008747
GregFcd1f1692017-09-21 18:40:22 -06008748#endif
8749
John Kessenich4e11b612018-08-30 16:56:59 -06008750 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008751}
8752
8753}; // end namespace glslang